Dummynet freebsd что это

Dummynet freebsd что это

Наступил такой интересный момент — порнуха у пользователей зарезана, приличная часть сайтов развлекательного назначения тоже заразана, баннеры режутся, короче, зарезано очень и очень много. А вот потребление траффика больше не снижается 🙁 Народ припугнутый «драконовскими» методами, типа по 200 мегабайт инета на каждого протянул недолго — месяца полтора — потом просекли, что если попросить то включают анлим 🙁 (и, ввиду, дырявости моей памяти, забывают выключить. ) Короче, было принято решение ограничить скорость работы с инетом. Мера проверенная ещё на старой работе, и действенная (но там было вообще жестоко — 2kB/s). Можно было ограничить скорость работы по протоколу HTTP средствами SQUID, но были отдельные грамотные товарищщи, которые тянули всякий хлам по ftp — поэтому нужно было зарезать все протоколы, для этого подходил DUMMYNET.
Сказано — сделано. Для начала правим конфиг ядра, туда надо добавить поддержку DUMMYNET, файрволла.

После чего пересобираем ядро. Если у Вас до этого ядро было без файрволла — то будте готовы к тому, что после перезагрузки он заработает, и в нём будет только одно правило:

Если файрволл есть, то в него надо добавить следующие строки (в самом верху):

Где переменные:
$ — /sbin/ipfw — собственно IPFW
$ — 192.168.20.0 — внутренняя сеть
$ — 24 — маска сети
$ — 222.222.222.222 — внешний IP сервака
Вкратце о том, что всё это делает: первые две pipe для того, чтобы не ограничивалась скорость работы с самим серваком — на нём лежит почта, кое какие файлы, и естественно от того, что почта принимается со скоростью 64k никто в восторге не будет, тем более, что внутри офиса довольно большой документооборот идёт именно по почте. Затем запускаем цикл по всем IP-шникам (я сделал не одно правило, а целую кучу (больше 200!), чтобы была большая гибкость в использовании — есть люди которым не надо ничего ограничивать, те же IT-шники, начальство. ) В цикле (он специально сделан не с начала диапазона и не до конца — у меня вверху и внизу висят серваки — их ограничивать не надо вообще) добавляются именованые каналы и в зависимости от IP выставляется скорость — в примере приведено для 2-х адресов — 192.168.20.13 и 192.168.20.22 — можно сделать не такое жёсткое деление, используя не else , а elif . Выглядеть это будет так:

В этом случае имеем всем скорость 64k, для адресов
192.168.20.13 и 192.168.20.22 — 100 мегабит,
192.168.20.18 и 192.168.20.38 — 128k,
192.168.20.55, 192.168.20.159 и 192.168.20.188 — 256k.
После чего перезапускаем файрволл следующей командой:

(при условии, что конфиг файрволла у Вас в файле /etc/rc.firewall ). Для просмотра существующих pipe пользуемся командой

Только не забудьте & в конце — иначе может так получиться, что старые правила сбросятся, а новые не успеют примениться (в момент запуска этой команды соединение по ssh почти всегда обрывается.)

размещено: 2005-11-29,
последнее обновление: 2006-05-18,
автор: lissyara

PomidorOFF, 2006-07-26 в 16:38:06

src/share/examples/ipfw/change_rules.sh
стандартный скрипт перезапуска фаервола, ssh не рвется если правила написаны верно, и не разрывается соединение. 😉

paha, 2006-09-21 в 13:10:16

а так не проще?
/etc/rc.d/ipfw forcerestart . ни разу SSh не рвалось.

ztaz, 2006-10-20 в 3:53:48

А не проще ничего не выводить при обновлении правил?
FwCMD=»/sbin/ipfw -q»
Тогда ничего и не будет разрывать.

Про обрывание соединений при изменении настроек ipfw тоже пережмвал, пока не узнал об
/usr/ports/sysutils/screen/
Даже не представляю теперь как жиз без этого раньше 🙂

Trias, 2007-02-10 в 13:07:30

еще достаточно удобно делать ограничения используя возможности IPFW2, а точнее ipfw table

в 5.х и 6.х уже по дефолту а 4.х надо пересобирать ядро.

ipfw add 2 pipe 1 ip from any to table\(1\) in
pipe 1 config bw 300Kbit/s mask dst-ip 0xffffffff

ipfw add 2 pipe 2 ip from table\(1\) to any
pipe 2 config bw 300Kbit/s mask src-ip 0xffffffff

если пользователь заносится в таблицу 1 то он будет иметь ограничение по 300/300 на каждого. уберем ( mask dst-ip 0xffffffff ) в pipe и будет на всех в таблице =)

Andrey74, 2007-04-15 в 21:01:05

А после elif не нужен then?

Zaq, 2007-05-14 в 14:45:30

ну и не плохо добовлять in/out для правил, дабы избежать превращения 128 в 64, может это конечно только при наличии natd но всёже более чёткое правило будет
pipe 1 ip from 10.0.0.109 to any in
pipe 1 ip from any to 10.0.0.109 out

pipe 1 config bw 128kbit/s mask src-ip 0xffffffff
pipe 2 config bw 128kbit/s mask dst-ip 0xffffffff
правда, зачем плодить пайпы ))

Читайте также:  Картридж для hp laserjet 4515

Попробовал, действительно теребует после elif then. Фря 6.2

ma4o, 2007-09-12 в 14:34:40

Вот что искал нигде не мог внятного ответа найти про «sh /etc/rc.firewall &», точнее про амперсанд в конце. А то по удаленке перегружаешь правила и все колом встает пока в локаль не залезешь. Да и сама статья полезная.

ADvise, 2008-04-29 в 6:25:58

Господа, я так понимаю, это все мы проделываем ручками.

скажем, вот хочу так, дошел юзер до предела, скажем 200 мб выкачал, и все, хочу ему или инет отрезать или скорость такой сделать, что ему все желание отбивает пользоваться инетом. но скажем я на месте бываю раз в три месяца.

скажем, по юзеру можно узнать, сколько он накачал, но как правила на лету править. или подставлять в командной строке адрес и в крон?

Из статьи лишь понятно, что мы просто жестко определяем скорость конкретным пользователям. и все.

может сделать следующее:
1. смотрим число — 1 число, разрешаем максимальную допустимую скорость всем.
2. не 1 число, смотрим статистику юзера, >200 мб накачал, вызываем файрвол с параметром (адрес юзера), урезаем скорость.
3. и можно ему об этом еще письмом сообщить, что мол лимит достигнут имейте совесть, тра-ля-ля.

Алексей, 2008-09-02 в 9:52:57

А если юзвери ходят в инет через прозрачный проксик. а остальной трафик через NAT. Ограничить таким образом ширину канала для них возможно?

Croaker, 2008-09-08 в 15:46:14

В первом конфиге есть строка
$ add pipe 2 ip from $ to
а сама переменная IpIn не опеределена

vesper, 2009-03-14 в 1:17:01

А для DUMMYNET В FreeBSD 7.1 ничего не будет? О:-) там много нового появилось.. а инфы мало

dr_alf, 2009-05-21 в 10:20:30

$ pipe $i config bw 64000 bit/s
у меня с пробелом неработало) я особенный или в разных версиях фри, разные требования? ))))

Народ, статья все еще актуальна? Например, для 8-ки.

Морфин, 2010-03-25 в 7:34:14

А можно же сделать
rdr on $int_if proto tcp from \\\»192.168.20.0/24\\\» to any port www -> 127.0.0.1 port 3128
и аналогично для FTP и скомпилить SQUID под поддержку pf

Товарищщи!, 2010-04-01 в 21:58:29

Товарищщи! Это поля для ввода комментариев к статье, а не для вопросов. Сюда пишите найденные баги, или какие-то фичи 🙂
Для вопросов есть форум!

День добрый.
Есть ВОТ это:
$ add pipe 2 ip from $ to $/$
$ pipe 2 config bw 100Mbit/s
Для чего? Что за IpIn?

Мфынф, 2013-10-22 в 17:12:15

АФТАР ЕБЛАН СОСИ ХУЙ. 11111111111

АЛЕКС КЕДА ЛОХЪ


2014-07-27, lissyara
gmirror
Удалённое создание софтверного зеркала средствами gmirror, на диске разбитом с использованием gpart. Использование меток дисков для монтирования разделов. 2013-08-20, zentarim
Scan+Print server FreeBSD 9
Настройка сервера печати и сервера сканирования под управлением операционной системы FreebSD 9 для МФУ Canon PIXMA MP540 2011-11-20, BlackCat
Разъём на WiFi-карту
Делаем съёмной несъёмную антену на WiFi-карте путём установки ВЧ-разъёма 2011-09-14, manefesto
Настройка git+gitosis
Настройка системы контроля версия исходного кода в связке git+gitosis+ssh 2011-08-14, zentarim
Wi-FI роутер + DHCP + DNS
Настройка Wi-Fi роутера на Freebsd 8 + DNS сервер + DHCP сервер: чтобы Wi-Fi клиенты были в одной подсети с проводными, проводные и беспроводные клиенты получали адреса автоматически по DHCP, кэширующ 2011-06-15, -ZG-
Охранная система на FreeBSD+LPT
В этой статье описана попытка реализации простой охранной системы на базе FreeBSD с подключением к ней охранных устройтсв на LPT порт и видеорегистрацией. 2011-03-13, terminus
ng_nat
Описание работы ng_nat, практическое использование, достоинства и недостатки в сравнении с ipfw nat 2011-02-20, Капитан
Nagios+Digitemp
Статья описывает создание системы оповещения о превышении температуры в специальных помещениях на основе Nagios с использованием программы Digitemp. 2011-02-17, Le1
Zyxel Configuration
Скрипт для массового изменения конфига свичей Zyxel. Берет из файла iplist список ip-шек, заходит последовательно на каждый и выполняет комманды из файла commands, записывая происходящее в лог файл. 2011-02-16, fox
hast carp zfs ucarp cluster
HAST (Highly Available Storage), CARP, UCARP, ZFS, Cluster настройка и одаптация плюс личные размышления… 2011-02-04, BlackCat
Восстановление ZFS
История о том, как был восстановлен развалившийся RAIDZ ZFS-пул (перешедший в FAULTED) с помощью скотча и подручных средств. Или о том, какие приключения ожидают тех, кто не делает резервных копий. 2011-02-03, Капитан
1-Wire
Статья описывает самостоятельное изготовление контроллера DS9097 для съёма показаний с датчиков температуры DS1820 с помощью программы Digitemp. 2011-01-28, Капитан
Температура в серверной
Статья описывает построение системы наблюдения за температурой в помещении серверной с использованием программы Digitemp и выводом графиков в MRTG 2011-01-21, m4rkell
Syslog server
Как то буквально на днях, у нас завалилось, что то в еве) или не в еве не суть. Суть в том, что когда захотели снять логи с хостов esx обнаружили, что хранят эти негодяи логии только за последнии сутк 2011-01-07, lissyara
Canon/gphotofs
Монтирование цифровых фотоаппаратов Canon (PTP) как файловой системы, автоматизация этого процесса через события devd и внешние скрипты. 2010-12-13, Al
IPSec
Описание принципов работы IPSEC и способов аутентификации. 2010-12-07, manefesto
FreeBSD on flash
Было принято решении переехать на USB Flash и установить минимальный джентельменский набор для работы своего роутера. Делаем =) 2010-12-05, Fomalhaut
root ZFS, GPT
Инструкция по установке FreeBSD с использованием в качестве таблицы разделов GPT и в качестве основной файловой системы — ZFS 2010-09-05, Cancer
Настройка аудиоплеера на ximp3
Цели: Простенький аудиоплеер, для того что бы тетя продавец в магазине утром пришла нажала на кнопку Power и заиграла в зале музыка, так же был доступ по сети, общая шара куда можно заливать музыку, к
вверх

Читайте также:  Драйвера для принтера канон лазер бас
Статистика сайта
Сейчас на сайте находится: 10 чел.
За последние 30 мин было: 55 человек
За сегодня было
1153 показов,
299 уникальных IP

Этот информационный блок появился по той простой причине, что многие считают нормальным, брать чужую информацию не уведомляя автора (что не так страшно), и не оставляя линк на оригинал и автора — что более существенно. Я не против распространения информации — только за. Только условие простое — извольте подписывать автора, и оставлять линк на оригинальную страницу в виде прямой, активной, нескриптовой, незакрытой от индексирования, и не запрещенной для следования роботов ссылки.
Если соизволите поставить автора в известность — то вообще почёт вам и уважение.

Источник

Klara Inc.

Posted on July 13, 2020 by officeklara

Dummynet: The Better Way to Build FreeBSD Networks

Dummynet: The Better Way of Building FreeBSD Networks

Dummynet is the FreeBSD traffic shaper, packet scheduler, and network emulator. Dummynet allows you to emulate a whole set of network environments in a straight-forward way. It has the ability to model delay, packet loss, and can act as a traffic shaper and policer. Dummynet is roughly equivalent to netem in Linux, but we have found that dummynet is easier to integrate and provides much more consistent results.

Network emulation is a technique for creating virtual networks to simulate the conditions of real networks in a more controlled lab-like environment. Using network emulation helps speed up testing and development by allowing the user to duplicate and replicate their findings. Emulation combined with traffic shaping allows you to build interesting networks that can place limits on how much of the available capacity is used by one type of application or flow. With network emulation we can create strict environments for different types of traffic, limiting bandwidth or artifically increasing round trip time so they don’t overwhelm the network.

Network emulation gives you the power to test your applications and services in network conditions with vastly different from the ones you currently have. This means that developers can get the full hellish experience of using a weak edge signal or the terrible interactivity of geostationary satellite delay. With emulation you can test a field deployment from the comfort of a warm lab. Network conditions vary greatly and many types of network (especially those that use radio somewhere along the path) can vary in capacity and delay based on the time of day or even the weather.

Using dummynet on FreeBSD

Dummynet is a feature of the ipfw firewall. It exposes three rule types that let you control how traffic is managed once it is fed into the emulator: pipes, schedulers, and queues. A pipe emulates a network link, you can set characteristics on a pipe and they will be enforced by the emulator. This allows you to limit the available bandwidth or impose additional delay on packets that traverse the pipe. Queues and scheduler rules allow us to use dummynet as a traffic shaper, packets fed into a queue are classified by their 5-tuple (protocol, source and destination IP and port) and scheduled differently based on the algorithm and parameters provided.

To start using dummynet you need to load the ipfw and dummynet kernel modules. You should always experiment with firewall rules on a test machine, ideally one where you can easily get access to the console when you lock yourself out.

When testing rules, it can be helpful to change the ipfw default rule to accept rather than reject all traffic. This helps avoid lock out and removes some of the more perplexing forwarding issues. You can do this before loading the kernel module with the kenv utility, or by adding a very late rule that allows all traffic through.

ipfw is configured with a ruleset, a list of numbered rules from 1 to 65535. Packets are evaluated against the ruleset until a rule either drops the packet or passes the packet through. The first rule that matches is the winner and further processing stops. In ipfw rules you can use the actions deny or drop to stop packets and allow, accept, pass or permit to allow packets through.

When configuring network emulation (and firewalls generally) it is very important to have a good idea how you are going to test that the rules you have written are performing the actions you intend (and hopefully no other actions).

When performing network emulation you are primarily concerned with two parameters, the bandwidth available and the path delay. For testing delay you can use the hardy ping(8) command. ping will tell you the round trip time it experiences, helping you see how much delay there is in the network. Sometimes more usefully it will report all ICMP error messages it receives. This can be really helpful when an errant rule is rejecting traffic.

To measure the bandwidth available with the emulator (and normally before) you can use the iperf3(1) tool available from ports or packages. iperf3 is the third version of the iperf tool and it offers a whole host of features, and there are some public servers available that allow you to perform measurements to them. iperf3 is more automatable than the older iperf2 was and now offers json output so it can easily be integrated into automated test workflows.

The table below shows typical bandwidth and delay values for different types of network you may wish to emulate:

When configuring network emulation with ipfw using pipes, the pipe emulates a link with the given bandwidth, delay, loss, burst sizes and buffering characteristics. To use pipes with ipfw you first have to configure them, then add rules that feed traffic to the pipe. Pipes are typically used to enforce network conditions on an entire subnetwork, but you can use any of the filters in ipfw to control which traffic goes into the emulated link. Pipes are referred to by a number, which should not be confused with the ipfw rule numbers. You may wish to define a specific range of numbers that are used for pipes, and not create firewall rules with the same numbers, to avoid confusion. The ipfw pipe config command will use the default values for any parameter you don’t specify when creating the pipe.

For these tests you can use a FreeBSD host machine with bhyve running a FreeBSD guest VM. Add the guest’s tap interface as a member to a bridge on the host.

The bridge has the address 10.0.4.1 while the VM will have the address 10.0.4.2. Configuring bhyve is left as an exercise to the reader.

Setting up Network Emulation

Before you do anything, use ping and iperf3 to measure the network characteristics from the VM guest to the host in your test network (you could do this to a public host you know, such as 1.1.1.1 or to one of the iperf3 test servers listed here).

To run a bandwidth test you run iperf3 in server mode on your VM host:

and run a default 10 second test from your guest VM to the host:

That looks like a great network, there is a ton of capacity (it is just a guest speaking to the VM host after all) and the delay is below 1ms and hardly varies at all. This setup might exist between machine in a data center or your house, but it isn’t anything like what you will see from the Internet edge to the core.

Around 20 milliseconds of total delay (the round trip time that ping reports) is typical from many locations to services on the Internet. Lets set up pipes to delay all of the traffic from the guest VM by 10ms in each direction:

With these commands all traffic from the guest to the hosts bridge is fed into pipe 1 and any traffic from the host to the bridge is fed into pipe 2. Each pipe only models one direction of the link, this can be very helpful if you are modelling a cellular network that has delays that are different in each direction. Lets test this config to see if it has the desired effect:

The delay is what we expect. Now lets configure a bandwidth limit in our network:

This has set a limit, but the TCP transfer that iperf3 is doing is not able to utilize the full link capacity. This is because there is not enough buffering configured on the link. Sizing buffers is a complicated field of study, but as a general rule you want one full Bandwith Delay Product (BDP, the bandwidth times the total delay) of buffering. If we configure this for the forward link it does much better:

With that change you have a guest VM that with network conditions similar to a VDSL line. This has only scratched the surface of some of what can be done with dummynet as a network emulator. Dummynet can also be used as a packet scheduler and is able to make very interesting and useful networks.

Tom Jones is an Internet Researcher and FreeBSD developer that works on improving the core protocols that drive the Internet. He is a contributor to open standards in the IETF and is enthusiastic about using FreeBSD as a platform to experiment with new networking ideas as they progress towards standardisation.

Источник

Поделиться с друзьями
КомпСовет
Adblock
detector