hardware error hack code microcontroller linux FreeBSD windows

chemical experiments
I just repair my home PC power supply i think will be no loud sound …
У нас эксперимент по химии (и физике) ремонт блока питания от компа, гуляем пока во дворе ждем результата опыта.
chemical-test

Image watermark php code (for Bitrix 12 … 16) Битрикс 1С водяной знак на дополнительные
фото png jpg.


Исправленый вариант change code if imageSX imageSY function returns 0
( image object create from jpeg ..)
Вообще как то принято если публикуется код программы в нем должно быть парочка ошибок или вообще закладка которая например позволяет спам рассылать ну или стереть чего, а потом вежливо попросить так евро 500 за восстановление. Ну тут в порядке исключения проверенный кусочек кода.До php5.6 version 7 no test.

<p>bitrix/php_interface/init.php<br> [php autolinks="1" classname="myclass" collapse="1" firstline="1" gutter="true" highlight="1-3,6,9" htmlscript="false" light="false" padlinenumbers="false" smarttabs="true" tabsize="4" toolbar="true" title="bitrix init.php"]<br> <blockquote><code><br> <!--?php &lt;br ?--> //Подключаем файл с функциями<br> require_once ($_SERVER["DOCUMENT_ROOT"]. "/bitrix/php_interface/watermark.php");<br> //Создание элемента<br> AddEventHandler("iblock", "OnBeforeIBlockElementAdd",array("CWatermark", "ImageAdd"));<br> //Изменение элемента<br> AddEventHandler("iblock", "OnBeforeIBlockElementUpdate",array("CWatermark", "ImageUpdate"));</code></p><p>// обработчик события регистрации (use Russian letters for username only but trusted method against spammers is shut down then hack kill 'em all with axe)<br> AddEventHandler("main", "OnBeforeUserRegister", "OnBeforeUserRegisterHandler");<br> // обработчик события обновления данных пользователем<br> AddEventHandler("main", "OnBeforeUserUpdate", "OnBeforeUserRegisterHandler");<br> function OnBeforeUserRegisterHandler($args) {<br> if(isset($_POST['c']) &amp;&amp; $_POST['c'] != $_POST['s']) {<br> $GLOBALS['APPLICATION']-&gt;ThrowException('Произошла внутренняя ошибка, попробуйте еще раз');<br> return false;<br> }</p><p>if (!preg_match("/^[а-яА-Я]+$/ui", $args['NAME'])) {<br> if(empty($args['NAME'])) {<br> $GLOBALS['APPLICATION']-&gt;ThrowException('Имя обязательное поле');<br> return false;<br> }else{<br> $GLOBALS['APPLICATION']-&gt;ThrowException('Имя может состоять только из русских букв');<br> return false;<br> }<br> }</p><p>if (!preg_match("/^[а-яА-Я]+$/ui", $args['LAST_NAME'])) {<br> if(empty($args['LAST_NAME'])) {<br> $GLOBALS['APPLICATION']-&gt;ThrowException('Фамилия обязательное поле');<br> return false;<br> }else{<br> $GLOBALS['APPLICATION']-&gt;ThrowException('Фамилия может состоять только из русских букв');<br> return false;<br> }<br> .<br> }</p><p>return true;<br> }<br> [/php]</p><p>..<br> watermark.php<br> [code collapse="true"]<br> <!--?php class CWatermark { // chmod 1777 ./tmp ./bitrix/tmp ./upload ./upload/tmp // св-ва инфоблока-настроить вн вид списка - вывести все поля -не обязательно но проще отладка // ./.upload/tmp сохраняется оригинал картинки и включены 2 файла лога - пишется $arFields //Срабатываем при создании элемента function ImageAdd(&amp;$arFields) { //Указываем нужные ИБ, допустим ваш каталог имеет ID 1 + секция в других инфоблоках 529 if ($arFields["IBLOCK_ID"] == 4 or $arFields["IBLOCK_SECTION"][0]== 529) { CWatermark::log_array($arFields); // убрать после отладки if (!empty($arFields["PREVIEW_PICTURE"]["tmp_name"])) { //CWatermark::PostWaterMark($arFields["PREVIEW_PICTURE"]["tmp_name"]); } //Если заполнено детальное изображение if (!empty($arFields["DETAIL_PICTURE"]["tmp_name"])) { // //foreach($arFields[PROPERTY_VALUES][28] as &amp;$file): // foreach($arFields["DETAIL_PICTURE"] as &amp;$file): // CAllFile::ResizeImage( // $file, // array("width" =&gt; "200", "height" =&gt; "200"),&lt;br ?--> // BX_RESIZE_IMAGE_PROPORTIONAL);<br> // endforeach;<br> CWatermark::PostWaterMark($arFields["DETAIL_PICTURE"]["tmp_name"]);<br> }<br> // $tok="bbb";<br> //$arFields[NAME] = $tok; //имя присваиваем из свойства<br> //if ($arFields[PROPERTY_VALUES][69][0] == "") {$arFields[ACTIVE] = "N";} //aктивность также в зависимости от свойства<br> //<br> // $arFields[PROPERTY_VALUES][2][n0][VALUE]["name"]=$arFields[DETAIL_PICTURE]["name"];<br> // $arFields[PROPERTY_VALUES][2][n0][VALUE]["type"]=$arFields[DETAIL_PICTURE]["type"];<br> // $arFields[PROPERTY_VALUES][2][n0][VALUE]["tmp_name"]=$arFields[DETAIL_PICTURE]["tmp_name"];<br> // $arFields[PROPERTY_VALUES][2][n0][VALUE][error]=$arFields[DETAIL_PICTURE][error];<br> // $arFields[PROPERTY_VALUES][2][n0][VALUE][size]=$arFields[DETAIL_PICTURE][size];<br> // $arFields[PROPERTY_VALUES][2][n0][VALUE]["COPY_FILE"] = "Y";<br> // $arFields[TAGS] = trim($tok, " ;:\/*.,");<br> $f=fopen($_SERVER["DOCUMENT_ROOT"]."/logc1.txt","w");<br> fwrite($f, print_r($arFields,true));//печатаем в файл результирующий массив для проверки<br> fclose($f);</code></p><p>CWatermark::log_array($arFields); // убрать после отладки.<br> //Тут наносим на дополнительное фото, 2 это ID свойства ИБ //for jcarusel<br> if(isset($arFields["PROPERTY_VALUES"]["53"])) {</p><p>foreach ($arFields["PROPERTY_VALUES"]["53"] as $key=&gt;$moreimg)<br> {<br> CWatermark::PostWaterMark($arFields["PROPERTY_VALUES"]["53"][$key]['VALUE']['tmp_name']);<br> }<br> }<br> if(isset($arFields["PROPERTY_VALUES"]["54"])) {<br> foreach ($arFields["PROPERTY_VALUES"]["54"] as $key=&gt;$moreimg)<br> {<br> CWatermark::PostWaterMark($arFields["PROPERTY_VALUES"]["54"][$key]['VALUE']['tmp_name']);<br> }<br> }<br> if(isset($arFields["PROPERTY_VALUES"]["56"])) {</p><p>foreach ($arFields["PROPERTY_VALUES"]["56"] as $key=&gt;$moreimg)<br> {<br> CWatermark::PostWaterMark($arFields["PROPERTY_VALUES"]["56"][$key]['VALUE']['tmp_name']);<br> }<br> }<br> if(isset($arFields["PROPERTY_VALUES"]["61"])) {<br> foreach ($arFields["PROPERTY_VALUES"]["61"] as $key=&gt;$moreimg)<br> {<br> CWatermark::PostWaterMark($arFields["PROPERTY_VALUES"]["61"][$key]['VALUE']['tmp_name']);<br> }<br> }</p><p>//REAL_PICTURE //Оригинал<br> //CWatermark::PostWaterMark($arFields["PROPERTY_VALUES"]["54"]["n0"]["VALUE"]["tmp_name"]);<br> //CWatermark::PostWaterMark($arFields[PROPERTY_VALUES][2]["xkey0"][VALUE][tmp_name]); //bx16 no extension for temp picture!!!</p><p>/* [n0] =&gt; Array<br> (<br> [VALUE] =&gt; Array<br> (<br> [name] =&gt;<br> [type] =&gt;<br> [tmp_name] =&gt;<br> [error] =&gt; 4<br> [size] =&gt; 0<br> )</p><p>)<br> */</p><p>// foreach($arFields["PROPERTY_VALUES"]["2"] as &amp;$file):<br> // CAllFile::ResizeImage(<br> // $file,<br> // array("width" =&gt; "200", "height" =&gt; "200"),<br> // BX_RESIZE_IMAGE_PROPORTIONAL);<br> // endforeach;</p><p>}<br> }</p><p>//Срабатываем при изменение элемента<br> // only catalog infoblock id=1<br> /* [IBLOCK_SECTION] =&gt; Array<br> (<br> [0] =&gt; 529<br> )<br> */</p><p>function ImageUpdate(&amp;$arFields) {<br> //То же самое, указываем ID ИБ<br> if ($arFields["IBLOCK_ID"] == 4 or $arFields["IBLOCK_SECTION"][0]== 529) {<br> //Если заполнено изображение анонса<br> // if(!empty($arFields["PREVIEW_PICTURE"]["tmp_name"])){<br> //CWatermark::PostWaterMark($arFields["PREVIEW_PICTURE"]["tmp_name"]);<br> // }<br> //Если заполнено детальное изображение<br> // if (!empty($arFields["DETAIL_PICTURE"]["tmp_name"])) {<br> // CWatermark::PostWaterMark($arFields["DETAIL_PICTURE"]["tmp_name"]);<br> //}<br> //Тут наносим на дополнительное фото, 2 это ID свойства ИБ 53 54 56 61 edit insert correct //for jcarusel<br> $f=fopen($_SERVER["DOCUMENT_ROOT"]."/logc2.txt","w");<br> fwrite($f, print_r($arFields,true));//печатаем в файл результирующий массив для проверки<br> fclose($f);<br> CWatermark::log_array($arFields); // убрать после отладки.<br> if(isset($arFields["PROPERTY_VALUES"]["53"])) {</p><p>foreach ($arFields["PROPERTY_VALUES"]["53"] as $key=&gt;$moreimg)<br> {<br> CWatermark::PostWaterMark($arFields["PROPERTY_VALUES"]["53"][$key]['VALUE']['tmp_name']);<br> }<br> }<br> if(isset($arFields["PROPERTY_VALUES"]["54"])) {<br> foreach ($arFields["PROPERTY_VALUES"]["54"] as $key=&gt;$moreimg)<br> {<br> CWatermark::PostWaterMark($arFields["PROPERTY_VALUES"]["54"][$key]['VALUE']['tmp_name']);<br> }<br> }<br> if(isset($arFields["PROPERTY_VALUES"]["56"])) {</p><p>foreach ($arFields["PROPERTY_VALUES"]["56"] as $key=&gt;$moreimg)<br> {<br> CWatermark::PostWaterMark($arFields["PROPERTY_VALUES"]["56"][$key]['VALUE']['tmp_name']);<br> }<br> }<br> if(isset($arFields["PROPERTY_VALUES"]["61"])) {<br> foreach ($arFields["PROPERTY_VALUES"]["61"] as $key=&gt;$moreimg)<br> {<br> CWatermark::PostWaterMark($arFields["PROPERTY_VALUES"]["61"][$key]['VALUE']['tmp_name']);<br> }<br> }<br> //REAL_PICTURE //Оригинал<br> }<br> }<br> //functions *********************************<br> // записывает все что передадут в /bitrix/log.txt</p><p>function log_array() {<br> $arArgs = func_get_args();<br> $sResult = '';<br> foreach($arArgs as $arArg) {<br> $sResult .= "\n\n".print_r($arArg, true);<br> }</p><p>if(!defined('LOG_FILENAME')) {<br> define('LOG_FILENAME', $_SERVER['DOCUMENT_ROOT'].'/bitrix/log.txt');<br> }<br> AddMessage2Log($sResult, 'log_array -&gt; ');<br> }</p><p>function PostWaterMark(&amp;$image) {<br> //echo ("<br> <pre>");<br> //print_r ($key);<br> //print_r ($arFields);<br> //echo ("</pre><br> ");<br> if ($image == NULL) return true;<br> //Получаем папку для загрузок<br> $_upload_dir = COption::GetOptionString("main", "upload_dir");</p><p>// imagesX imagesY FAIL!! if image create from jpg jpeg (truecolor? &gt;600 pixel??)<br> // getimagesize return array - Correctly!<br> //ошибка - imagesx imagesy выдают 0 если картинка jpeg truecolor?<br> $size = getimagesize($image);<br> $ratio = $size[0]/$size[1]; // width/height<br> if( $ratio &gt; 1) {<br> $width = $size[0];<br> $height = $size[1];<br> }<br> else {<br> $width = ceil($size[1]*$ratio); //for resize watermark before add<br> $height = ceil($size[0]*$ratio); //picture w - h change &amp; smaller size - more proportional<br> }<br> if ($size[mime] == 'image/jpeg') { $resultImage = imagecreatefromjpeg($image); }<br> if ($size[mime] == 'image/png') { $resultImage = imagecreatefrompng($image); }<br> if ($resultImage == NULL) return true; // source picture jpeg or png<br> #$src = imagecreatefromstring(file_get_contents($fn));<br> #$dst = imagecreatetruecolor($width,$height);<br> #imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);<br> #imagedestroy($src);<br> #imagepng($dst,$target_filename_here); // adjust format as needed<br> #imagedestroy($dst);<br> imagealphablending($resultImage, true); //adobe photoshop flatten image<br> //отладка отключить если работает debug comment this after<br> $imgprop = array("width" =&gt; $width, "height" =&gt; $height, "lay"=&gt;$size[2],"dim"=&gt;$size[3],"bits"=&gt;$size[bits],"channels"=&gt;$size[channels],"mime"=&gt;$size[mime] );<br> $f3=fopen($_SERVER["DOCUMENT_ROOT"]."/logc3.txt","w");<br> fwrite($f3, print_r($imgprop,true));//печатаем в файл результирующий массив для проверки<br> fwrite($f3, print_r($size[3],true));//печатаем в файл результирующий массив для проверки<br> fclose($f3);<br> //Создаем временную картинку //пригодилось для копии только<br> $_image = $_SERVER['DOCUMENT_ROOT'] . "/" . $_upload_dir . "/tmp/" . md5(microtime()) . ".jpg";<br> imagejpeg($resultImage, $_image, 100); //save original<br> //Узнаем размеры загружаемой картинки<br> //ошибка - imagesx imagesy выдают 0 если картинка jpeg truecolor?<br> // change - getimagesize(filename) get correct width &amp; height in [0] [1] !<br> $imagesizeW = $width ; //imagesx($resultImage);<br> $imagesizeH = $height ; //imagesy($resultImage);</p><p>//Открываем картинку для наложения<br> //Но сначала масштабируем водяной знак, т.к. размеры картинок у нас разные<br> //Узнаем размер будущего водяного знака (8% //35% от ширины картинки)<br> // if ($imagesizeW = 0) { $imagesizeW=$wight; $imagesizeH=$height; } imagesx imagesy do not work!<br> $watermarkSize = ceil(46 * $imagesizeW / 100);<br> $watermarkSizeH = ceil(46 * $imagesizeH / 100);<br> #imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$watermarkSize,$watermarkSizeH);<br> // ну опять хрень - прозрачный png эта ф-ция не масштабирует!!!<br> //fuck.. png with transparent (at white 255,255,255 color) do not resize with ResizeImageGet<br> //see manual Bitrix! to prevent black pictures w/o transparency<br> $wmTargetArray = CFile::ResizeImageGet(<br> 63,<br> array("width" =&gt; $watermarkSize, "height" =&gt; $watermarkSizeH),<br> BX_RESIZE_IMAGE_EXACT,<br> true,<br> array()<br> );<br> //2181 //63 - это ID watermark.png, который лежит в файловой системе Битрикса b_file ID SUBDIR FILE_NAME (закинуть в медиабиблиотеку)<br> //select * from b_file where module_id!="iblock" (in medialibrary)</p><p>//$wmTarget = $_SERVER['DOCUMENT_ROOT'] . "/bitrix/php_interface/watermark.png";<br> $wmTarget = $_SERVER['DOCUMENT_ROOT'] . $wmTargetArray["src"];</p><p>//Загружаем PNG ватермарка<br> // $finalWaterMarkImage<br> // resize transparent png (color 255,255,255 is transparent)<br> $src = imagecreatefrompng($wmTarget);<br> $srcWidth = imagesx($src); //if png work correctly<br> $srcHeight = imagesy($src);<br> $finalWaterMarkImage = imagecreatetruecolor($watermarkSize,$watermarkSizeH);<br> imagecolortransparent($finalWaterMarkImage, imagecolorallocatealpha($finalWaterMarkImage, 0, 0, 0, 112)); //127 full transparency<br> imagealphablending($finalWaterMarkImage, false);<br> imagesavealpha($finalWaterMarkImage, true);<br> //setTransparency($new_image,$image_source); function 50 lines up</p><p>// $transparencyIndex = imagecolortransparent($src);<br> // $transparencyColor = array('red' =&gt; 255, 'green' =&gt; 255, 'blue' =&gt; 255);<br> // if ($transparencyIndex &gt;= 0) {<br> // $transparencyColor = imagecolorsforindex($src, $transparencyIndex);<br> // }<br> // $transparencyIndex = imagecolorallocate($finalWaterMarkImage, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']);<br> // imagefill($finalWaterMarkImage, 0, 0, $transparencyIndex);<br> // imagecolortransparent($finalWaterMarkImage, $transparencyIndex);<br> // $black = imagecolorallocate($finalWaterMarkImage, 0, 0, 0);<br> // $white = imagecolorallocate($finalWaterMarkImage, 255, 255, 255);<br> // imagecolortransparent($finalWaterMarkImage, $black); black after resize, in original white...<br> // resize with transparent color http://php.net/manual/ru/function.imagecolortransparent.php see comment 3<br> //imagecopyresampled($new_image, $image_source, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);<br> imagecopyresampled($finalWaterMarkImage,$src,0,0,0,0,$watermarkSize,$watermarkSizeH,$srcWidth,$srcHeight);<br> // imagecolortransparent($finalWaterMarkImage, $transparencyIndex);</p><p>// comment if correcte<br> $_image1 = $_SERVER['DOCUMENT_ROOT'] . "/" . $_upload_dir . "/tmp/" . md5(microtime()) . ".png";<br> imagepng($finalWaterMarkImage, $_image1, 0); //debug save watermark img w resize see correct resize &amp; transparent color</p><p>//Узнаем размеры картинки водяного знака<br> $finalWaterMarkWidth = imagesx($finalWaterMarkImage);<br> $finalWaterMarkHeight = imagesy($finalWaterMarkImage);</p><p>//Пихаем водяной знак в нижний правый угол картинки<br> //Узнаем какой ставить отступ с краев (4% 15% от ширины картинки)</p><p>$watermarkMargin = ceil(15 * $imagesizeW / 100);<br> $im_prop1= array("fw" =&gt; $finalWaterMarkWidth, "fh" =&gt; $finalWaterMarkHeight, "w" =&gt; $imagesizeW, "h" =&gt; $imagesizeH, "m" =&gt; $watermarkMargin, "width" =&gt; $width, "height" =&gt; $height, "ww" =&gt; $watermarkSize , "wh" =&gt; $watermarkSizeH );</p><p>AddMessage2Log($image, 'nameofimage -&gt; ');<br> CWatermark::log_array($im_prop1); // убрать после отладки.<br> CWatermark::log_array($size); // убрать после отладки.<br> imagecopy($resultImage,$finalWaterMarkImage,$imagesizeW - $finalWaterMarkWidth - $watermarkMargin, $imagesizeH - $finalWaterMarkHeight - $watermarkMargin, 0, 0, $finalWaterMarkWidth, $finalWaterMarkHeight);</p><p>imagealphablending($resultImage, false);<br> imagesavealpha($resultImage, true);<br> imagejpeg($resultImage, $image, 100); //result $image overwrite original with watermark 8% size right bottom<br> //imagejpeg($resultImage, $_image, 100); //save copy with watermark in upload/tmp<br> imagedestroy($resultImage);<br> imagedestroy($finalWaterMarkImage);<br> //rename($_SERVER["DOCUMENT_ROOT"].$newimg["src"],$_image["tmp_name"]);<br> // $_image["size"]=$newimg["size"];</p><p>//$GLOBALS['APPLICATION']-&gt;ThrowException('file $_image');<br> //return ($_image); //return as input $image</p><p>}<br> //Очищаем временную папку<br> // function Clear() {<br> //$_upload_dir = COption::GetOptionString("main", "upload_dir");<br> //$_WFILE = glob($_SERVER['DOCUMENT_ROOT'] . "/" . $_upload_dir . "/tmp/*.jpg");<br> //foreach($_WFILE as $_file) unlink($_file);<br> // return true;<br> // }<br> }<br> [/code]<br> ?></p>

 


 

Установка на FreeBSD oss (4) и nspluginwrapper — libflashplayer,

и соответственно linux-centos emulator,
или что лучше — Firefox Chromium (chrome) wine-devel (wine use pkg) + Pipelight,
все это нужно для посмотра flash видео и клипов.
Первый вариант сейчас идеально работает без звука, а со звуком — где то по цепочке
alsa-lib-oss (kernel panic) browser crash ): .

OSS нужно ставить для многих звуковушек особенно если для серверных плат,
я не смог ее запустить так на новой версии freebsd 12 current что то dump/ kernel panic/ но на 10-11 версии работает.

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

html5 клипы и рекламу показывает  со звуком и youtube тоже без сбоев и зависов — даже несколько окошек, без flash.

 

************———————


 

 короткие записи

— почему то Brasero не записывает образ диска в простом режиме tao а диск dvd iso ( привод lg  bluray)

установлен пакет sysutils/dvd+rw-tools

<p>root@pc1:~# cd Downloads<br> root@pc1:~/Downloads# ls *.iso<br> CentOS-7-x86_64-DVD-1511.iso VBoxGuestAdditions_5.0.6.iso<br> root@pc1:~/Downloads# growisofs -dvd-compat -Z /dev/cd0=CentOS-7-x86_64-DVD-1511.iso<br> Executing 'builtin_dd if=CentOS-7-x86_64-DVD-1511.iso of=/dev/pass1 obs=32k seek=0'<br> /dev/pass1: "Current Write Speed" is 8.2x1352KBps.<br> 2949120/4329570304 ( 0.1%) @0.6x, remaining 146:42 RBU 100.0% UBU 1.2%</p><p>...<br> 30408704/4329570304 ( 0.7%) @5.9x, remaining 21:12 RBU 100.0% UBU 98.8%<br> 4157276160/4329570304 (96.0%) @8.0x, remaining 0:16 RBU 100.0% UBU 100.0%<br> 4194271232/4329570304 (96.9%) @8.0x, remaining 0:13 RBU 100.0% UBU 100.0%<br> 4231200768/4329570304 (97.7%) @8.0x, remaining 0:09 RBU 100.0% UBU 100.0%<br> 4268163072/4329570304 (98.6%) @8.0x, remaining 0:05 RBU 100.0% UBU 98.8%<br> 4305092608/4329570304 (99.4%) @8.0x, remaining 0:02 RBU 72.9% UBU 100.0%<br> builtin_dd: 2114048*2KB out @ average 7.5x1352KBps<br> /dev/pass1: flushing cache<br> /dev/pass1: updating RMA<br> /dev/pass1: closing disc</p><span id="mce_marker" data-mce-type="bookmark" data-mce-fragment="1">​</span>

 

 

*ok

вытащить диск и поставить опять

/dev/cd0 on /media/CentOS 7 x86_64 (cd9660, local, nosuid, read-only)
root@pc1:~# mount_cd9660
usage: mount_cd9660 [-begjrv] [-C charset] [-o options] [-s startsector]
special node
root@pc1:~# mount_udf /dev/cd0

cd0 .. disk file system.. not udf

все записано нормально и монтируется в Gnome3 как iso9660

наверно догадываюсь устройство не dev/dvd a dev/cd0


———————————-

настроить роутер на операционке из Беркли!

(если у кого получится — может итти на работу сис.админом или сэкономить пару тыс евро на зарплате  если сам директор, очень часто в малом офисе или магазине надо завести интернет на 3-5 компьютеров а соединение одно. Сейчас есть роутеры за 1500р и со всеми vpn НО не сервер это и зависают они надо раза 2 за день перегружать и самое главное — взламывают их на раз два три! А потом сеть из этих железок устраивает всякие дидосы…)

да еще срочно на серверной материнке где 2012 сервер подохли обе сетевушки то есть не то чтобы совсем а на сотку не включается ни одна, нет то принимаемых пакетов то переданных и соответственно никак  не работает. А на 1000 мегабит включается, может молния попала или моя шерстистая собачища пробежала. (на 1000 используется все 8 проводков, на 100 достаточно 2-х пар).

——
2 вариант подгрузил kernel module ipfw nat ядро не собирал
— из loader.conf natd соответственно отключен

<p>[bash]<br> root@pc1:~ # kldstat<br> Id Refs Address Size Name<br> 1 59 0xffffffff80200000 1a1c900 kernel<br> 2 4 0xffffffff81c1d000 45c20 linux.ko<br> 3 3 0xffffffff81c63000 7f98 linux_common.ko<br> 4 4 0xffffffff81c6b000 1d290 ipfw.ko<br> 5 1 0xffffffff81c89000 2d10 coretemp.ko<br> 6 1 0xffffffff81c8c000 15090 fuse.ko<br> 7 1 0xffffffff81ca2000 6878 sem.ko<br> 8 1 0xffffffff81ca9000 10c210 nvidia-modeset.ko<br> 9 2 0xffffffff81db6000 f57558 nvidia.ko<br> 10 1 0xffffffff82d0e000 4ce0 ipdivert.ko<br> 11 1 0xffffffff82d13000 47f0 ipfw_nat.ko<br> 12 2 0xffffffff82d18000 14550 libalias.ko<br> 13 1 0xffffffff82e19000 3ca2 linprocfs.ko<br> 14 1 0xffffffff82e1d000 22ca ums.ko<br> 15 1 0xffffffff82e20000 9ac8 dummynet.ko<br> 16 1 0xffffffff82e2a000 16a25 smbfs.ko<br> 17 2 0xffffffff82e41000 3117 libiconv.ko<br> 18 2 0xffffffff82e45000 e89 libmchain.ko<br> 19 2 0xffffffff82e46000 7bdb7 osscore.ko<br> 20 1 0xffffffff82ec2000 e070 oss_envy24ht.ko<br> 21 1 0xffffffff82ed1000 74c rtc.ko<br> root@pc1:~ #<br> root@pc1:~ # ipfw show<br> 00050 171484 54040303 nat 123 ip4 from any to any via igb1<br> 00100 2912 282650 allow ip from any to any via lo0<br> 00200 0 0 deny ip from any to 127.0.0.0/8<br> 00300 0 0 deny ip from 127.0.0.0/8 to any<br> 00400 0 0 deny ip from any to ::1<br> 00500 0 0 deny ip from ::1 to any<br> 00600 2 152 allow ipv6-icmp from :: to ff02::/16<br> 00700 0 0 allow ipv6-icmp from fe80::/10 to fe80::/10<br> 00800 38 3060 allow ipv6-icmp from fe80::/10 to ff02::/16<br> 00900 0 0 allow ipv6-icmp from any to any ip6 icmp6types 1<br> 01000 0 0 allow ipv6-icmp from any to any ip6 icmp6types 2,135,136<br> 65000 621598 962497442 allow ip from any to any<br> 65535 282 19494 deny ip from any to any<br> root@pc1:~ # cat /loader.conf<br> cat: /loader.conf: No such file or directory<br> root@pc1:~ # cat /boot/loader.conf<br> legal.intel_wpi.license_ack=1<br> hw.vga.textmode=1<br> #wpifw_load="YES"<br> #if_wpi_load="YES"<br> #vboxdrv_load="YES"<br> fuse_load="YES"<br> coretemp_load="YES"<br> #hw.pci.default_vgapci_unit="0"<br> #hw.psm.synaptics_support=1<br> linux_load="yes"<br> #wlan_wep_load="yes"<br> #if_alc_load="YES"<br> ##accf_http_load="YES"<br> #via envy24 not in kernel<br> #sound_load="YES"<br> #snd_spicds_load="YES"<br> #snd_envy24_load="YES"<br> #snd_envy24ht_load="YES"<br> #/usr/local/lib/oss/modules/osscore_load="YES"<br> #radeon.agpmode="8"<br> net.graph.maxdata=8192<br> kern.maxvnodes=85000<br> kern.maxproc=15000<br> kern.maxfiles=32700<br> kern.securelevel=-1<br> #kern.maxfiles="32500"<br> #radeonkms_load="YES"<br> #acpi_asus_load="YES"<br> sem_load="YES"<br> #cuse4bsd_load="YES"<br> #nvidia change to nvidia-modeset 1.09.2016<br> nvidia-modeset_load="YES"<br> nvidia_load="YES"<br> libalias_load="YES"<br> ipfw_load="YES"<br> ipdivert_load="YES"<br> ipfw_nat_load="YES"</p><p>//ip not actual<br> root@pc1:~ # cat /etc/rc.conf<br> hostname="pc1"<br> #fsck_y_enable="YES"<br> background_fsck="YES"<br> #wlans_ath0="wlan0"<br> ##ifconfig alc0="DHCP"<br> #ifconfig_wlan0="WPA DHCP"<br> #ifconfig_alc0="SYNCDHCP"<br> #ifconfig_igb0="SYNCDHCP"<br> ifconfig_igb0="192.168.3.211"<br> # inet .. netmask 0xffffff00 broadcast 192.168.3.255<br> ifconfig_igb1="SYNCDHCP"<br> #ifconfig_nfe0="SYNCDHCP"<br> #ifconfig_re0="SYNCDHCP"<br> sshd_enable="YES"<br> ifconfig_igb0_ipv6="inet6 accept_rtadv"<br> #vboxdrv_enable="YES"<br> #vboxnet_enable="YES"<br> gateway_enable="YES"<br> firewall_enable="YES"<br> firewall_nat_enable="YES"<br> firewall_nat_flags="redirect_port tcp 192.168.3.2:1723 1723 redirect_port tcp 192.168.3.2:4899 4900 redirect_port tcp 192.168.3.211:90 90 redirect_port tcp 192.168.3.211:80 80"<br> firewall_nat_interface="igb1"<br> firewall_type="OPEN"<br> dummynet_enable="YES"<br> #natd_enable="YES"<br> #natd_interface="igb1"<br> #natd_flags="-f /etc/natd.conf"<br> ##crash if 12 current kernel after 17-aug-2016 (soundon in rc.local)<br> oss_enable="YES"<br> # Set dumpdev to "AUTO" to enable crash dumps, "NO" to disable<br> dumpdev="NO"<br> #apache22_enable="YES"<br> #apache24_enable="YES"<br> php_fpm_enable="YES"<br> nginx_enable="YES"<br> webmin_enable="YES"<br> devfs_rulesets="/etc/defaults/devfs.rules /etc/devfs.rules"<br> devfs_system_ruleset="system"<br> devfs_load_rulesets="YES"<br> #kpasswdd_enable="YES"<br> #kpasswd_program="/usr/libexec/kpasswdd"<br> #kdc_enable="YES"<br> #fuse_load="YES"<br> #fusefs_load="YES"<br> #kadmind_enable="YES""<br> casperd_enable="YES"<br> ppp_enable="NO"<br> ppp_mode="ddial"<br> ppp_profile="vpn"<br> pppoed_enable="NO"<br> inetd_enable="NO"<br> #route_lan2="-net 192.168.0.0/24 192.168.3.8"<br> mysql_server_enable="YES"<br> mysql_enable="YES"<br> mysql_limits="NO"<br> #apm_enable="YES"<br> #apmd_enable="YES"<br> #amd_enable="YES"<br> # run order dbus-hald-gdm (xorg 1.14.4.901) avahi gnome3<br> gnome_enable="YES"<br> dbus_enable="YES"<br> hald_enable="YES"<br> ##kldload radeonkms<br> avahi_daemon_enable="YES"<br> gdm_enable="YES"<br> #slim_enable="YES"<br> gdm_lang="ru_RU.UTF-8"<br> webcamd_enable="YES"<br> proftpd_enable="YES"<br> mbmon_enable=YES<br> snmpd_enable="YES"<br> #snmpd_conffile="/usr/local/etc/snmpd.conf"<br> mrtg_daemon_enable="YES"<br> mrtg_daemon_config="/usr/local/etc/mrtg/pc.conf"<br> #transmission_enable=yes<br> #transmission_conf_dir="/etc/transmission"<br> ##TRANSMISSION_HOME="/usr/local/etc/transmission/home"<br> #transmission_download_dir="/root/Desktop/"<br> root@pc1:~ # cat /etc/rc.local<br> ##kldload radeon<br> #dhclient alc0<br> #kldload linux<br> #kldload fuse<br> ifconfig igb0 192.168.3.211<br> #ntfs-3g /dev/ada1s1 /media/disk2<br> #ntfs-3g /dev/ada1s2 /media/disk3<br> /usr/local/bin/ntfs-3g /dev/da0s1 /media/disk<br> mount_smbfs -I192.168.3.2 -EUTF-8:CP1251 //Админ1@srv01/e$ /mnt<br> mount_smbfs -I192.168.3.2 -EUTF-8:CP1251 //Админ1@srv01/F /mnt1<br> #mount_smbfs -L ru_RU.UTF-8 -E UTF-8:CP1251 //админ2@srv02/e$ /mnt<br> # for ati driver 7.2.0 - no KMS kernel part & fw autoload<br> #kldload radeonkms<br> ##kldload drm<br> #kldload nvi-.ko<br> #soundon</p><p># all in loader.conf<br> #kldload libalias<br> #kldload ipfilter<br> #kldload ipfw<br> #kldload ipfw_nat<br> #kldload ipdivert</p><p>#/sbin/ipfw add 100 allow ip from any to any<br> #/sbin/ipfw add 100 allow ip from 192.168.3.211 to any</p><p># conflict with vpn server (route nat ok)<br> #/sbin/ipfw add 40 divert natd ip from 192.168.3.0/24 to any out via igb1<br> #/sbin/ipfw add 40 divert natd ip from any to me in via igb1</p><p># variable defines into rc.conf - edit<br> #/sbin/ipfw nat 123 config if $firewall_nat_interface redirect_port tcp 192.168.3.211:90 90</p><p>#vpn pptp at 192.168.3.2<br> route add 192.168.0.0 192.168.3.2</p><p>#/sbin/ipfw add 40 divert natd ip from any to 77.41.57.147 in via igb1<br> #natd -interface igb1 -f /etc/natd.conf<br> #service natd restart</p><p>#route add -net 192.168.0.0/24 192.168.3.2<br> #route add 0.0.0.0 192.168.3.2</p><p>#route add -net 0.0.0.0 192.168.3.2<br> #route show 192.168.0.0<br> #route add 77.37.234.161 192.168.3.1<br> #/root/rungnome.sh<br> #/usr/bin/env DISPLAY=:0 xterm</p><p>root@pc1:~ # ipfw show<br> 00050 178184 55166105 nat 123 ip4 from any to any via igb1<br> 00100 3066 297004 allow ip from any to any via lo0<br> 00200 0 0 deny ip from any to 127.0.0.0/8<br> 00300 0 0 deny ip from 127.0.0.0/8 to any<br> 00400 0 0 deny ip from any to ::1<br> 00500 0 0 deny ip from ::1 to any<br> 00600 2 152 allow ipv6-icmp from :: to ff02::/16<br> 00700 0 0 allow ipv6-icmp from fe80::/10 to fe80::/10<br> 00800 41 3288 allow ipv6-icmp from fe80::/10 to ff02::/16<br> 00900 0 0 allow ipv6-icmp from any to any ip6 icmp6types 1<br> 01000 0 0 allow ipv6-icmp from any to any ip6 icmp6types 2,135,136<br> 65000 645702 965143768 allow ip from any to any<br> 65535 282 19494 deny ip from any to any<br> root@pc1:~ # ipfw show nat<br> ipfw: invalid rule number: nat<br> root@pc1:~ # ipfw show config<br> ipfw: invalid rule number: config<br> root@pc1:~ # ipfw -?<br> ipfw: Нет соответствий.<br> root@pc1:~ # man ipfw<br> IPFW(8) FreeBSD System Manager's Manual IPFW(8)</p><p>NAME<br> ipfw — User interface for firewall, traffic shaper, packet scheduler, in-<br> kernel NAT.</p><p>SYNOPSIS<br> FIREWALL CONFIGURATION<br> ipfw [-cq] add rule<br> ipfw [-acdefnNStT] [set N] {list | show} [rule | first-last ...]<br> ipfw [-f | -q] [set N] flush<br> ipfw [-q] [set N] {delete | zero | resetlog} [number ...]</p><p>ipfw set [disable number ...] [enable number ...]<br> ipfw set move [rule] number to number<br> ipfw set swap number number<br> ipfw set show</p><p>SYSCTL SHORTCUTS<br> ipfw enable<br> {firewall | altq | one_pass | debug | verbose | dyn_keepalive}<br> ipfw disable<br> {firewall | altq | one_pass | debug | verbose | dyn_keepalive}</p><p>LOOKUP TABLES<br> ipfw table number add addr[/masklen] [value]<br> ipfw table number delete addr[/masklen]<br> ipfw table {number | all} flush<br> ipfw table {number | all} list</p><p>DUMMYNET CONFIGURATION (TRAFFIC SHAPER AND PACKET SCHEDULER)<br> ipfw {pipe | queue | sched} number config config-options<br> ipfw [-s [field]] {pipe | queue | sched} {delete | list | show}<br> [number ...]</p><p>IN-KERNEL NAT<br> ipfw [-q] nat number config config-options</p><p>ipfw [-cfnNqS] [-p preproc [preproc-flags]] pathname</p><p>DESCRIPTION<br> The ipfw utility is the user interface for controlling the ipfw(4) fire‐<br> wall, the dummynet(4) traffic shaper/packet scheduler, and the in-kernel<br> NAT services.</p><p>A firewall configuration, or ruleset, is made of a list of rules numbered<br> from 1 to 65535. Packets are passed to the firewall from a number of<br> different places in the protocol stack (depending on the source and des‐<br> tination of the packet, it is possible for the firewall to be invoked<br> multiple times on the same packet). The packet passed to the firewall is<br> compared against each of the rules in the ruleset, in rule-number order<br> (multiple rules with the same number are permitted, in which case they<br> are processed in order of insertion). When a match is found, the action<br> corresponding to the matching rule is performed.</p><p>Depending on the action and certain system settings, packets can be rein‐<br> jected into the firewall at some rule after the matching one for further<br> processing.</p><p>A ruleset always includes a default rule (numbered 65535) which cannot be<br> modified or deleted, and matches all packets. The action associated with<br> the default rule can be either deny or allow depending on how the kernel<br> is configured.</p><p>If the ruleset includes one or more rules with the keep-state or limit<br> option, the firewall will have a stateful behaviour, i.e., upon a match<br> it will create dynamic rules, i.e., rules that match packets with the<br> same 5-tuple (protocol, source and destination addresses and ports) as<br> the packet which caused their creation. Dynamic rules, which have a lim‐<br> ited lifetime, are checked at the first occurrence of a check-state,<br> keep-state or limit rule, and are typically used to open the firewall on-<br> demand to legitimate traffic only. See the STATEFUL FIREWALL and<br> EXAMPLES Sections below for more information on the stateful behaviour of<br> ipfw.</p><p>All rules (including dynamic ones) have a few associated counters: a<br> packet count, a byte count, a log count and a timestamp indicating the<br> time of the last match. Counters can be displayed or reset with ipfw<br> commands.</p><p>Each rule belongs to one of 32 different sets , and there are ipfw com‐<br> mands to atomically manipulate sets, such as enable, disable, swap sets,<br> move all rules in a set to another one, delete all rules in a set. These<br> can be useful to install temporary configurations, or to test them. See<br> Section SETS OF RULES for more information on sets.</p><p>Rules can be added with the add command; deleted individually or in<br> groups with the delete command, and globally (except those in set 31)<br> with the flush command; displayed, optionally with the content of the<br> counters, using the show and list commands. Finally, counters can be<br> reset with the zero and resetlog commands.</p><p>COMMAND OPTIONS<br> The following general options are available when invoking ipfw:</p><p>-a Show counter values when listing rules. The show command implies<br> this option.</p><p>-b Only show the action and the comment, not the body of a rule.<br> Implies -c.</p><p>-c When entering or showing rules, print them in compact form, i.e.,<br> omitting the "ip from any to any" string when this does not carry<br> any additional information.</p><p>-d When listing, show dynamic rules in addition to static ones.</p><p>-e When listing and -d is specified, also show expired dynamic<br> rules.</p><p>-f Do not ask for confirmation for commands that can cause problems<br> if misused, i.e., flush. If there is no tty associated with the<br> process, this is implied.</p><p>-i When listing a table (see the LOOKUP TABLES section below for<br> more information on lookup tables), format values as IP<br> addresses. By default, values are shown as integers.</p><p>-n Only check syntax of the command strings, without actually pass‐<br> ing them to the kernel.</p><p>-N Try to resolve addresses and service names in output.</p><p>-q Be quiet when executing the add, nat, zero, resetlog or flush<br> commands; (implies -f). This is useful when updating rulesets by<br> executing multiple ipfw commands in a script (e.g.,<br> ‘sh /etc/rc.firewall’), or by processing a file with many ipfw<br> rules across a remote login session. It also stops a table add<br> or delete from failing if the entry already exists or is not<br> present.</p><p>The reason why this option may be important is that for some of<br> these actions, ipfw may print a message; if the action results in<br> blocking the traffic to the remote client, the remote login ses‐<br> sion will be closed and the rest of the ruleset will not be pro‐<br> cessed. Access to the console would then be required to recover.</p><p>-S When listing rules, show the set each rule belongs to. If this<br> flag is not specified, disabled rules will not be listed.</p><p>-s [field]<br> When listing pipes, sort according to one of the four counters<br> (total or current packets or bytes).</p><p>-t When listing, show last match timestamp converted with ctime().</p><p>-T When listing, show last match timestamp as seconds from the<br> epoch. This form can be more convenient for postprocessing by<br> scripts.</p><p>LIST OF RULES AND PREPROCESSING<br> To ease configuration, rules can be put into a file which is processed<br> using ipfw as shown in the last synopsis line. An absolute pathname must<br> be used. The file will be read line by line and applied as arguments to<br> the ipfw utility.</p><p>Optionally, a preprocessor can be specified using -p preproc where<br> pathname is to be piped through. Useful preprocessors include cpp(1) and<br> m4(1). If preproc does not start with a slash (‘/’) as its first charac‐<br> ter, the usual PATH name search is performed. Care should be taken with<br> this in environments where not all file systems are mounted (yet) by the<br> time ipfw is being run (e.g. when they are mounted over NFS). Once -p<br> has been specified, any additional arguments are passed on to the pre‐<br> processor for interpretation. This allows for flexible configuration<br> files (like conditionalizing them on the local hostname) and the use of<br> macros to centralize frequently required arguments like IP addresses.</p><p>TRAFFIC SHAPER CONFIGURATION<br> The ipfw pipe, queue and sched commands are used to configure the traffic<br> shaper and packet scheduler. See the TRAFFIC SHAPER (DUMMYNET)<br> CONFIGURATION Section below for details.</p><p>If the world and the kernel get out of sync the ipfw ABI may break, pre‐<br> venting you from being able to add any rules. This can adversely effect<br> the booting process. You can use ipfw disable firewall to temporarily<br> disable the firewall to regain access to the network, allowing you to fix<br> the problem.</p><p>PACKET FLOW<br> A packet is checked against the active ruleset in multiple places in the<br> protocol stack, under control of several sysctl variables. These places<br> and variables are shown below, and it is important to have this picture<br> in mind in order to design a correct ruleset.</p><p>^ to upper layers V<br> | |<br> +----------->-----------+<br> ^ V<br> [ip(6)_input] [ip(6)_output] net.inet(6).ip(6).fw.enable=1<br> | |<br> ^ V<br> [ether_demux] [ether_output_frame] net.link.ether.ipfw=1<br> | |<br> +-->--[bdg_forward]-->--+ net.link.bridge.ipfw=1<br> ^ V<br> | to devices |</p><p>The number of times the same packet goes through the firewall can vary<br> between 0 and 4 depending on packet source and destination, and system<br> configuration.</p><p>Note that as packets flow through the stack, headers can be stripped or<br> added to it, and so they may or may not be available for inspection.<br> E.g., incoming packets will include the MAC header when ipfw is invoked<br> from ether_demux(), but the same packets will have the MAC header<br> stripped off when ipfw is invoked from ip_input() or ip6_input().</p><p>Also note that each packet is always checked against the complete rule‐<br> set, irrespective of the place where the check occurs, or the source of<br> the packet. If a rule contains some match patterns or actions which are<br> not valid for the place of invocation (e.g. trying to match a MAC header<br> within ip_input or ip6_input ), the match pattern will not match, but a<br> not operator in front of such patterns will cause the pattern to always<br> match on those packets. It is thus the responsibility of the programmer,<br> if necessary, to write a suitable ruleset to differentiate among the pos‐<br> sible places. skipto rules can be useful here, as an example:</p><p># packets from ether_demux or bdg_forward<br> ipfw add 10 skipto 1000 all from any to any layer2 in<br> # packets from ip_input<br> ipfw add 10 skipto 2000 all from any to any not layer2 in<br> # packets from ip_output<br> ipfw add 10 skipto 3000 all from any to any not layer2 out<br> # packets from ether_output_frame<br> ipfw add 10 skipto 4000 all from any to any layer2 out</p><p>(yes, at the moment there is no way to differentiate between ether_demux<br> and bdg_forward).</p><p>SYNTAX<br> In general, each keyword or argument must be provided as a separate com‐<br> mand line argument, with no leading or trailing spaces. Keywords are<br> case-sensitive, whereas arguments may or may not be case-sensitive<br> depending on their nature (e.g. uid's are, hostnames are not).</p><p>Some arguments (e.g., port or address lists) are comma-separated lists of<br> values. In this case, spaces after commas ',' are allowed to make the<br> line more readable. You can also put the entire command (including<br> flags) into a single argument. E.g., the following forms are equivalent:</p><p>ipfw -q add deny src-ip 10.0.0.0/24,127.0.0.1/8<br> ipfw -q add deny src-ip 10.0.0.0/24, 127.0.0.1/8<br> ipfw "-q add deny src-ip 10.0.0.0/24, 127.0.0.1/8"</p><p>RULE FORMAT<br> The format of firewall rules is the following:</p><p>[rule_number] [set set_number] [prob match_probability] action<br> [log [logamount number]] [altq queue] [{tag | untag} number] body</p><p>where the body of the rule specifies which information is used for fil‐<br> tering packets, among the following:</p><p>Layer-2 header fields When available<br> IPv4 and IPv6 Protocol TCP, UDP, ICMP, etc.<br> Source and dest. addresses and ports<br> Direction See Section PACKET FLOW<br> Transmit and receive interface By name or address<br> Misc. IP header fields Version, type of service, data‐<br> gram length, identification,<br> fragment flag (non-zero IP off‐<br> set), Time To Live<br> IP options<br> IPv6 Extension headers Fragmentation, Hop-by-Hop<br> options, Routing Headers, Source<br> routing rthdr0, Mobile IPv6<br> rthdr2, IPSec options.<br> IPv6 Flow-ID<br> Misc. TCP header fields TCP flags (SYN, FIN, ACK, RST,<br> etc.), sequence number, acknowl‐<br> edgment number, window<br> TCP options<br> ICMP types for ICMP packets<br> ICMP6 types for ICMP6 packets<br> User/group ID When the packet can be associ‐<br> ated with a local socket.<br> Divert status Whether a packet came from a<br> divert socket (e.g., natd(8)).<br> Fib annotation state Whether a packet has been tagged<br> for using a specific FIB (rout‐<br> ing table) in future forwarding<br> decisions.</p><p>Note that some of the above information, e.g. source MAC or IP addresses<br> and TCP/UDP ports, can be easily spoofed, so filtering on those fields<br> alone might not guarantee the desired results.</p><p>rule_number<br> Each rule is associated with a rule_number in the range 1..65535,<br> with the latter reserved for the default rule. Rules are checked<br> sequentially by rule number. Multiple rules can have the same<br> number, in which case they are checked (and listed) according to<br> the order in which they have been added. If a rule is entered<br> without specifying a number, the kernel will assign one in such a<br> way that the rule becomes the last one before the default rule.<br> Automatic rule numbers are assigned by incrementing the last non-<br> default rule number by the value of the sysctl variable<br> net.inet.ip.fw.autoinc_step which defaults to 100. If this is<br> not possible (e.g. because we would go beyond the maximum allowed<br> rule number), the number of the last non-default value is used<br> instead.</p><p>set set_number<br> Each rule is associated with a set_number in the range 0..31.<br> Sets can be individually disabled and enabled, so this parameter<br> is of fundamental importance for atomic ruleset manipulation. It<br> can be also used to simplify deletion of groups of rules. If a<br> rule is entered without specifying a set number, set 0 will be<br> used.<br> Set 31 is special in that it cannot be disabled, and rules in set<br> 31 are not deleted by the ipfw flush command (but you can delete<br> them with the ipfw delete set 31 command). Set 31 is also used<br> for the default rule.</p><p>prob match_probability<br> A match is only declared with the specified probability (floating<br> point number between 0 and 1). This can be useful for a number<br> of applications such as random packet drop or (in conjunction<br> with dummynet) to simulate the effect of multiple paths leading<br> to out-of-order packet delivery.</p><p>Note: this condition is checked before any other condition,<br> including ones such as keep-state or check-state which might have<br> side effects.</p><p>log [logamount number]<br> Packets matching a rule with the log keyword will be made avail‐<br> able for logging in two ways: if the sysctl variable<br> net.inet.ip.fw.verbose is set to 0 (default), one can use bpf(4)<br> attached to the ipfw0 pseudo interface. This pseudo interface<br> can be created after a boot manually by using the following com‐<br> mand:</p><p># ifconfig ipfw0 create</p><p>Or, automatically at boot time by adding the following line to<br> the rc.conf(5) file:</p><p>firewall_logif="YES"</p><p>There is no overhead if no bpf(4) is attached to the pseudo<br> interface.</p><p>If net.inet.ip.fw.verbose is set to 1, packets will be logged to<br> syslogd(8) with a LOG_SECURITY facility up to a maximum of<br> logamount packets. If no logamount is specified, the limit is<br> taken from the sysctl variable net.inet.ip.fw.verbose_limit. In<br> both cases, a value of 0 means unlimited logging.</p><p>Once the limit is reached, logging can be re-enabled by clearing<br> the logging counter or the packet counter for that entry, see the<br> resetlog command.</p><p>Note: logging is done after all other packet matching conditions<br> have been successfully verified, and before performing the final<br> action (accept, deny, etc.) on the packet.</p><p>tag number<br> When a packet matches a rule with the tag keyword, the numeric<br> tag for the given number in the range 1..65534 will be attached<br> to the packet. The tag acts as an internal marker (it is not<br> sent out over the wire) that can be used to identify these pack‐<br> ets later on. This can be used, for example, to provide trust<br> between interfaces and to start doing policy-based filtering. A<br> packet can have multiple tags at the same time. Tags are<br> "sticky", meaning once a tag is applied to a packet by a matching<br> rule it exists until explicit removal. Tags are kept with the<br> packet everywhere within the kernel, but are lost when packet<br> leaves the kernel, for example, on transmitting packet out to the<br> network or sending packet to a divert(4) socket.</p><p>To check for previously applied tags, use the tagged rule option.<br> To delete previously applied tag, use the untag keyword.</p><p>Note: since tags are kept with the packet everywhere in ker‐<br> nelspace, they can be set and unset anywhere in the kernel net‐<br> work subsystem (using the mbuf_tags(9) facility), not only by<br> means of the ipfw(4) tag and untag keywords. For example, there<br> can be a specialized netgraph(4) node doing traffic analyzing and<br> tagging for later inspecting in firewall.</p><p>untag number<br> When a packet matches a rule with the untag keyword, the tag with<br> the number number is searched among the tags attached to this<br> packet and, if found, removed from it. Other tags bound to<br> packet, if present, are left untouched.</p><p>altq queue<br> When a packet matches a rule with the altq keyword, the ALTQ<br> identifier for the given queue (see altq(4)) will be attached.<br> Note that this ALTQ tag is only meaningful for packets going<br> "out" of IPFW, and not being rejected or going to divert sockets.<br> Note that if there is insufficient memory at the time the packet<br> is processed, it will not be tagged, so it is wise to make your<br> ALTQ "default" queue policy account for this. If multiple altq<br> rules match a single packet, only the first one adds the ALTQ<br> classification tag. In doing so, traffic may be shaped by using<br> count altq queue rules for classification early in the ruleset,<br> then later applying the filtering decision. For example,<br> check-state and keep-state rules may come later and provide the<br> actual filtering decisions in addition to the fallback ALTQ tag.</p><p>You must run pfctl(8) to set up the queues before IPFW will be<br> able to look them up by name, and if the ALTQ disciplines are<br> rearranged, the rules in containing the queue identifiers in the<br> kernel will likely have gone stale and need to be reloaded.<br> Stale queue identifiers will probably result in misclassifica‐<br> tion.</p><p>All system ALTQ processing can be turned on or off via ipfw<br> enable altq and ipfw disable altq. The usage of<br> net.inet.ip.fw.one_pass is irrelevant to ALTQ traffic shaping, as<br> the actual rule action is followed always after adding an ALTQ<br> tag.</p><p>RULE ACTIONS<br> A rule can be associated with one of the following actions, which will be<br> executed when the packet matches the body of the rule.</p><p>allow | accept | pass | permit<br> Allow packets that match rule. The search terminates.</p><p>check-state<br> Checks the packet against the dynamic ruleset. If a match is<br> found, execute the action associated with the rule which gener‐<br> ated this dynamic rule, otherwise move to the next rule.<br> Check-state rules do not have a body. If no check-state rule is<br> found, the dynamic ruleset is checked at the first keep-state or<br> limit rule.</p><p>count Update counters for all packets that match rule. The search con‐<br> tinues with the next rule.</p><p>deny | drop<br> Discard packets that match this rule. The search terminates.</p><p>divert port<br> Divert packets that match this rule to the divert(4) socket bound<br> to port port. The search terminates.</p><p>fwd | forward ipaddr | tablearg[,port]<br> Change the next-hop on matching packets to ipaddr, which can be<br> an IP address or a host name. For IPv4, the next hop can also be<br> supplied by the last table looked up for the packet by using the<br> tablearg keyword instead of an explicit address. The search ter‐<br> minates if this rule matches.</p><p>If ipaddr is a local address, then matching packets will be for‐<br> warded to port (or the port number in the packet if one is not<br> specified in the rule) on the local machine.<br> If ipaddr is not a local address, then the port number (if speci‐<br> fied) is ignored, and the packet will be forwarded to the remote<br> address, using the route as found in the local routing table for<br> that IP.<br> A fwd rule will not match layer-2 packets (those received on<br> ether_input, ether_output, or bridged).<br> The fwd action does not change the contents of the packet at all.<br> In particular, the destination address remains unmodified, so<br> packets forwarded to another system will usually be rejected by<br> that system unless there is a matching rule on that system to<br> capture them. For packets forwarded locally, the local address<br> of the socket will be set to the original destination address of<br> the packet. This makes the netstat(1) entry look rather weird<br> but is intended for use with transparent proxy servers.</p><p>nat nat_nr | tablearg<br> Pass packet to a nat instance (for network address translation,<br> address redirect, etc.): see the NETWORK ADDRESS TRANSLATION<br> (NAT) Section for further information.</p><p>pipe pipe_nr<br> Pass packet to a dummynet “pipe” (for bandwidth limitation,<br> delay, etc.). See the TRAFFIC SHAPER (DUMMYNET) CONFIGURATION<br> Section for further information. The search terminates; however,<br> on exit from the pipe and if the sysctl(8) variable<br> net.inet.ip.fw.one_pass is not set, the packet is passed again to<br> the firewall code starting from the next rule.</p><p>queue queue_nr<br> Pass packet to a dummynet “queue” (for bandwidth limitation using<br> WF2Q+).</p><p>reject (Deprecated). Synonym for unreach host.</p><p>reset Discard packets that match this rule, and if the packet is a TCP<br> packet, try to send a TCP reset (RST) notice. The search termi‐<br> nates.</p><p>reset6 Discard packets that match this rule, and if the packet is a TCP<br> packet, try to send a TCP reset (RST) notice. The search termi‐<br> nates.</p><p>skipto number | tablearg<br> Skip all subsequent rules numbered less than number. The search<br> continues with the first rule numbered number or higher. It is<br> possible to use the tablearg keyword with a skipto for a computed<br> skipto, but care should be used, as no destination caching is<br> possible in this case so the rules are always walked to find it,<br> starting from the skipto.</p><p>call number | tablearg<br> The current rule number is saved in the internal stack and rule‐<br> set processing continues with the first rule numbered number or<br> higher. If later a rule with the return action is encountered,<br> the processing returns to the first rule with number of this call<br> rule plus one or higher (the same behaviour as with packets<br> returning from divert(4) socket after a divert action). This<br> could be used to make somewhat like an assembly language<br> “subroutine” calls to rules with common checks for different<br> interfaces, etc.</p><p>Rule with any number could be called, not just forward jumps as<br> with skipto. So, to prevent endless loops in case of mistakes,<br> both call and return actions don't do any jumps and simply go to<br> the next rule if memory cannot be allocated or stack over‐<br> flowed/underflowed.</p><p>Internally stack for rule numbers is implemented using<br> mbuf_tags(9) facility and currently has size of 16 entries. As<br> mbuf tags are lost when packet leaves the kernel, divert should<br> not be used in subroutines to avoid endless loops and other unde‐<br> sired effects.</p><p>return Takes rule number saved to internal stack by the last call action<br> and returns ruleset processing to the first rule with number<br> greater than number of corresponding call rule. See description<br> of the call action for more details.</p><p>Note that return rules usually end a “subroutine” and thus are<br> unconditional, but ipfw command-line utility currently requires<br> every action except check-state to have body. While it is some‐<br> times useful to return only on some packets, usually you want to<br> print just “return” for readability. A workaround for this is to<br> use new syntax and -c switch:</p><p># Add a rule without actual body<br> ipfw add 2999 return via any</p><p># List rules without "from any to any" part<br> ipfw -c list</p><p>This cosmetic annoyance may be fixed in future releases.</p><p>tee port<br> Send a copy of packets matching this rule to the divert(4) socket<br> bound to port port. The search continues with the next rule.</p><p>unreach code<br> Discard packets that match this rule, and try to send an ICMP<br> unreachable notice with code code, where code is a number from 0<br> to 255, or one of these aliases: net, host, protocol, port,<br> needfrag, srcfail, net-unknown, host-unknown, isolated,<br> net-prohib, host-prohib, tosnet, toshost, filter-prohib,<br> host-precedence or precedence-cutoff. The search terminates.</p><p>unreach6 code<br> Discard packets that match this rule, and try to send an ICMPv6<br> unreachable notice with code code, where code is a number from 0,<br> 1, 3 or 4, or one of these aliases: no-route, admin-prohib,<br> address or port. The search terminates.</p><p>netgraph cookie<br> Divert packet into netgraph with given cookie. The search termi‐<br> nates. If packet is later returned from netgraph it is either<br> accepted or continues with the next rule, depending on<br> net.inet.ip.fw.one_pass sysctl variable.</p><p>ngtee cookie<br> A copy of packet is diverted into netgraph, original packet con‐<br> tinues with the next rule. See ng_ipfw(4) for more information<br> on netgraph and ngtee actions.</p><p>setfib fibnum | tablearg<br> The packet is tagged so as to use the FIB (routing table) fibnum<br> in any subsequent forwarding decisions. In the current implemen‐<br> tation, this is limited to the values 0 through 15, see<br> setfib(2). Processing continues at the next rule. It is possi‐<br> ble to use the tablearg keyword with setfib. If the tablearg<br> value is not within the compiled range of fibs, the packet's fib<br> is set to 0.</p><p>setdscp DSCP | number | tablearg<br> Set specified DiffServ codepoint for an IPv4/IPv6 packet. Pro‐<br> cessing continues at the next rule. Supported values are:</p><p>CS0 (000000), CS1 (001000), CS2 (010000), CS3 (011000), CS4<br> (100000), CS5 (101000), CS6 (110000), CS7 (111000), AF11<br> (001010), AF12 (001100), AF13 (001110), AF21 (010010), AF22<br> (010100), AF23 (010110), AF31 (011010), AF32 (011100), AF33<br> (011110), AF41 (100010), AF42 (100100), AF43 (100110), EF<br> (101110), BE (000000). Additionally, DSCP value can be specified<br> by number (0..64). It is also possible to use the tablearg key‐<br> word with setdscp. If the tablearg value is not within the 0..64<br> range, lower 6 bits of supplied value are used.</p><p>reass Queue and reassemble IP fragments. If the packet is not frag‐<br> mented, counters are updated and processing continues with the<br> next rule. If the packet is the last logical fragment, the<br> packet is reassembled and, if net.inet.ip.fw.one_pass is set to<br> 0, processing continues with the next rule. Otherwise, the<br> packet is allowed to pass and the search terminates. If the<br> packet is a fragment in the middle of a logical group of frag‐<br> ments, it is consumed and processing stops immediately.</p><p>Fragment handling can be tuned via net.inet.ip.maxfragpackets and<br> net.inet.ip.maxfragsperpacket which limit, respectively, the max‐<br> imum number of processable fragments (default: 800) and the maxi‐<br> mum number of fragments per packet (default: 16).</p><p>NOTA BENE: since fragments do not contain port numbers, they<br> should be avoided with the reass rule. Alternatively, direction-<br> based (like in / out ) and source-based (like via ) match pat‐<br> terns can be used to select fragments.</p><p>Usually a simple rule like:</p><p># reassemble incoming fragments<br> ipfw add reass all from any to any in</p><p>is all you need at the beginning of your ruleset.</p><p>RULE BODY<br> The body of a rule contains zero or more patterns (such as specific<br> source and destination addresses or ports, protocol options, incoming or<br> outgoing interfaces, etc.) that the packet must match in order to be<br> recognised. In general, the patterns are connected by (implicit) and<br> operators -- i.e., all must match in order for the rule to match. Indi‐<br> vidual patterns can be prefixed by the not operator to reverse the result<br> of the match, as in</p><p>ipfw add 100 allow ip from not 1.2.3.4 to any</p><p>Additionally, sets of alternative match patterns (or-blocks) can be con‐<br> structed by putting the patterns in lists enclosed between parentheses (<br> ) or braces { }, and using the or operator as follows:</p><p>ipfw add 100 allow ip from { x or not y or z } to any</p><p>Only one level of parentheses is allowed. Beware that most shells have<br> special meanings for parentheses or braces, so it is advisable to put a<br> backslash \ in front of them to prevent such interpretations.</p><p>The body of a rule must in general include a source and destination<br> address specifier. The keyword any can be used in various places to<br> specify that the content of a required field is irrelevant.</p><p>The rule body has the following format:</p><p>[proto from src to dst] [options]</p><p>The first part (proto from src to dst) is for backward compatibility with<br> earlier versions of FreeBSD. In modern FreeBSD any match pattern<br> (including MAC headers, IP protocols, addresses and ports) can be speci‐<br> fied in the options section.</p><p>Rule fields have the following meaning:</p><p>proto: protocol | { protocol or ... }</p><p>protocol: [not] protocol-name | protocol-number<br> An IP protocol specified by number or name (for a complete list<br> see /etc/protocols), or one of the following keywords:</p><p>ip4 | ipv4<br> Matches IPv4 packets.</p><p>ip6 | ipv6<br> Matches IPv6 packets.</p><p>ip | all<br> Matches any packet.</p><p>The ipv6 in proto option will be treated as inner protocol. And,<br> the ipv4 is not available in proto option.</p><p>The { protocol or ... } format (an or-block) is provided for con‐<br> venience only but its use is deprecated.</p><p>src and dst: {addr | { addr or ... }} [[not] ports]<br> An address (or a list, see below) optionally followed by ports<br> specifiers.</p><p>The second format (or-block with multiple addresses) is provided<br> for convenience only and its use is discouraged.</p><p>addr: [not] {any | me | me6 | table(number[,value]) | addr-list |<br> addr-set}</p><p>any matches any IP address.</p><p>me matches any IP address configured on an interface in the<br> system.</p><p>me6 matches any IPv6 address configured on an interface in<br> the system. The address list is evaluated at the time<br> the packet is analysed.</p><p>table(number[,value])<br> Matches any IPv4 address for which an entry exists in the<br> lookup table number. If an optional 32-bit unsigned<br> value is also specified, an entry will match only if it<br> has this value. See the LOOKUP TABLES section below for<br> more information on lookup tables.</p><p>addr-list: ip-addr[,addr-list]</p><p>ip-addr:<br> A host or subnet address specified in one of the following ways:</p><p>numeric-ip | hostname<br> Matches a single IPv4 address, specified as dotted-quad<br> or a hostname. Hostnames are resolved at the time the<br> rule is added to the firewall list.</p><p>addr/masklen<br> Matches all addresses with base addr (specified as an IP<br> address, a network number, or a hostname) and mask width<br> of masklen bits. As an example, 1.2.3.4/25 or 1.2.3.0/25<br> will match all IP numbers from 1.2.3.0 to 1.2.3.127 .</p><p>addr:mask<br> Matches all addresses with base addr (specified as an IP<br> address, a network number, or a hostname) and the mask of<br> mask, specified as a dotted quad. As an example,<br> 1.2.3.4:255.0.255.0 or 1.0.3.0:255.0.255.0 will match<br> 1.*.3.*. This form is advised only for non-contiguous<br> masks. It is better to resort to the addr/masklen format<br> for contiguous masks, which is more compact and less<br> error-prone.</p><p>addr-set: addr[/masklen]{list}</p><p>list: {num | num-num}[,list]<br> Matches all addresses with base address addr (specified as an IP<br> address, a network number, or a hostname) and whose last byte is<br> in the list between braces { } . Note that there must be no spa‐<br> ces between braces and numbers (spaces after commas are allowed).<br> Elements of the list can be specified as single entries or<br> ranges. The masklen field is used to limit the size of the set<br> of addresses, and can have any value between 24 and 32. If not<br> specified, it will be assumed as 24.<br> This format is particularly useful to handle sparse address sets<br> within a single rule. Because the matching occurs using a bit‐<br> mask, it takes constant time and dramatically reduces the com‐<br> plexity of rulesets.<br> As an example, an address specified as 1.2.3.4/24{128,35-55,89}</p><p>addr:mask<br> Matches all addresses with base addr (specified as an IP<br> address, a network number, or a hostname) and the mask of<br> mask, specified as a dotted quad. As an example,<br> 1.2.3.4:255.0.255.0 or 1.0.3.0:255.0.255.0 will match<br> 1.*.3.*. This form is advised only for non-contiguous<br> masks. It is better to resort to the addr/masklen format<br> for contiguous masks, which is more compact and less<br> error-prone.</p><p>addr-set: addr[/masklen]{list}</p><p>list: {num | num-num}[,list]<br> Matches all addresses with base address addr (specified as an IP<br> address, a network number, or a hostname) and whose last byte is<br> in the list between braces { } . Note that there must be no spa‐<br> ces between braces and numbers (spaces after commas are allowed).<br> Elements of the list can be specified as single entries or<br> ranges. The masklen field is used to limit the size of the set<br> of addresses, and can have any value between 24 and 32. If not<br> specified, it will be assumed as 24.<br> This format is particularly useful to handle sparse address sets<br> within a single rule. Because the matching occurs using a bit‐<br> mask, it takes constant time and dramatically reduces the com‐<br> plexity of rulesets.<br> As an example, an address specified as 1.2.3.4/24{128,35-55,89}<br> or 1.2.3.0/24{128,35-55,89} will match the following IP<br> addresses:<br> 1.2.3.128, 1.2.3.35 to 1.2.3.55, 1.2.3.89 .</p><p>addr6-list: ip6-addr[,addr6-list]</p><p>ip6-addr:<br> A host or subnet specified one of the following ways:</p><p>numeric-ip | hostname<br> Matches a single IPv6 address as allowed by inet_pton(3)<br> or a hostname. Hostnames are resolved at the time the<br> rule is added to the firewall list.</p><p>addr/masklen<br> Matches all IPv6 addresses with base addr (specified as<br> allowed by inet_pton or a hostname) and mask width of<br> masklen bits.</p><p>No support for sets of IPv6 addresses is provided because IPv6<br> addresses are typically random past the initial prefix.</p><p>ports: {port | port-port}[,ports]<br> For protocols which support port numbers (such as TCP and UDP),<br> optional ports may be specified as one or more ports or port<br> ranges, separated by commas but no spaces, and an optional not<br> operator. The ‘-’ notation specifies a range of ports (including<br> boundaries).</p><p>Service names (from /etc/services) may be used instead of numeric<br> port values. The length of the port list is limited to 30 ports<br> or ranges, though one can specify larger ranges by using an<br> or-block in the options section of the rule.</p><p>A backslash (‘\’) can be used to escape the dash (‘-’) character<br> in a service name (from a shell, the backslash must be typed<br> twice to avoid the shell itself interpreting it as an escape<br> character).</p><p>ipfw add count tcp from any ftp\\-data-ftp to any</p><p>1.2.3.128, 1.2.3.35 to 1.2.3.55, 1.2.3.89 .</p><p>addr6-list: ip6-addr[,addr6-list]</p><p>ip6-addr:<br> A host or subnet specified one of the following ways:</p><p>numeric-ip | hostname<br> Matches a single IPv6 address as allowed by inet_pton(3)<br> or a hostname. Hostnames are resolved at the time the<br> rule is added to the firewall list.</p><p>addr/masklen<br> Matches all IPv6 addresses with base addr (specified as<br> allowed by inet_pton or a hostname) and mask width of<br> masklen bits.</p><p>No support for sets of IPv6 addresses is provided because IPv6<br> addresses are typically random past the initial prefix.</p><p>ports: {port | port-port}[,ports]<br> For protocols which support port numbers (such as TCP and UDP),<br> optional ports may be specified as one or more ports or port<br> ranges, separated by commas but no spaces, and an optional not<br> operator. The ‘-’ notation specifies a range of ports (including<br> boundaries).</p><p>Service names (from /etc/services) may be used instead of numeric<br> port values. The length of the port list is limited to 30 ports<br> or ranges, though one can specify larger ranges by using an<br> or-block in the options section of the rule.</p><p>A backslash (‘\’) can be used to escape the dash (‘-’) character<br> in a service name (from a shell, the backslash must be typed<br> twice to avoid the shell itself interpreting it as an escape<br> character).</p><p>ipfw add count tcp from any ftp\\-data-ftp to any</p><p>Fragmented packets which have a non-zero offset (i.e., not the<br> first fragment) will never match a rule which has one or more<br> port specifications. See the frag option for details on matching<br> fragmented packets.</p><p>RULE OPTIONS (MATCH PATTERNS)<br> Additional match patterns can be used within rules. Zero or more of<br> these so-called options can be present in a rule, optionally prefixed by<br> the not operand, and possibly grouped into or-blocks.</p><p>The following match patterns can be used (listed in alphabetical order):</p><p>// this is a comment.<br> Inserts the specified text as a comment in the rule. Everything<br> following // is considered as a comment and stored in the rule.<br> You can have comment-only rules, which are listed as having a<br> port specifications. See the frag option for details on matching<br> fragmented packets.</p><p>RULE OPTIONS (MATCH PATTERNS)<br> Additional match patterns can be used within rules. Zero or more of<br> these so-called options can be present in a rule, optionally prefixed by<br> the not operand, and possibly grouped into or-blocks.</p><p>The following match patterns can be used (listed in alphabetical order):</p><p>// this is a comment.<br> Inserts the specified text as a comment in the rule. Everything<br> following // is considered as a comment and stored in the rule.<br> You can have comment-only rules, which are listed as having a<br> count action followed by the comment.</p><p>bridged<br> Alias for layer2.</p><p>diverted<br> Matches only packets generated by a divert socket.</p><p>diverted-loopback<br> Matches only packets coming from a divert socket back into the IP<br> stack input for delivery.</p><p>diverted-output<br> Matches only packets going from a divert socket back outward to<br> the IP stack output for delivery.</p><p>dst-ip ip-address<br> Matches IPv4 packets whose destination IP is one of the<br> address(es) specified as argument.</p><p>{dst-ip6 | dst-ipv6} ip6-address<br> Matches IPv6 packets whose destination IP is one of the<br> address(es) specified as argument.</p><p>dst-port ports<br> Matches IP packets whose destination port is one of the port(s)<br> specified as argument.</p><p>established<br> Matches TCP packets that have the RST or ACK bits set.</p><p>ext6hdr header<br> Matches IPv6 packets containing the extended header given by<br> header. Supported headers are:</p><p>Fragment, (frag), Hop-to-hop options (hopopt), any type of Rout‐<br> ing Header (route), Source routing Routing Header Type 0<br> (rthdr0), Mobile IPv6 Routing Header Type 2 (rthdr2), Destination<br> options (dstopt), IPSec authentication headers (ah), and IPsec<br> encapsulated security payload headers (esp).</p><p>fib fibnum<br> Matches a packet that has been tagged to use the given FIB (rout‐<br> ing table) number.</p><p>flow-id labels<br> Matches IPv6 packets containing any of the flow labels given in<br> labels. labels is a comma separated list of numeric flow labels.</p><p>frag Matches packets that are fragments and not the first fragment of<br> an IP datagram. Note that these packets will not have the next<br> protocol header (e.g. TCP, UDP) so options that look into these<br> headers cannot match.</p><p>gid group<br> Matches all TCP or UDP packets sent by or received for a group.<br> A group may be specified by name or number.</p><p>jail prisonID<br> Matches all TCP or UDP packets sent by or received for the jail<br> whos prison ID is prisonID.</p><p>icmptypes types<br> Matches ICMP packets whose ICMP type is in the list types. The<br> list may be specified as any combination of individual types<br> (numeric) separated by commas. Ranges are not allowed. The sup‐<br> ported ICMP types are:</p><p>echo reply (0), destination unreachable (3), source quench (4),<br> redirect (5), echo request (8), router advertisement (9), router<br> solicitation (10), time-to-live exceeded (11), IP header bad<br> (12), timestamp request (13), timestamp reply (14), information<br> request (15), information reply (16), address mask request (17)<br> and address mask reply (18).</p><p>icmp6types types<br> Matches ICMP6 packets whose ICMP6 type is in the list of types.<br> The list may be specified as any combination of individual types<br> (numeric) separated by commas. Ranges are not allowed.</p><p>in | out<br> Matches incoming or outgoing packets, respectively. in and out<br> are mutually exclusive (in fact, out is implemented as not in).</p><p>ipid id-list<br> Matches IPv4 packets whose ip_id field has value included in<br> id-list, which is either a single value or a list of values or<br> ranges specified in the same way as ports.</p><p>iplen len-list<br> Matches IP packets whose total length, including header and data,<br> is in the set len-list, which is either a single value or a list<br> of values or ranges specified in the same way as ports.</p><p>ipoptions spec<br> Matches packets whose IPv4 header contains the comma separated<br> list of options specified in spec. The supported IP options are:</p><p>ssrr (strict source route), lsrr (loose source route), rr (record<br> packet route) and ts (timestamp). The absence of a particular<br> option may be denoted with a ‘!’.</p><p>ipprecedence precedence<br> Matches IPv4 packets whose precedence field is equal to<br> precedence.</p><p>ipsec Matches packets that have IPSEC history associated with them<br> (i.e., the packet comes encapsulated in IPSEC, the kernel has<br> IPSEC support and IPSEC_FILTERTUNNEL option, and can correctly<br> decapsulate it).</p><p>Note that specifying ipsec is different from specifying proto<br> ipsec as the latter will only look at the specific IP protocol<br> field, irrespective of IPSEC kernel support and the validity of<br> the IPSEC data.</p><p>Further note that this flag is silently ignored in kernels with‐<br> out IPSEC support. It does not affect rule processing when given<br> and the rules are handled as if with no ipsec flag.</p><p>iptos spec<br> Matches IPv4 packets whose tos field contains the comma separated<br> list of service types specified in spec. The supported IP types<br> of service are:</p><p>lowdelay (IPTOS_LOWDELAY), throughput (IPTOS_THROUGHPUT),<br> reliability (IPTOS_RELIABILITY), mincost (IPTOS_MINCOST),<br> congestion (IPTOS_ECN_CE). The absence of a particular type may<br> be denoted with a ‘!’.</p><p>dscp spec[,spec]<br> Matches IPv4/IPv6 packets whose DS field value is contained in<br> spec mask. Multiple values can be specified via the comma sepa‐<br> rated list. Value can be one of keywords used in setdscp action<br> or exact number.</p><p>ipttl ttl-list<br> Matches IPv4 packets whose time to live is included in ttl-list,<br> which is either a single value or a list of values or ranges<br> specified in the same way as ports.</p><p>ipversion ver<br> Matches IP packets whose IP version field is ver.</p><p>keep-state<br> Upon a match, the firewall will create a dynamic rule, whose<br> default behaviour is to match bidirectional traffic between<br> source and destination IP/port using the same protocol. The rule<br> has a limited lifetime (controlled by a set of sysctl(8) vari‐<br> ables), and the lifetime is refreshed every time a matching<br> packet is found.</p><p>layer2 Matches only layer2 packets, i.e., those passed to ipfw from<br> ether_demux() and ether_output_frame().</p><p>limit {src-addr | src-port | dst-addr | dst-port} N<br> The firewall will only allow N connections with the same set of<br> parameters as specified in the rule. One or more of source and<br> destination addresses and ports can be specified. Currently,<br> only IPv4 flows are supported.</p><p>lookup {dst-ip | dst-port | src-ip | src-port | uid | jail} N<br> Search an entry in lookup table N that matches the field speci‐<br> fied as argument. If not found, the match fails. Otherwise, the<br> match succeeds and tablearg is set to the value extracted from<br> the table.</p><p>This option can be useful to quickly dispatch traffic based on<br> certain packet fields. See the LOOKUP TABLES section below for<br> more information on lookup tables.</p><p>{ MAC | mac } dst-mac src-mac<br> Match packets with a given dst-mac and src-mac addresses, speci‐<br> fied as the any keyword (matching any MAC address), or six groups<br> of hex digits separated by colons, and optionally followed by a<br> mask indicating the significant bits. The mask may be specified<br> using either of the following methods:</p><p>1. A slash (/) followed by the number of significant bits.<br> For example, an address with 33 significant bits could be<br> specified as:</p><p>MAC 10:20:30:40:50:60/33 any</p><p>2. An ampersand (&) followed by a bitmask specified as six<br> groups of hex digits separated by colons. For example,<br> an address in which the last 16 bits are significant<br> could be specified as:</p><p>MAC 10:20:30:40:50:60&00:00:00:00:ff:ff any</p><p>Note that the ampersand character has a special meaning<br> in many shells and should generally be escaped.</p><p>Note that the order of MAC addresses (destination first, source<br> second) is the same as on the wire, but the opposite of the one<br> used for IP addresses.</p><p>mac-type mac-type<br> Matches packets whose Ethernet Type field corresponds to one of<br> those specified as argument. mac-type is specified in the same<br> way as port numbers (i.e., one or more comma-separated single<br> values or ranges). You can use symbolic names for known values<br> such as vlan, ipv4, ipv6. Values can be entered as decimal or<br> hexadecimal (if prefixed by 0x), and they are always printed as<br> hexadecimal (unless the -N option is used, in which case symbolic<br> resolution will be attempted).</p><p>proto protocol<br> Matches packets with the corresponding IP protocol.</p><p>recv | xmit | via {ifX | if* | table(number[,value | ipno | any])}<br> Matches packets received, transmitted or going through, respec‐<br> tively, the interface specified by exact name (ifX), by device<br> name (if*), by IP address, or through some interface.</p><p>The via keyword causes the interface to always be checked. If<br> recv or xmit is used instead of via, then only the receive or<br> transmit interface (respectively) is checked. By specifying<br> both, it is possible to match packets based on both receive and<br> transmit interface, e.g.:</p><p>ipfw add deny ip from any to any out recv ed0 xmit ed1</p><p>The recv interface can be tested on either incoming or outgoing<br> packets, while the xmit interface can only be tested on outgoing<br> packets. So out is required (and in is invalid) whenever xmit is<br> used.</p><p>A packet might not have a receive or transmit interface: packets<br> originating from the local host have no receive interface, while<br> packets destined for the local host have no transmit interface.</p><p>setup Matches TCP packets that have the SYN bit set but no ACK bit.<br> This is the short form of “tcpflags syn,!ack”.</p><p>sockarg<br> Matches packets that are associated to a local socket and for<br> which the SO_USER_COOKIE socket option has been set to a non-zero<br> value. As a side effect, the value of the option is made avail‐<br> able as tablearg value, which in turn can be used as skipto or<br> pipe number.</p><p>src-ip ip-address<br> Matches IPv4 packets whose source IP is one of the address(es)<br> specified as an argument.</p><p>src-ip6 ip6-address<br> Matches IPv6 packets whose source IP is one of the address(es)<br> specified as an argument.</p><p>src-port ports<br> Matches IP packets whose source port is one of the port(s) speci‐<br> fied as argument.</p><p>tagged tag-list<br> Matches packets whose tags are included in tag-list, which is<br> either a single value or a list of values or ranges specified in<br> the same way as ports. Tags can be applied to the packet using<br> tag rule action parameter (see it's description for details on<br> tags).</p><p>tcpack ack<br> TCP packets only. Match if the TCP header acknowledgment number<br> field is set to ack.</p><p>tcpdatalen tcpdatalen-list<br> Matches TCP packets whose length of TCP data is tcpdatalen-list,<br> which is either a single value or a list of values or ranges<br> specified in the same way as ports.</p><p>tcpflags spec<br> TCP packets only. Match if the TCP header contains the comma<br> separated list of flags specified in spec. The supported TCP<br> flags are:</p><p>fin, syn, rst, psh, ack and urg. The absence of a particular<br> flag may be denoted with a ‘!’. A rule which contains a tcpflags<br> specification can never match a fragmented packet which has a<br> non-zero offset. See the frag option for details on matching<br> fragmented packets.</p><p>tcpseq seq<br> TCP packets only. Match if the TCP header sequence number field<br> is set to seq.</p><p>tcpwin tcpwin-list<br> Matches TCP packets whose header window field is set to<br> tcpwin-list, which is either a single value or a list of values<br> or ranges specified in the same way as ports.</p><p>tcpoptions spec<br> TCP packets only. Match if the TCP header contains the comma<br> separated list of options specified in spec. The supported TCP<br> options are:</p><p>mss (maximum segment size), window (tcp window advertisement),<br> sack (selective ack), ts (rfc1323 timestamp) and cc (rfc1644<br> t/tcp connection count). The absence of a particular option may<br> be denoted with a ‘!’.</p><p>uid user<br> Match all TCP or UDP packets sent by or received for a user. A<br> user may be matched by name or identification number.</p><p>verrevpath<br> For incoming packets, a routing table lookup is done on the<br> packet's source address. If the interface on which the packet<br> entered the system matches the outgoing interface for the route,<br> the packet matches. If the interfaces do not match up, the<br> packet does not match. All outgoing packets or packets with no<br> incoming interface match.</p><p>The name and functionality of the option is intentionally similar<br> to the Cisco IOS command:</p><p>ip verify unicast reverse-path</p><p>This option can be used to make anti-spoofing rules to reject all<br> packets with source addresses not from this interface. See also<br> the option antispoof.</p><p>versrcreach<br> For incoming packets, a routing table lookup is done on the<br> packet's source address. If a route to the source address<br> exists, but not the default route or a blackhole/reject route,<br> the packet matches. Otherwise, the packet does not match. All<br> outgoing packets match.</p><p>The name and functionality of the option is intentionally similar<br> to the Cisco IOS command:</p><p>ip verify unicast source reachable-via any</p><p>This option can be used to make anti-spoofing rules to reject all<br> packets whose source address is unreachable.</p><p>antispoof<br> For incoming packets, the packet's source address is checked if<br> it belongs to a directly connected network. If the network is<br> directly connected, then the interface the packet came on in is<br> compared to the interface the network is connected to. When<br> incoming interface and directly connected interface are not the<br> same, the packet does not match. Otherwise, the packet does<br> match. All outgoing packets match.</p><p>This option can be used to make anti-spoofing rules to reject all<br> packets that pretend to be from a directly connected network but<br> do not come in through that interface. This option is similar to<br> but more restricted than verrevpath because it engages only on<br> packets with source addresses of directly connected networks<br> instead of all source addresses.</p><p>LOOKUP TABLES<br> Lookup tables are useful to handle large sparse sets of addresses or<br> other search keys (e.g., ports, jail IDs, interface names). In the rest<br> of this section we will use the term ``address''. There may be up to<br> 65535 different lookup tables, numbered 0 to 65534.</p><p>Each entry is represented by an addr[/masklen] and will match all<br> addresses with base addr (specified as an IPv4/IPv6 address, a hostname<br> or an unsigned integer) and mask width of masklen bits. If masklen is<br> not specified, it defaults to 32 for IPv4 and 128 for IPv6. When looking<br> up an IP address in a table, the most specific entry will match. Associ‐<br> ated with each entry is a 32-bit unsigned value, which can optionally be<br> checked by a rule matching code. When adding an entry, if value is not<br> specified, it defaults to 0.</p><p>An entry can be added to a table (add), or removed from a table (delete).<br> A table can be examined (list) or flushed (flush).</p><p>Internally, each table is stored in a Radix tree, the same way as the<br> routing table (see route(4)).</p><p>Lookup tables currently support only ports, jail IDs, IPv4/IPv6<br> addresses and interface names. Wildcards is not supported for interface<br> names.</p><p>The tablearg feature provides the ability to use a value, looked up in<br> the table, as the argument for a rule action, action parameter or rule<br> option. This can significantly reduce number of rules in some configura‐<br> tions. If two tables are used in a rule, the result of the second (des‐<br> tination) is used. The tablearg argument can be used with the following<br> actions: nat, pipe, queue, divert, tee, netgraph, ngtee, fwd, skipto,<br> setfib, action parameters: tag, untag, rule options: limit, tagged.</p><p>When used with fwd it is possible to supply table entries with values<br> that are in the form of IP addresses or hostnames. See the EXAMPLES Sec‐<br> tion for example usage of tables and the tablearg keyword.</p><p>When used with the skipto action, the user should be aware that the code<br> will walk the ruleset up to a rule equal to, or past, the given number,<br> and should therefore try keep the ruleset compact between the skipto and<br> the target rules.</p><p>SETS OF RULES<br> Each rule belongs to one of 32 different sets , numbered 0 to 31. Set 31<br> is reserved for the default rule.</p><p>By default, rules are put in set 0, unless you use the set N attribute<br> when entering a new rule. Sets can be individually and atomically<br> enabled or disabled, so this mechanism permits an easy way to store mul‐<br> tiple configurations of the firewall and quickly (and atomically) switch<br> between them. The command to enable/disable sets is</p><p>ipfw set [disable number ...] [enable number ...]</p><p>where multiple enable or disable sections can be specified. Command exe‐<br> cution is atomic on all the sets specified in the command. By default,<br> all sets are enabled.</p><p>When you disable a set, its rules behave as if they do not exist in the<br> firewall configuration, with only one exception:</p><p>dynamic rules created from a rule before it had been disabled will<br> still be active until they expire. In order to delete dynamic<br> rules you have to explicitly delete the parent rule which generated<br> them.</p><p>The set number of rules can be changed with the command</p><p>ipfw set move {rule rule-number | old-set} to new-set</p><p>Also, you can atomically swap two rulesets with the command</p><p>ipfw set swap first-set second-set</p><p>See the EXAMPLES Section on some possible uses of sets of rules.</p><p>STATEFUL FIREWALL<br> Stateful operation is a way for the firewall to dynamically create rules<br> for specific flows when packets that match a given pattern are detected.<br> Support for stateful operation comes through the check-state, keep-state<br> and limit options of rules.</p><p>Dynamic rules are created when a packet matches a keep-state or limit<br> rule, causing the creation of a dynamic rule which will match all and<br> only packets with a given protocol between a src-ip/src-port<br> dst-ip/dst-port pair of addresses (src and dst are used here only to<br> denote the initial match addresses, but they are completely equivalent<br> afterwards). Dynamic rules will be checked at the first check-state,<br> keep-state or limit occurrence, and the action performed upon a match<br> will be the same as in the parent rule.</p><p>Note that no additional attributes other than protocol and IP addresses<br> and ports are checked on dynamic rules.</p><p>The typical use of dynamic rules is to keep a closed firewall configura‐<br> tion, but let the first TCP SYN packet from the inside network install a<br> dynamic rule for the flow so that packets belonging to that session will<br> be allowed through the firewall:</p><p>ipfw add check-state<br> ipfw add allow tcp from my-subnet to any setup keep-state<br> ipfw add deny tcp from any to any</p><p>A similar approach can be used for UDP, where an UDP packet coming from<br> the inside will install a dynamic rule to let the response through the<br> firewall:</p><p>ipfw add check-state<br> ipfw add allow udp from my-subnet to any keep-state<br> ipfw add deny udp from any to any</p><p>Dynamic rules expire after some time, which depends on the status of the<br> flow and the setting of some sysctl variables. See Section SYSCTL<br> VARIABLES for more details. For TCP sessions, dynamic rules can be<br> instructed to periodically send keepalive packets to refresh the state of<br> the rule when it is about to expire.</p><p>See Section EXAMPLES for more examples on how to use dynamic rules.</p><p>TRAFFIC SHAPER (DUMMYNET) CONFIGURATION<br> ipfw is also the user interface for the dummynet traffic shaper, packet<br> scheduler and network emulator, a subsystem that can artificially queue,<br> delay or drop packets emulating the behaviour of certain network links or<br> queueing systems.</p><p>dummynet operates by first using the firewall to select packets using any<br> match pattern that can be used in ipfw rules. Matching packets are then<br> passed to either of two different objects, which implement the traffic<br> regulation:</p><p>pipe A pipe emulates a link with given bandwidth and propagation<br> delay, driven by a FIFO scheduler and a single queue with<br> programmable queue size and packet loss rate. Packets are<br> appended to the queue as they come out from ipfw, and then<br> transferred in FIFO order to the link at the desired rate.</p><p>queue A queue is an abstraction used to implement packet scheduling<br> using one of several packet scheduling algorithms. Packets<br> sent to a queue are first grouped into flows according to a<br> mask on the 5-tuple. Flows are then passed to the scheduler<br> associated to the queue, and each flow uses scheduling param‐<br> eters (weight and others) as configured in the queue itself.<br> A scheduler in turn is connected to an emulated link, and<br> arbitrates the link's bandwidth among backlogged flows<br> according to weights and to the features of the scheduling<br> algorithm in use.</p><p>In practice, pipes can be used to set hard limits to the bandwidth that a<br> flow can use, whereas queues can be used to determine how different flows<br> share the available bandwidth.</p><p>A graphical representation of the binding of queues, flows, schedulers<br> and links is below.</p><p>(flow_mask|sched_mask) sched_mask<br> +---------+ weight Wx +-------------+<br> | |->-[flow]-->--| |-+<br> -->--| QUEUE x | ... | | |<br> | |->-[flow]-->--| SCHEDuler N | |<br> +---------+ | | |<br> ... | +--[LINK N]-->--<br> +---------+ weight Wy | | +--[LINK N]-->--<br> | |->-[flow]-->--| | |<br> -->--| QUEUE y | ... | | |<br> | |->-[flow]-->--| | |<br> +---------+ +-------------+ |<br> +-------------+<br> It is important to understand the role of the SCHED_MASK and FLOW_MASK,<br> which are configured through the commands<br> ipfw sched N config mask SCHED_MASK ...<br> and<br> ipfw queue X config mask FLOW_MASK ....</p><p>The SCHED_MASK is used to assign flows to one or more scheduler<br> instances, one for each value of the packet's 5-tuple after applying<br> SCHED_MASK. As an example, using ``src-ip 0xffffff00'' creates one<br> instance for each /24 destination subnet.</p><p>The FLOW_MASK, together with the SCHED_MASK, is used to split packets<br> into flows. As an example, using ``src-ip 0x000000ff'' together with the<br> previous SCHED_MASK makes a flow for each individual source address. In<br> turn, flows for each /24 subnet will be sent to the same scheduler<br> instance.</p><p>The above diagram holds even for the pipe case, with the only restriction<br> that a pipe only supports a SCHED_MASK, and forces the use of a FIFO<br> scheduler (these are for backward compatibility reasons; in fact, inter‐<br> nally, a dummynet's pipe is implemented exactly as above).</p><p>There are two modes of dummynet operation: “normal” and “fast”. The<br> “normal” mode tries to emulate a real link: the dummynet scheduler<br> ensures that the packet will not leave the pipe faster than it would on<br> the real link with a given bandwidth. The “fast” mode allows certain<br> packets to bypass the dummynet scheduler (if packet flow does not exceed<br> pipe's bandwidth). This is the reason why the “fast” mode requires less<br> CPU cycles per packet (on average) and packet latency can be signifi‐<br> cantly lower in comparison to a real link with the same bandwidth. The<br> default mode is “normal”. The “fast” mode can be enabled by setting the<br> net.inet.ip.dummynet.io_fast sysctl(8) variable to a non-zero value.</p><p>PIPE, QUEUE AND SCHEDULER CONFIGURATION<br> The pipe, queue and scheduler configuration commands are the following:</p><p>pipe number config pipe-configuration</p><p>queue number config queue-configuration</p><p>sched number config sched-configuration</p><p>The following parameters can be configured for a pipe:</p><p>bw bandwidth | device<br> Bandwidth, measured in [K|M]{bit/s|Byte/s}.</p><p>A value of 0 (default) means unlimited bandwidth. The unit must<br> immediately follow the number, as in</p><p>ipfw pipe 1 config bw 300Kbit/s</p><p>If a device name is specified instead of a numeric value, as in</p><p>ipfw pipe 1 config bw tun0</p><p>then the transmit clock is supplied by the specified device. At<br> the moment only the tun(4) device supports this functionality,<br> for use in conjunction with ppp(8).</p><p>delay ms-delay<br> Propagation delay, measured in milliseconds. The value is<br> rounded to the next multiple of the clock tick (typically 10ms,<br> but it is a good practice to run kernels with “options HZ=1000”<br> to reduce the granularity to 1ms or less). The default value is<br> 0, meaning no delay.</p><p>burst size<br> If the data to be sent exceeds the pipe's bandwidth limit (and<br> the pipe was previously idle), up to size bytes of data are<br> allowed to bypass the dummynet scheduler, and will be sent as<br> fast as the physical link allows. Any additional data will be<br> transmitted at the rate specified by the pipe bandwidth. The<br> burst size depends on how long the pipe has been idle; the effec‐<br> tive burst size is calculated as follows: MAX( size , bw *<br> pipe_idle_time).</p><p>profile filename<br> A file specifying the additional overhead incurred in the trans‐<br> mission of a packet on the link.</p><p>Some link types introduce extra delays in the transmission of a<br> packet, e.g., because of MAC level framing, contention on the use<br> of the channel, MAC level retransmissions and so on. From our<br> point of view, the channel is effectively unavailable for this<br> extra time, which is constant or variable depending on the link<br> type. Additionally, packets may be dropped after this time<br> (e.g., on a wireless link after too many retransmissions). We<br> can model the additional delay with an empirical curve that rep‐<br> resents its distribution.</p><p>cumulative probability<br> 1.0 ^<br> |<br> L +-- loss-level x<br> | ******<br> | *<br> | *****<br> | *<br> | **<br> | *<br> +-------*-------------------><br> delay<br> The empirical curve may have both vertical and horizontal lines.<br> Vertical lines represent constant delay for a range of probabili‐<br> ties. Horizontal lines correspond to a discontinuity in the<br> delay distribution: the pipe will use the largest delay for a<br> given probability.</p><p>The file format is the following, with whitespace acting as a<br> separator and '#' indicating the beginning a comment:</p><p>name identifier<br> optional name (listed by "ipfw pipe show") to identify<br> the delay distribution;</p><p>bw value<br> the bandwidth used for the pipe. If not specified here,<br> it must be present explicitly as a configuration parame‐<br> ter for the pipe;</p><p>loss-level L<br> the probability above which packets are lost. (0.0 <= L<br> <= 1.0, default 1.0 i.e., no loss);</p><p>samples N<br> the number of samples used in the internal representation<br> of the curve (2..1024; default 100);</p><p>delay prob | prob delay<br> One of these two lines is mandatory and defines the for‐<br> mat of the following lines with data points.</p><p>XXX YYY<br> 2 or more lines representing points in the curve, with<br> either delay or probability first, according to the cho‐<br> sen format. The unit for delay is milliseconds. Data<br> points do not need to be sorted. Also, the number of<br> actual lines can be different from the value of the "sam‐<br> ples" parameter: ipfw utility will sort and interpolate<br> the curve as needed.</p><p>Example of a profile file:</p><p>name bla_bla_bla<br> samples 100<br> loss-level 0.86<br> prob delay<br> 0 200 # minimum overhead is 200ms<br> 0.5 200<br> 0.5 300<br> 0.8 1000<br> 0.9 1300<br> 1 1300<br> #configuration file end</p><p>The following parameters can be configured for a queue:</p><p>pipe pipe_nr<br> Connects a queue to the specified pipe. Multiple queues (with<br> the same or different weights) can be connected to the same pipe,<br> which specifies the aggregate rate for the set of queues.</p><p>weight weight<br> Specifies the weight to be used for flows matching this queue.<br> The weight must be in the range 1..100, and defaults to 1.</p><p>The following case-insensitive parameters can be configured for a sched‐<br> uler:</p><p>type {fifo | wf2q+ | rr | qfq}<br> specifies the scheduling algorithm to use.<br> fifo is just a FIFO scheduler (which means that all packets<br> are stored in the same queue as they arrive to the sched‐<br> uler). FIFO has O(1) per-packet time complexity, with<br> very low constants (estimate 60-80ns on a 2GHz desktop<br> machine) but gives no service guarantees.<br> wf2q+ implements the WF2Q+ algorithm, which is a Weighted Fair<br> Queueing algorithm which permits flows to share bandwidth<br> according to their weights. Note that weights are not<br> priorities; even a flow with a minuscule weight will<br> never starve. WF2Q+ has O(log N) per-packet processing<br> cost, where N is the number of flows, and is the default<br> algorithm used by previous versions dummynet's queues.<br> rr implements the Deficit Round Robin algorithm, which has<br> O(1) processing costs (roughly, 100-150ns per packet) and<br> permits bandwidth allocation according to weights, but<br> with poor service guarantees.<br> qfq implements the QFQ algorithm, which is a very fast vari‐<br> ant of WF2Q+, with similar service guarantees and O(1)<br> processing costs (roughly, 200-250ns per packet).</p><p>In addition to the type, all parameters allowed for a pipe can also be<br> specified for a scheduler.</p><p>Finally, the following parameters can be configured for both pipes and<br> queues:</p><p>buckets hash-table-size<br> Specifies the size of the hash table used for storing the various<br> queues. Default value is 64 controlled by the sysctl(8) variable<br> net.inet.ip.dummynet.hash_size, allowed range is 16 to 65536.</p><p>mask mask-specifier<br> Packets sent to a given pipe or queue by an ipfw rule can be fur‐<br> ther classified into multiple flows, each of which is then sent to<br> a different dynamic pipe or queue. A flow identifier is con‐<br> structed by masking the IP addresses, ports and protocol types as<br> specified with the mask options in the configuration of the pipe or<br> queue. For each different flow identifier, a new pipe or queue is<br> created with the same parameters as the original object, and match‐<br> ing packets are sent to it.</p><p>Thus, when dynamic pipes are used, each flow will get the same<br> bandwidth as defined by the pipe, whereas when dynamic queues are<br> used, each flow will share the parent's pipe bandwidth evenly with<br> other flows generated by the same queue (note that other queues<br> with different weights might be connected to the same pipe).<br> Available mask specifiers are a combination of one or more of the<br> following:</p><p>dst-ip mask, dst-ip6 mask, src-ip mask, src-ip6 mask, dst-port<br> mask, src-port mask, flow-id mask, proto mask or all,</p><p>where the latter means all bits in all fields are significant.</p><p>noerror<br> When a packet is dropped by a dummynet queue or pipe, the error is<br> normally reported to the caller routine in the kernel, in the same<br> way as it happens when a device queue fills up. Setting this<br> option reports the packet as successfully delivered, which can be<br> needed for some experimental setups where you want to simulate loss<br> or congestion at a remote router.</p><p>plr packet-loss-rate<br> Packet loss rate. Argument packet-loss-rate is a floating-point<br> number between 0 and 1, with 0 meaning no loss, 1 meaning 100%<br> loss. The loss rate is internally represented on 31 bits.</p><p>queue {slots | sizeKbytes}<br> Queue size, in slots or KBytes. Default value is 50 slots, which<br> is the typical queue size for Ethernet devices. Note that for slow<br> speed links you should keep the queue size short or your traffic<br> might be affected by a significant queueing delay. E.g., 50 max-<br> sized ethernet packets (1500 bytes) mean 600Kbit or 20s of queue on<br> a 30Kbit/s pipe. Even worse effects can result if you get packets<br> from an interface with a much larger MTU, e.g. the loopback inter‐<br> face with its 16KB packets. The sysctl(8) variables<br> net.inet.ip.dummynet.pipe_byte_limit and<br> net.inet.ip.dummynet.pipe_slot_limit control the maximum lengths<br> that can be specified.</p><p>red | gred w_q/min_th/max_th/max_p<br> Make use of the RED (Random Early Detection) queue management algo‐<br> rithm. w_q and max_p are floating point numbers between 0 and 1 (0<br> not included), while min_th and max_th are integer numbers specify‐<br> ing thresholds for queue management (thresholds are computed in<br> bytes if the queue has been defined in bytes, in slots otherwise).<br> The dummynet also supports the gentle RED variant (gred). Three<br> sysctl(8) variables can be used to control the RED behaviour:</p><p>net.inet.ip.dummynet.red_lookup_depth<br> specifies the accuracy in computing the average queue when<br> the link is idle (defaults to 256, must be greater than<br> zero)</p><p>net.inet.ip.dummynet.red_avg_pkt_size<br> specifies the expected average packet size (defaults to<br> 512, must be greater than zero)</p><p>net.inet.ip.dummynet.red_max_pkt_size<br> specifies the expected maximum packet size, only used when<br> queue thresholds are in bytes (defaults to 1500, must be<br> greater than zero).</p><p>When used with IPv6 data, dummynet currently has several limitations.<br> Information necessary to route link-local packets to an interface is not<br> available after processing by dummynet so those packets are dropped in<br> the output path. Care should be taken to ensure that link-local packets<br> are not passed to dummynet.</p><p>CHECKLIST<br> Here are some important points to consider when designing your rules:</p><p>· Remember that you filter both packets going in and out. Most connec‐<br> tions need packets going in both directions.</p><p>· Remember to test very carefully. It is a good idea to be near the<br> console when doing this. If you cannot be near the console, use an<br> auto-recovery script such as the one in<br> /usr/share/examples/ipfw/change_rules.sh.</p><p>· Do not forget the loopback interface.</p><p>FINE POINTS<br> · There are circumstances where fragmented datagrams are uncondition‐<br> ally dropped. TCP packets are dropped if they do not contain at<br> least 20 bytes of TCP header, UDP packets are dropped if they do not<br> contain a full 8 byte UDP header, and ICMP packets are dropped if<br> they do not contain 4 bytes of ICMP header, enough to specify the<br> ICMP type, code, and checksum. These packets are simply logged as<br> “pullup failed” since there may not be enough good data in the packet<br> to produce a meaningful log entry.</p><p>· Another type of packet is unconditionally dropped, a TCP packet with<br> a fragment offset of one. This is a valid packet, but it only has<br> one use, to try to circumvent firewalls. When logging is enabled,<br> these packets are reported as being dropped by rule -1.</p><p>· If you are logged in over a network, loading the kld(4) version of<br> ipfw is probably not as straightforward as you would think. The fol‐<br> lowing command line is recommended:</p><p>kldload ipfw && \<br> ipfw add 32000 allow ip from any to any</p><p>Along the same lines, doing an</p><p>ipfw flush</p><p>in similar surroundings is also a bad idea.</p><p>· The ipfw filter list may not be modified if the system security level<br> is set to 3 or higher (see init(8) for information on system security<br> levels).</p><p>PACKET DIVERSION<br> A divert(4) socket bound to the specified port will receive all packets<br> diverted to that port. If no socket is bound to the destination port, or<br> if the divert module is not loaded, or if the kernel was not compiled<br> with divert socket support, the packets are dropped.</p><p>NETWORK ADDRESS TRANSLATION (NAT)<br> ipfw support in-kernel NAT using the kernel version of libalias(3).</p><p>The nat configuration command is the following:</p><p>nat nat_number config nat-configuration</p><p>The following parameters can be configured:</p><p>ip ip_address<br> Define an ip address to use for aliasing.</p><p>if nic Use ip address of NIC for aliasing, dynamically changing it if<br> NIC's ip address changes.</p><p>log Enable logging on this nat instance.</p><p>deny_in<br> Deny any incoming connection from outside world.</p><p>same_ports<br> Try to leave the alias port numbers unchanged from the actual<br> local port numbers.</p><p>unreg_only<br> Traffic on the local network not originating from an unregistered<br> address spaces will be ignored.</p><p>reset Reset table of the packet aliasing engine on address change.</p><p>reverse<br> Reverse the way libalias handles aliasing.</p><p>proxy_only<br> Obey transparent proxy rules only, packet aliasing is not per‐<br> formed.</p><p>skip_global<br> Skip instance in case of global state lookup (see below).</p><p>Some specials value can be supplied instead of nat_number:</p><p>global Looks up translation state in all configured nat instances. If<br> an entry is found, packet is aliased according to that entry. If<br> no entry was found in any of the instances, packet is passed<br> unchanged, and no new entry will be created. See section<br> MULTIPLE INSTANCES in natd(8) for more information.</p><p>tablearg<br> Uses argument supplied in lookup table. See LOOKUP TABLES sec‐<br> tion below for more information on lookup tables.</p><p>To let the packet continue after being (de)aliased, set the sysctl vari‐<br> able net.inet.ip.fw.one_pass to 0. For more information about aliasing<br> modes, refer to libalias(3). See Section EXAMPLES for some examples<br> about nat usage.</p><p>REDIRECT AND LSNAT SUPPORT IN IPFW<br> Redirect and LSNAT support follow closely the syntax used in natd(8).<br> See Section EXAMPLES for some examples on how to do redirect and lsnat.</p><p>SCTP NAT SUPPORT<br> SCTP nat can be configured in a similar manner to TCP through the ipfw<br> command line tool. The main difference is that sctp nat does not do port<br> translation. Since the local and global side ports will be the same,<br> there is no need to specify both. Ports are redirected as follows:</p><p>nat nat_number config if nic redirect_port sctp<br> ip_address [,addr_list] {[port | port-port] [,ports]}</p><p>Most sctp nat configuration can be done in real-time through the<br> sysctl(8) interface. All may be changed dynamically, though the hash_ta‐<br> ble size will only change for new nat instances. See SYSCTL VARIABLES<br> for more info.</p><p>LOADER TUNABLES<br> Tunables can be set in loader(8) prompt, loader.conf(5) or kenv(1) before<br> ipfw module gets loaded.</p><p>net.inet.ip.fw.default_to_accept: 0<br> Defines ipfw last rule behavior. This value overrides options<br> IPFW_DEFAULT_TO_(ACCEPT|DENY) from kernel configuration file.</p><p>net.inet.ip.fw.tables_max: 128<br> Defines number of tables available in ipfw. Number cannot exceed<br> 65534.</p><p>SYSCTL VARIABLES<br> A set of sysctl(8) variables controls the behaviour of the firewall and<br> associated modules (dummynet, bridge, sctp nat). These are shown below<br> together with their default value (but always check with the sysctl(8)<br> command what value is actually in use) and meaning:</p><p>net.inet.ip.alias.sctp.accept_global_ootb_addip: 0<br> Defines how the nat responds to receipt of global OOTB ASCONF-<br> AddIP:</p><p>0 No response (unless a partially matching association<br> exists - ports and vtags match but global address does<br> not)</p><p>1 nat will accept and process all OOTB global AddIP mes‐<br> sages.</p><p>Option 1 should never be selected as this forms a security risk.<br> An attacker can establish multiple fake associations by sending<br> AddIP messages.</p><p>net.inet.ip.alias.sctp.chunk_proc_limit: 5<br> Defines the maximum number of chunks in an SCTP packet that will<br> be parsed for a packet that matches an existing association.<br> This value is enforced to be greater or equal than<br> net.inet.ip.alias.sctp.initialising_chunk_proc_limit. A high<br> value is a DoS risk yet setting too low a value may result in<br> important control chunks in the packet not being located and<br> parsed.</p><p>net.inet.ip.alias.sctp.error_on_ootb: 1<br> Defines when the nat responds to any Out-of-the-Blue (OOTB) pack‐<br> ets with ErrorM packets. An OOTB packet is a packet that arrives<br> with no existing association registered in the nat and is not an<br> INIT or ASCONF-AddIP packet:</p><p>0 ErrorM is never sent in response to OOTB packets.</p><p>1 ErrorM is only sent to OOTB packets received on the local<br> side.</p><p>2 ErrorM is sent to the local side and on the global side<br> ONLY if there is a partial match (ports and vtags match<br> but the source global IP does not). This value is only<br> useful if the nat is tracking global IP addresses.</p><p>3 ErrorM is sent in response to all OOTB packets on both<br> the local and global side (DoS risk).</p><p>At the moment the default is 0, since the ErrorM packet is not<br> yet supported by most SCTP stacks. When it is supported, and if<br> not tracking global addresses, we recommend setting this value to<br> 1 to allow multi-homed local hosts to function with the nat. To<br> track global addresses, we recommend setting this value to 2 to<br> allow global hosts to be informed when they need to (re)send an<br> ASCONF-AddIP. Value 3 should never be chosen (except for debug‐<br> ging) as the nat will respond to all OOTB global packets (a DoS<br> risk).</p><p>net.inet.ip.alias.sctp.hashtable_size: 2003<br> Size of hash tables used for nat lookups (100 < prime_number ><br> 1000001). This value sets the hash table size for any future<br> created nat instance and therefore must be set prior to creating<br> a nat instance. The table sizes may be changed to suit specific<br> needs. If there will be few concurrent associations, and memory<br> is scarce, you may make these smaller. If there will be many<br> thousands (or millions) of concurrent associations, you should<br> make these larger. A prime number is best for the table size.<br> The sysctl update function will adjust your input value to the<br> next highest prime number.</p><p>net.inet.ip.alias.sctp.holddown_time: 0<br> Hold association in table for this many seconds after receiving a<br> SHUTDOWN-COMPLETE. This allows endpoints to correct shutdown<br> gracefully if a shutdown_complete is lost and retransmissions are<br> required.</p><p>net.inet.ip.alias.sctp.init_timer: 15<br> Timeout value while waiting for (INIT-ACK|AddIP-ACK). This value<br> cannot be 0.</p><p>net.inet.ip.alias.sctp.initialising_chunk_proc_limit: 2<br> Defines the maximum number of chunks in an SCTP packet that will<br> be parsed when no existing association exists that matches that<br> packet. Ideally this packet will only be an INIT or ASCONF-AddIP<br> packet. A higher value may become a DoS risk as malformed pack‐<br> ets can consume processing resources.</p><p>net.inet.ip.alias.sctp.param_proc_limit: 25<br> Defines the maximum number of parameters within a chunk that will<br> be parsed in a packet. As for other similar sysctl variables,<br> larger values pose a DoS risk.</p><p>net.inet.ip.alias.sctp.log_level: 0<br> Level of detail in the system log messages (0 - minimal, 1 -<br> event, 2 - info, 3 - detail, 4 - debug, 5 - max debug). May be a<br> good option in high loss environments.</p><p>net.inet.ip.alias.sctp.shutdown_time: 15<br> Timeout value while waiting for SHUTDOWN-COMPLETE. This value<br> cannot be 0.</p><p>net.inet.ip.alias.sctp.track_global_addresses: 0<br> Enables/disables global IP address tracking within the nat and<br> places an upper limit on the number of addresses tracked for each<br> association:</p><p>0 Global tracking is disabled</p><p>>1 Enables tracking, the maximum number of addresses tracked<br> for each association is limited to this value</p><p>This variable is fully dynamic, the new value will be adopted for<br> all newly arriving associations, existing associations are<br> treated as they were previously. Global tracking will decrease<br> the number of collisions within the nat at a cost of increased<br> processing load, memory usage, complexity, and possible nat state<br> problems in complex networks with multiple nats. We recommend<br> not tracking global IP addresses, this will still result in a<br> fully functional nat.</p><p>net.inet.ip.alias.sctp.up_timer: 300<br> Timeout value to keep an association up with no traffic. This<br> value cannot be 0.</p><p>net.inet.ip.dummynet.expire: 1<br> Lazily delete dynamic pipes/queue once they have no pending traf‐<br> fic. You can disable this by setting the variable to 0, in which<br> case the pipes/queues will only be deleted when the threshold is<br> reached.</p><p>net.inet.ip.dummynet.hash_size: 64<br> Default size of the hash table used for dynamic pipes/queues.<br> This value is used when no buckets option is specified when con‐<br> figuring a pipe/queue.</p><p>net.inet.ip.dummynet.io_fast: 0<br> If set to a non-zero value, the “fast” mode of dummynet operation<br> (see above) is enabled.</p><p>net.inet.ip.dummynet.io_pkt<br> Number of packets passed to dummynet.</p><p>net.inet.ip.dummynet.io_pkt_drop<br> Number of packets dropped by dummynet.</p><p>net.inet.ip.dummynet.io_pkt_fast<br> Number of packets bypassed by the dummynet scheduler.</p><p>net.inet.ip.dummynet.max_chain_len: 16<br> Target value for the maximum number of pipes/queues in a hash<br> bucket. The product max_chain_len*hash_size is used to determine<br> the threshold over which empty pipes/queues will be expired even<br> when net.inet.ip.dummynet.expire=0.</p><p>net.inet.ip.dummynet.red_lookup_depth: 256</p><p>net.inet.ip.dummynet.red_avg_pkt_size: 512</p><p>net.inet.ip.dummynet.red_max_pkt_size: 1500<br> Parameters used in the computations of the drop probability for<br> the RED algorithm.</p><p>net.inet.ip.dummynet.pipe_byte_limit: 1048576</p><p>net.inet.ip.dummynet.pipe_slot_limit: 100<br> The maximum queue size that can be specified in bytes or packets.<br> These limits prevent accidental exhaustion of resources such as<br> mbufs. If you raise these limits, you should make sure the sys‐<br> tem is configured so that sufficient resources are available.</p><p>net.inet.ip.fw.autoinc_step: 100<br> Delta between rule numbers when auto-generating them. The value<br> must be in the range 1..1000.</p><p>net.inet.ip.fw.curr_dyn_buckets: net.inet.ip.fw.dyn_buckets<br> The current number of buckets in the hash table for dynamic rules<br> (readonly).</p><p>net.inet.ip.fw.debug: 1<br> Controls debugging messages produced by ipfw.</p><p>net.inet.ip.fw.default_rule: 65535<br> The default rule number (read-only). By the design of ipfw, the<br> default rule is the last one, so its number can also serve as the<br> highest number allowed for a rule.</p><p>net.inet.ip.fw.dyn_buckets: 256<br> The number of buckets in the hash table for dynamic rules. Must<br> be a power of 2, up to 65536. It only takes effect when all<br> dynamic rules have expired, so you are advised to use a flush<br> command to make sure that the hash table is resized.</p><p>net.inet.ip.fw.dyn_count: 3<br> Current number of dynamic rules (read-only).</p><p>net.inet.ip.fw.dyn_keepalive: 1<br> Enables generation of keepalive packets for keep-state rules on<br> TCP sessions. A keepalive is generated to both sides of the con‐<br> nection every 5 seconds for the last 20 seconds of the lifetime<br> of the rule.</p><p>net.inet.ip.fw.dyn_max: 8192<br> Maximum number of dynamic rules. When you hit this limit, no<br> more dynamic rules can be installed until old ones expire.</p><p>net.inet.ip.fw.dyn_ack_lifetime: 300</p><p>net.inet.ip.fw.dyn_syn_lifetime: 20</p><p>net.inet.ip.fw.dyn_fin_lifetime: 1</p><p>net.inet.ip.fw.dyn_rst_lifetime: 1</p><p>net.inet.ip.fw.dyn_udp_lifetime: 5</p><p>net.inet.ip.fw.dyn_short_lifetime: 30<br> These variables control the lifetime, in seconds, of dynamic<br> rules. Upon the initial SYN exchange the lifetime is kept short,<br> then increased after both SYN have been seen, then decreased<br> again during the final FIN exchange or when a RST is received.<br> Both dyn_fin_lifetime and dyn_rst_lifetime must be strictly lower<br> than 5 seconds, the period of repetition of keepalives. The<br> firewall enforces that.</p><p>net.inet.ip.fw.enable: 1<br> Enables the firewall. Setting this variable to 0 lets you run<br> your machine without firewall even if compiled in.</p><p>net.inet6.ip6.fw.enable: 1<br> provides the same functionality as above for the IPv6 case.</p><p>net.inet.ip.fw.one_pass: 1<br> When set, the packet exiting from the dummynet pipe or from<br> ng_ipfw(4) node is not passed though the firewall again. Other‐<br> wise, after an action, the packet is reinjected into the firewall<br> at the next rule.</p><p>net.inet.ip.fw.tables_max: 128<br> Maximum number of tables.</p><p>net.inet.ip.fw.verbose: 1<br> Enables verbose messages.</p><p>net.inet.ip.fw.verbose_limit: 0<br> Limits the number of messages produced by a verbose firewall.</p><p>net.inet6.ip6.fw.deny_unknown_exthdrs: 1<br> If enabled packets with unknown IPv6 Extension Headers will be<br> denied.</p><p>net.link.ether.ipfw: 0<br> Controls whether layer-2 packets are passed to ipfw. Default is<br> no.</p><p>net.link.bridge.ipfw: 0<br> Controls whether bridged packets are passed to ipfw. Default is<br> no.</p><p>EXAMPLES<br> There are far too many possible uses of ipfw so this Section will only<br> give a small set of examples.</p><p>BASIC PACKET FILTERING<br> This command adds an entry which denies all tcp packets from<br> cracker.evil.org to the telnet port of wolf.tambov.su from being for‐<br> warded by the host:</p><p>ipfw add deny tcp from cracker.evil.org to wolf.tambov.su telnet</p><p>This one disallows any connection from the entire cracker's network to my<br> host:</p><p>ipfw add deny ip from 123.45.67.0/24 to my.host.org</p><p>A first and efficient way to limit access (not using dynamic rules) is<br> the use of the following rules:</p><p>ipfw add allow tcp from any to any established<br> ipfw add allow tcp from net1 portlist1 to net2 portlist2 setup<br> ipfw add allow tcp from net3 portlist3 to net3 portlist3 setup<br> ...<br> ipfw add deny tcp from any to any</p><p>The first rule will be a quick match for normal TCP packets, but it will<br> not match the initial SYN packet, which will be matched by the setup<br> rules only for selected source/destination pairs. All other SYN packets<br> will be rejected by the final deny rule.</p><p>If you administer one or more subnets, you can take advantage of the<br> address sets and or-blocks and write extremely compact rulesets which<br> selectively enable services to blocks of clients, as below:</p><p>goodguys="{ 10.1.2.0/24{20,35,66,18} or 10.2.3.0/28{6,3,11} }"<br> badguys="10.1.2.0/24{8,38,60}"</p><p>ipfw add allow ip from ${goodguys} to any<br> ipfw add deny ip from ${badguys} to any<br> ... normal policies ...</p><p>The verrevpath option could be used to do automated anti-spoofing by<br> adding the following to the top of a ruleset:</p><p>ipfw add deny ip from any to any not verrevpath in</p><p>This rule drops all incoming packets that appear to be coming to the sys‐<br> tem on the wrong interface. For example, a packet with a source address<br> belonging to a host on a protected internal network would be dropped if<br> it tried to enter the system from an external interface.</p><p>The antispoof option could be used to do similar but more restricted<br> anti-spoofing by adding the following to the top of a ruleset:</p><p>ipfw add deny ip from any to any not antispoof in</p><p>This rule drops all incoming packets that appear to be coming from<br> another directly connected system but on the wrong interface. For exam‐<br> ple, a packet with a source address of 192.168.0.0/24, configured on<br> fxp0, but coming in on fxp1 would be dropped.</p><p>The setdscp option could be used to (re)mark user traffic, by adding the<br> following to the appropriate place in ruleset:</p><p>ipfw add setdscp be ip from any to any dscp af11,af21</p><p>DYNAMIC RULES<br> In order to protect a site from flood attacks involving fake TCP packets,<br> it is safer to use dynamic rules:</p><p>ipfw add check-state<br> ipfw add deny tcp from any to any established<br> ipfw add allow tcp from my-net to any setup keep-state</p><p>This will let the firewall install dynamic rules only for those connec‐<br> tion which start with a regular SYN packet coming from the inside of our<br> network. Dynamic rules are checked when encountering the first occur‐<br> rence of a check-state, keep-state or limit rule. A check-state rule<br> should usually be placed near the beginning of the ruleset to minimize<br> the amount of work scanning the ruleset. Your mileage may vary.</p><p>To limit the number of connections a user can open you can use the fol‐<br> lowing type of rules:</p><p>ipfw add allow tcp from my-net/24 to any setup limit src-addr 10<br> ipfw add allow tcp from any to me setup limit src-addr 4</p><p>The former (assuming it runs on a gateway) will allow each host on a /24<br> network to open at most 10 TCP connections. The latter can be placed on<br> a server to make sure that a single client does not use more than 4<br> simultaneous connections.</p><p>BEWARE: stateful rules can be subject to denial-of-service attacks by a<br> SYN-flood which opens a huge number of dynamic rules. The effects of<br> such attacks can be partially limited by acting on a set of sysctl(8)<br> variables which control the operation of the firewall.</p><p>Here is a good usage of the list command to see accounting records and<br> timestamp information:</p><p>ipfw -at list</p><p>or in short form without timestamps:</p><p>ipfw -a list</p><p>which is equivalent to:</p><p>ipfw show</p><p>Next rule diverts all incoming packets from 192.168.2.0/24 to divert port<br> 5000:</p><p>ipfw divert 5000 ip from 192.168.2.0/24 to any in</p><p>TRAFFIC SHAPING<br> The following rules show some of the applications of ipfw and dummynet<br> for simulations and the like.</p><p>This rule drops random incoming packets with a probability of 5%:</p><p>ipfw add prob 0.05 deny ip from any to any in</p><p>A similar effect can be achieved making use of dummynet pipes:</p><p>ipfw add pipe 10 ip from any to any<br> ipfw pipe 10 config plr 0.05</p><p>We can use pipes to artificially limit bandwidth, e.g. on a machine act‐<br> ing as a router, if we want to limit traffic from local clients on<br> 192.168.2.0/24 we do:</p><p>ipfw add pipe 1 ip from 192.168.2.0/24 to any out<br> ipfw pipe 1 config bw 300Kbit/s queue 50KBytes</p><p>note that we use the out modifier so that the rule is not used twice.<br> Remember in fact that ipfw rules are checked both on incoming and outgo‐<br> ing packets.</p><p>Should we want to simulate a bidirectional link with bandwidth limita‐<br> tions, the correct way is the following:</p><p>ipfw add pipe 1 ip from any to any out<br> ipfw add pipe 2 ip from any to any in<br> ipfw pipe 1 config bw 64Kbit/s queue 10Kbytes<br> ipfw pipe 2 config bw 64Kbit/s queue 10Kbytes</p><p>The above can be very useful, e.g. if you want to see how your fancy Web<br> page will look for a residential user who is connected only through a<br> slow link. You should not use only one pipe for both directions, unless<br> you want to simulate a half-duplex medium (e.g. AppleTalk, Ethernet,<br> IRDA). It is not necessary that both pipes have the same configuration,<br> so we can also simulate asymmetric links.</p><p>Should we want to verify network performance with the RED queue manage‐<br> ment algorithm:</p><p>ipfw add pipe 1 ip from any to any<br> ipfw pipe 1 config bw 500Kbit/s queue 100 red 0.002/30/80/0.1</p><p>Another typical application of the traffic shaper is to introduce some<br> delay in the communication. This can significantly affect applications<br> which do a lot of Remote Procedure Calls, and where the round-trip-time<br> of the connection often becomes a limiting factor much more than band‐<br> width:</p><p>ipfw add pipe 1 ip from any to any out<br> ipfw add pipe 2 ip from any to any in<br> ipfw pipe 1 config delay 250ms bw 1Mbit/s<br> ipfw pipe 2 config delay 250ms bw 1Mbit/s</p><p>Per-flow queueing can be useful for a variety of purposes. A very simple<br> one is counting traffic:</p><p>ipfw add pipe 1 tcp from any to any<br> ipfw add pipe 1 udp from any to any<br> ipfw add pipe 1 ip from any to any<br> ipfw pipe 1 config mask all</p><p>The above set of rules will create queues (and collect statistics) for<br> all traffic. Because the pipes have no limitations, the only effect is<br> collecting statistics. Note that we need 3 rules, not just the last one,<br> because when ipfw tries to match IP packets it will not consider ports,<br> so we would not see connections on separate ports as different ones.</p><p>A more sophisticated example is limiting the outbound traffic on a net<br> with per-host limits, rather than per-network limits:</p><p>ipfw add pipe 1 ip from 192.168.2.0/24 to any out<br> ipfw add pipe 2 ip from any to 192.168.2.0/24 in<br> ipfw pipe 1 config mask src-ip 0x000000ff bw 200Kbit/s queue<br> 20Kbytes<br> ipfw pipe 2 config mask dst-ip 0x000000ff bw 200Kbit/s queue<br> 20Kbytes</p><p>LOOKUP TABLES<br> In the following example, we need to create several traffic bandwidth<br> classes and we need different hosts/networks to fall into different<br> classes. We create one pipe for each class and configure them accord‐<br> ingly. Then we create a single table and fill it with IP subnets and<br> addresses. For each subnet/host we set the argument equal to the number<br> of the pipe that it should use. Then we classify traffic using a single<br> rule:</p><p>ipfw pipe 1 config bw 1000Kbyte/s<br> ipfw pipe 4 config bw 4000Kbyte/s<br> ...<br> ipfw table 1 add 192.168.2.0/24 1<br> ipfw table 1 add 192.168.0.0/27 4<br> ipfw table 1 add 192.168.0.2 1<br> ...<br> ipfw add pipe tablearg ip from table(1) to any</p><p>Using the fwd action, the table entries may include hostnames and IP<br> addresses.</p><p>ipfw table 1 add 192.168.2.0/24 10.23.2.1<br> ipfw table 1 add 192.168.0.0/27 router1.dmz<br> ...<br> ipfw add 100 fwd tablearg ip from any to table(1)</p><p>In the following example per-interface firewall is created:</p><p>ipfw table 10 add vlan20 12000<br> ipfw table 10 add vlan30 13000<br> ipfw table 20 add vlan20 22000<br> ipfw table 20 add vlan30 23000<br> ..<br> ipfw add 100 ipfw skipto tablearg ip from any to any recv<br> 'table(10)' in<br> ipfw add 200 ipfw skipto tablearg ip from any to any xmit<br> 'table(10)' out</p><p>SETS OF RULES<br> To add a set of rules atomically, e.g. set 18:</p><p>ipfw set disable 18<br> ipfw add NN set 18 ... # repeat as needed<br> ipfw set enable 18</p><p>To delete a set of rules atomically the command is simply:</p><p>ipfw delete set 18</p><p>To test a ruleset and disable it and regain control if something goes<br> wrong:</p><p>ipfw set disable 18<br> ipfw add NN set 18 ... # repeat as needed<br> ipfw set enable 18; echo done; sleep 30 && ipfw set disable 18</p><p>Here if everything goes well, you press control-C before the "sleep" ter‐<br> minates, and your ruleset will be left active. Otherwise, e.g. if you<br> cannot access your box, the ruleset will be disabled after the sleep ter‐<br> minates thus restoring the previous situation.</p><p>To show rules of the specific set:</p><p>ipfw set 18 show</p><p>To show rules of the disabled set:</p><p>ipfw -S set 18 show</p><p>To clear a specific rule counters of the specific set:</p><p>ipfw set 18 zero NN</p><p>To delete a specific rule of the specific set:</p><p>ipfw set 18 delete NN</p><p>NAT, REDIRECT AND LSNAT<br> First redirect all the traffic to nat instance 123:</p><p>ipfw add nat 123 all from any to any</p><p>Then to configure nat instance 123 to alias all the outgoing traffic with<br> ip 192.168.0.123, blocking all incoming connections, trying to keep same<br> ports on both sides, clearing aliasing table on address change and keep‐<br> ing a log of traffic/link statistics:</p><p>ipfw nat 123 config ip 192.168.0.123 log deny_in reset same_ports</p><p>Or to change address of instance 123, aliasing table will be cleared (see<br> reset option):</p><p>ipfw nat 123 config ip 10.0.0.1</p><p>To see configuration of nat instance 123:</p><p>ipfw nat 123 show config</p><p>To show logs of all the instances in range 111-999:</p><p>ipfw nat 111-999 show</p><p>To see configurations of all instances:</p><p>ipfw nat show config</p><p>Or a redirect rule with mixed modes could looks like:</p><p>ipfw nat 123 config redirect_addr 10.0.0.1 10.0.0.66<br> redirect_port tcp 192.168.0.1:80 500<br> redirect_proto udp 192.168.1.43 192.168.1.1<br> redirect_addr 192.168.0.10,192.168.0.11<br> 10.0.0.100 # LSNAT<br> redirect_port tcp 192.168.0.1:80,192.168.0.10:22<br> 500 # LSNAT</p><p>or it could be split in:</p><p>ipfw nat 1 config redirect_addr 10.0.0.1 10.0.0.66<br> ipfw nat 2 config redirect_port tcp 192.168.0.1:80 500<br> ipfw nat 3 config redirect_proto udp 192.168.1.43 192.168.1.1<br> ipfw nat 4 config redirect_addr<br> 192.168.0.10,192.168.0.11,192.168.0.12<br> 10.0.0.100<br> ipfw nat 5 config redirect_port tcp<br> 192.168.0.1:80,192.168.0.10:22,192.168.0.20:25 500</p><p>SEE ALSO<br> cpp(1), m4(1), altq(4), divert(4), dummynet(4), if_bridge(4), ip(4),<br> ipfirewall(4), ng_ipfw(4), protocols(5), services(5), init(8),<br> kldload(8), reboot(8), sysctl(8), syslogd(8)</p><p>HISTORY<br> The ipfw utility first appeared in FreeBSD 2.0. dummynet was introduced<br> in FreeBSD 2.2.8. Stateful extensions were introduced in FreeBSD 4.0.<br> ipfw2 was introduced in Summer 2002.</p><p>AUTHORS<br> Ugen J. S. Antsilevich,<br> Poul-Henning Kamp,<br> Alex Nash,<br> Archie Cobbs,<br> Luigi Rizzo.</p><p>API based upon code written by Daniel Boulet for BSDI.</p><p>Dummynet has been introduced by Luigi Rizzo in 1997-1998.</p><p>Some early work (1999-2000) on the dummynet traffic shaper supported by<br> Akamba Corp.</p><p>The ipfw core (ipfw2) has been completely redesigned and reimplemented by<br> Luigi Rizzo in summer 2002. Further actions and options have been added<br> by various developer over the years.</p><p>In-kernel NAT support written by Paolo Pisati <piso@FreeBSD.org> as part<br> of a Summer of Code 2005 project.</p><p>SCTP nat support has been developed by The Centre for Advanced Internet<br> Architectures (CAIA) <http://www.caia.swin.edu.au>. The primary develop‐<br> ers and maintainers are David Hayes and Jason But. For further informa‐<br> tion visit: ⟨http://www.caia.swin.edu.au/urp/SONATA⟩</p><p>Delay profiles have been developed by Alessandro Cerri and Luigi Rizzo,<br> supported by the European Commission within Projects Onelab and Onelab2.</p><p>BUGS<br> The syntax has grown over the years and sometimes it might be confusing.<br> Unfortunately, backward compatibility prevents cleaning up mistakes made<br> in the definition of the syntax.</p><p>!!! WARNING !!!</p><p>Misconfiguring the firewall can put your computer in an unusable state,<br> possibly shutting down network services and requiring console access to<br> regain control of it.</p><p>Incoming packet fragments diverted by divert are reassembled before<br> delivery to the socket. The action used on those packet is the one from<br> the rule which matches the first fragment of the packet.</p><p>Packets diverted to userland, and then reinserted by a userland process<br> may lose various packet attributes. The packet source interface name<br> will be preserved if it is shorter than 8 bytes and the userland process<br> saves and reuses the sockaddr_in (as does natd(8)); otherwise, it may be<br> lost. If a packet is reinserted in this manner, later rules may be<br> incorrectly applied, making the order of divert rules in the rule<br> sequence very important.</p><p>Dummynet drops all packets with IPv6 link-local addresses.</p><p>Rules using uid or gid may not behave as expected. In particular, incom‐<br> ing SYN packets may have no uid or gid associated with them since they do<br> not yet belong to a TCP connection, and the uid/gid associated with a<br> packet may not be as expected if the associated process calls setuid(2)<br> or similar system calls.</p><p>Rule syntax is subject to the command line environment and some patterns<br> may need to be escaped with the backslash character or quoted appropri‐<br> ately.</p><p>Due to the architecture of libalias(3), ipfw nat is not compatible with<br> the TCP segmentation offloading (TSO). Thus, to reliably nat your net‐<br> work traffic, please disable TSO on your NICs using ifconfig(8).</p><p>ICMP error messages are not implicitly matched by dynamic rules for the<br> respective conversations. To avoid failures of network error detection<br> and path MTU discovery, ICMP error messages may need to be allowed<br> explicitly through static rules.</p><p>Rules using call and return actions may lead to confusing behaviour if<br> ruleset has mistakes, and/or interaction with other subsystems (netgraph,<br> dummynet, etc.) is used. One possible case for this is packet leaving<br> ipfw in subroutine on the input pass, while later on output encountering<br> unpaired return first. As the call stack is kept intact after input<br> pass, packet will suddenly return to the rule number used on input pass,<br> not on output one. Order of processing should be checked carefully to<br> avoid such mistakes.</p><p>FreeBSD 10.3 October 25, 2012 FreeBSD 10.3<br> root@pc1:~ # ipfw nat show config<br> ipfw nat 123 config if igb1 log redirect_port tcp 192.168.3.211:80 80 redirect_port tcp 192.168.3.211:90 90 redirect_port tcp 192.168.3.2:4899 4900 redirect_port tcp 192.168.3.2:1723 1723<br> root@pc1:~ #</p><p>[/bash]</p><span id="mce_marker" data-mce-type="bookmark" data-mce-fragment="1">​</span>

 

 

manual лучше прочитать с попытками взломать тамбовского волка !.
да вроде работает — любой исходящий поток с сервера режет до 30 килобайт
и выдает 13 ошибку.. где то глюк в потолке открылся люк..
работать невозможно а с компьютеров все работает просто летает,
пробилса каким то образом входящий вызов pptp хоть не было правила проброса порта, и соединился с внутренним компом (смотрим netstat netstat -r tcpdump) ну надо понимать что NAT это средство объединения сетей а для ограничения и защиты используется firewall.
Короче в ответ задачи смотреть нехорошо, но вот он (Как у мелкой — математик однако будет — уже в МГУ ездила на Олимпиаду для 6 класса хоть младше).
Реклама http://mccme.ru http://msu.ru

<p>[bash]<br> # fuck! wrong order?? out send 32k in any stream only then 13 error!<br> # flush do not try -me find no time<br> kldunload ipfw<br> kldunload ipfw_nat<br> kldstat<br> #kldload ipdivert<br> #kldload dummynet<br> kldload ipfw<br> kldload ipfw_nat<br> /sbin/ipfw nat show config</p><p>#/sbin/ipfw add 100 allow ip from any to any<br> #/sbin/ipfw add 100 allow ip from 192.168.3.211 to any<br> # conflict with vpn server (route nat ok use natd)<br> #/sbin/ipfw add 40 divert natd ip from 192.168.3.0/24 to any out via igb1<br> #/sbin/ipfw add 40 divert natd ip from any to me in via igb1<br> #/sbin/ipfw add 45 allow ip from 192.168.3.211 to any<br> #/sbin/ipfw add 40 allow ip from 127.0.0.1 to any</p><p># variable defines into rc.conf - edit<br> #/sbin/ipfw nat 123 config if $firewall_nat_interface redirect_port tcp 192.168.3.211:90 90<br> #/sbin/ipfw nat 123 config if igb1 redirect_port tcp 192.168.3.2:1723 1723 redirect_port tcp 192.168.3.2:4899 4900 redirect_port t<br> /sbin/ipfw add 45 nat 123 ip from any to me recv igb1 in<br> /sbin/ipfw add 50 allow ip from any to any in<br> /sbin/ipfw add 55 nat 123 ip from 192.168.3.0/24 to any xmit igb1 out<br> /sbin/ipfw add 100 allow ip from any to any via lo0<br> /sbin/ipfw add 63000 allow icmp from any to any<br> /sbin/ipfw add 65000 allow ip from any to any<br> /sbin/ipfw add 64500 allow ipv6-icmp from any to any<br> #65535 ip deny any<br> /sbin/ipfw nat 123 config if igb1 redirect_port tcp 192.168.3.2:1723 1723 redirect_port tcp 192.168.3.2:4899 4900</p><p>/sbin/ipfw nat 123 show config<br> #<br> # 00045 220448 21244857 nat 123 ip from any to me recv igb1 in<br> # 00045 0 0 nat 123 ip from 192.168.3.0/24 to any xmit igb1 out<br> # 00050 454010 23656338 allow ip from any to any in<br> # 00100 1594 3104317 allow ip from any to any via lo0<br> # 63000 435008 24360532 allow icmp from any to any<br> # 65000 512902 537332856 allow ip from any to any<br> # 65535 2479 232189 deny ip from any to any<br> #root@pc1:~ # ipfw show<br> #00045 7238318 8598021327 nat 123 ip from any to me recv igb1 in<br> #00050 6137780 2058485243 allow ip from any to any in<br> #00055 5895293 1357436434 nat 123 ip from 192.168.3.0/24 to any xmit igb1 out<br> #00100 83966 644609914 allow ip from any to any via lo0<br> #63000 28796 1873578 allow icmp from any to any<br> #64500 0 0 allow ipv6-icmp from any to any<br> #65000 7138190 8369822820 allow ip from any to any<br> #65535 48454 6764215 deny ip from any to any</p><p># root@pc1:/etc# ipfw nat show config<br> # ipfw nat 123 config if igb1 redirect_port tcp 192.168.3.2:4899 4900 redirect_port tcp 192.168.3.2:1723 1723<br> #.</p><p>#vpn pptp at 192.168.3.2<br> route add 192.168.0.0 192.168.3.2</p><p>rc.local соответственно не набирать же вручную<br> ipdivert и dummynet не подгружаются в самом ядре нет модули есть версия 12 не проверял</p><p>[/bash]</p><span id="mce_marker" data-mce-type="bookmark" data-mce-fragment="1">​</span>

 

 

а лучше расписано в оригинале

<p><strong>FreeBSD handbook natd</strong></p><p><strong>27.8. Даемон преобразования сетевых адресов (natd)</strong><br> <strong>Текст предоставил Chern Lee.</strong><br> <strong>27.8.1. Обзор</strong></p><p><strong>Даемон преобразования сетевых адресов (Network Address Translation) во FreeBSD, широко известный как natd(8), является даемоном, который принимает входящие IP-пакеты, изменяет адрес отправителя на адрес локальной машины и повторно отправляет эти пакеты в потоке исходящих пакетов. natd(8) делает это, меняя IP-адрес отправителя и порт таким образом, что когда данные принимаются обратно, он может определить расположение источника начальных данных и переслать их машине, которая запрашивала данные изначально.</strong></p><p><strong>Чаще всего NAT используется для организации так называемого Совместного Использования Интернет.</strong><br> <strong>27.8.2. Настройка</strong></p><p><strong>Из-за исчерпания пространства адресов в IPv4 и увеличения количества пользователей высокоскоростных каналов связи, таких, как кабельное подключение или DSL, необходимость в решении по Совместному Использованию Интернет растёт. Возможность подключить несколько компьютеров через единственное соединение и IP-адрес делает natd(8) подходящим решением.</strong></p><p><strong>Чаще всего у пользователя имеется машина, подключенная к кабельному каналу или каналу DSL с одним IP-адресом и есть желание использовать этот единственный подключенный компьютер для организации доступа в Интернет другим компьютерам в локальной сети.</strong></p><p><strong>Для этого машина FreeBSD, находящаяся в Интернет, должна выступать в роли шлюза. Эта шлюзовая машина должна иметь два сетевых адаптера-один для подключения к маршрутизатору Интернет, а другой для подключения к ЛВС. Все машины в локальной сети подключаются через сетевой концентратор или коммутатор.</strong><br> <strong>Примечание:</strong></p><p><strong>Существует много способов подсоединить локальную сеть к Internet через шлюз FreeBSD. Этот пример показывает шлюз c двумя сетевыми картами.</strong><br> <strong>Структура сети</strong></p><p><strong>Подобная конфигурация часто используется для совместного использования доступа в Интернет. Одна из подключенных к локальной сети машин подключается к Интернет. Остальные машины работают с Интернет посредством этой <<шлюзовой>> машины.</strong><br> <strong>27.8.3. Настройка</strong></p><p><strong>В файле конфигурации ядра должны присутствовать следующие параметры:</strong></p><p><strong>options IPFIREWALL</strong><br> <strong>options IPDIVERT</strong></p><p><strong>Дополнительно, если это нужно, можно добавить следующее:</strong></p><p><strong>options IPFIREWALL_DEFAULT_TO_ACCEPT</strong><br> <strong>options IPFIREWALL_VERBOSE</strong></p><p><strong>В файле /etc/rc.conf должны быть такие строки:</strong></p><p><strong>gateway_enable="YES" 1</strong><br> <strong>firewall_enable="YES" 2</strong><br> <strong>firewall_type="OPEN" 3</strong><br> <strong>natd_enable="YES"</strong><br> <strong>natd_interface="fxp0" 4</strong><br> <strong>natd_flags="" 5</strong></p><p><strong>1</strong><br> <strong>    </strong></p><p><strong>Указывает машине выступать в качестве шлюза. Выполнение команды sysctl net.inet.ip.forwarding=1 приведёт к тому же самому результату.</strong></p><p><strong>2</strong><br> <strong>    </strong></p><p><strong>При загрузке включает использование правил брандмауэра из файла /etc/rc.firewall.</strong></p><p><strong>3</strong><br> <strong>    </strong></p><p><strong>Здесь задается предопределенный набор правил брандмауэра, который разрешает все. Посмотрите файл /etc/rc.firewall для нахождения дополнительных типов.</strong></p><p><strong>4</strong><br> <strong>    </strong></p><p><strong>Указывает, через какой интерфейс передавать пакеты (интерфейс, подключенный к Интернет).</strong></p><p><strong>5</strong><br> <strong>    </strong></p><p><strong>Любые дополнительный параметры, передаваемые при запуске даемону natd(8).</strong></p><p><strong>При использовании вышеуказанных параметров в файле /etc/rc.conf при загрузке будет запущена команда natd -interface fxp0. Эту команду можно запустить и вручную.</strong><br> <strong>Примечание:</strong></p><p><strong>Если для передачи natd(8) набирается слишком много параметров, возможно также использовать конфигурационный файл. В этом случае имя настроечного файла должно быть задано добавлением следующей строки в /etc/rc.conf:</strong></p><p><strong>natd_flags="-f /etc/natd.conf"</strong></p><p><strong>Файл /etc/natd.conf будет содержать перечень конфигурационных параметров, по одному в строке. К примеру, для примера из следующего раздела будет использоваться такой файл:</strong></p><p><strong>redirect_port tcp 192.168.0.2:6667 6667</strong><br> <strong>redirect_port tcp 192.168.0.3:80 80</strong></p><p><strong>Для получения более полной информации о конфигурационном файле прочтите страницу справки по natd(8) относительно параметра -f.</strong></p><p><strong>Каждой машине и интерфейсу в ЛВС должен быть назначен IP-адрес из адресного пространства частных сетей, как это определено в RFC 1918, а в качестве маршрутизатора по умолчанию должен быть задан IP-адрес машины с natd из внутренней сети.</strong></p><p><strong>Например, клиенты A и B в ЛВС имеют IP-адреса 192.168.0.2 и 192.168.0.3, а интерфейс машины с natd в локальной сети имеет IP-адрес 192.168.0.1. Маршрутизатором по умолчанию для клиентов A и B должна быть назначена машина с natd, то есть 192.168.0.1. Внешний, или Интернет-интерфейс машины с natd не требует особых настроек для работы natd(8).</strong><br> <strong>27.8.4. Перенаправление портов</strong></p><p><strong>Минусом использования natd(8) является то, что машины в локальной сети недоступны из Интернет. Клиенты в ЛВС могут выполнять исходящие соединения во внешний мир, но не могут обслуживать входящие. Это является проблемой при запуске служб Интернет на клиентских машинах в локальной сети. Простым решением является перенаправление некоторых портов Интернет машины с natd на клиента локальной сети.</strong></p><p><strong>Пусть, к примеру, сервер IRC запущен на клиенте A, а Web-сервер работает на клиенте B. Чтобы это работало, соединения, принимаемые на портах 6667 (IRC) и 80 (Web), должны перенаправляться на соответствующие машины.</strong></p><p><strong>Программе natd(8) должна быть передана команда -redirect_port с соответствующими параметрами. Синтаксис следующий:</strong></p><p><strong>     -redirect_port proto targetIP:targetPORT[-targetPORT]</strong><br> <strong>                 [aliasIP:]aliasPORT[-aliasPORT]</strong><br> <strong>                 [remoteIP[:remotePORT[-remotePORT]]]</strong></p><p><strong>В примере выше аргументы должен быть такими:</strong></p><p><strong>    -redirect_port tcp 192.168.0.2:6667 6667</strong><br> <strong>    -redirect_port tcp 192.168.0.3:80 80</strong></p><p><strong>При этом будут перенаправлены соответствующие порты tcp на клиентские машины в локальной сети.</strong></p><p><strong>Аргумент -redirect_port может использоваться для указания диапазонов портов, а не конкретного порта. Например, tcp 192.168.0.2:2000-3000 2000-3000 будет перенаправлять все соединения, принимаемые на портах от 2000 до 3000, на порты от 2000 до 3000 клиента A.</strong></p><p><strong>Эти параметры можно указать при непосредственном запуске natd(8), поместить их в параметр natd_flags="" файла /etc/rc.conf, либо передать через конфигурационный файл.</strong></p><p><strong>Для получение информации о других параметрах настройки обратитесь к справочной странице по natd(8)</strong><br> <strong>27.8.5. Перенаправление адреса</strong></p><p><strong>Перенаправление адреса полезно, если имеется несколько адресов IP, и они должны быть на одной машине. В этой ситуации natd(8) может назначить каждому клиенту ЛВС свой собственный внешний IP-адрес. Затем natd(8) преобразует исходящие от клиентов локальной сети пакеты, заменяя IP-адреса на соответствующие внешние, и перенаправляет весь трафик, входящий на некоторый IP-адрес, обратно конкретному клиенту локальной сети. Это также называют статическим NAT. К примеру, пусть IP-адреса 128.1.1.1, 128.1.1.2 и 128.1.1.3 принадлежат шлюзовой машине natd. 128.1.1.1 может использоваться в качестве внешнего IP-адреса шлюзовой машины natd, тогда как 128.1.1.2 и 128.1.1.3 будут перенаправляться обратно к клиентам ЛВС A и B.</strong></p><p><strong>Синтаксис для -redirect_address таков:</strong></p><p><strong>-redirect_address localIP publicIP</strong></p><p><strong>localIP    Внутренний IP-адрес клиента локальной сети.</strong><br> <strong>publicIP    Внешний IP, соответствующий клиенту локальной сети.</strong></p><p><strong>В примере этот аргумент будет выглядеть так:</strong></p><p><strong>-redirect_address 192.168.0.2 128.1.1.2</strong><br> <strong>-redirect_address 192.168.0.3 128.1.1.3</strong></p><p><strong>Как и для -redirect_port, эти аргументы также помещаются в строку natd_flags="" файла /etc/rc.conf или передаются через конфигурационный файл. При перенаправлении адресов нет нужды в перенаправлении портов, потому что перенаправляются все данные, принимаемые для конкретного IP-адреса.</strong></p><p><strong>Внешние IP-адреса машины с natd должны быть активизированы и являться синонимами для внешнего интерфейса. Обратитесь к rc.conf(5), чтобы это сделать.</strong><br> <strong>Пред.     Наверх     След.</strong><br> <strong>27.7. ISDN     Начало     27.9. IP по параллельному порту (PLIP)</strong></p><span id="mce_marker" data-mce-type="bookmark" data-mce-fragment="1">​</span>

 

 

взято отсюда с исправлением:

Роутер на Freebsd 10 для доступа в интернет

Дистрибутив фрюхи часто называют самым подходящим для решения прикладных сетевых задач в локальной сети. Сегодня мы займемся решением одной из сетевых задач — настройкой шлюза на Freebsd 10 для доступа в интернет из локалки. Это простой, популярный и востребованный функционал сервера, который можно расширять дополнительными возможностями.

Введение

Будем использовать следующую версию системы для решения нашей задачи по настройке шлюза:

# uname -v
FreeBSD 10.2-RELEASE-p8 #0 r292756M: Sat Dec 26 22:49:34 MSK 2015 root@freebsd:/usr/obj/usr/src/sys/GENERIC

Если вы еще не установили систему, то рекомендую мою статью с подробным описанием установки Freebsd 10 с видео в конце. Если вдруг будете устанавливать в качестве виртуальной машины на Hyper-V, то у меня есть отдельная заметка на эту тему с описанием поддержки ядром freebsd гипервизора Hyper-V.

На сервере установлены 2 сетевые карты:

  • hn0 — внешний интерфейс, получает интернет от провайдера, настройки по dhcp
  • hn1 — локальная сеть, адрес 10.20.30.1, установлен вручную

В нашу задачу по настройке программного freebsd роутера будет входить настройка маршрутизации на сервере, установка и настройка ipfw, включение nat, настройка локального dhcp и dns сервера.

Если у вас недостаточно опыта и вы не чувствуете в себе сил разобраться с настройкой шлюза самому с помощью консоли сервера — попробуйте дистрибутив на основе centos для организации шлюза и прокси сервера в локальной сети — clearos. С его помощью можно через браузер настроить весь необходимый функционал. В отдельной статье я подробно рассказал о настройке и установке clearos.

Подготовка сервера к настройке шлюза

Подробно вопрос настройки сервера Freebsd 10 я рассмотрел отдельно. Рекомендую ознакомиться с материалом. Здесь я не буду останавливаться на нюансах, а просто приведу команды, которые нам необходимы, без комментариев и подробных пояснений.

Любую настройку я предпочитаю начинать с обновления системы. Выполним его:

# freebsd-update fetch
# freebsd-update install

Теперь установим mc, я привык работать в нем:

# pkg install mc

Включаем синхронизацию времени. Для этого добавляем в /etc/rc.conf

ntpd_enable="YES"

И запускаем демон ntpd:

# service ntpd start

Теперь проверим сетевые настройки. Первый сетевой интерфейс я настроил еще во время установки, поэтому доступ в интернет на сервере уже есть. Вот мой конфиг сети:

hostname="freebsd"
ifconfig_hn0="SYNCDHCP"
ifconfig_hn1="inet 10.20.30.1 netmask 255.255.255.0"
defaultrouter="192.168.1.1"

Не забываем добавить dns сервер в /etc/resolv.conf.

Подготовительный этап завершен. Прежде чем двигаться дальше, я рекомендую проверить все, что было настроено тут, чтобы потом не отвлекаться. Убедитесь, что на самом сервере есть интернет, что он доступен в локальной сети — пингует другие машины и они его. После этого двигайтесь дальше.

Настройка ipfw и ядерного nat на Freebsd 10

Для того, чтобы включить firewall и nat на будущем freebsd маршрутизаторе можно просто подгрузить необходимые модули ядра. Так сделать проще всего и быстрее, но есть нюанс. Как только вы загружаете модуль ipfw, вы теряете доступ к серверу. Если вы работаете не за консолью, а скорее всего это так, тем более если у вас вообще нет доступа к консоли сервера, то делать так не рекомендуется по понятным причинам. Поэтому мы поступим по-другому. Добавим необходимые опции в ядро, в том числе и опцию, которая делает по-умолчанию фаервол открытым, соберем новое ядро и установим его. Так мы не потеряем удаленный доступ к серверу.

Перед сборкой ядра обновим исходники системы. Я предпочитаю это делать через svn. Если он у вас не установлен, то установите:

# pkg install subversion

Теперь обновляем исходники:

# svn checkout https://svn0.ru.freebsd.org/base/release/10.2.0 /usr/src

Копируем стандартное ядро и добавляем туда новые строки:

# cp /usr/src/sys/amd64/conf/GENERIC /usr/src/sys/amd64/conf/GATE
options IPFIREWALL # включаем ipfw
options IPFIREWALL_DEFAULT_TO_ACCEPT # делаем по-умолчанию ipfw открытым
options IPFIREWALL_VERBOSE # включение логирования ipfw
options IPFIREWALL_VERBOSE_LIMIT=50 # ограничение на количество записей в лог от одного правила
options IPDIVERT # для форварда пакетов
options IPFIREWALL_NAT # для nat
options LIBALIAS # просто надо, не помню зачем

Собираем и устанавливаем новое ядро:

# cd /usr/src
# make kernel -s -j4 KERNCONF=GATE

Добавляем в файл /boot/loader.conf строку:

# mcedit /boot/loader.conf
net.inet.ip.fw.one_pass=1

Перезагружаем сервер:

# reboot

Добавляем в /etc/rc.conf следующие строки (комментарии уберите):

gateway_enable="YES" # разрешаем пересылку пакетов между сетевыми интерфейсами
firewall_nat_enable="YES" # включаем ядерный nat
firewall_nat_interface="hn0" # указываем внешний интерфейс для nat
firewall_enable="YES" # включаем ipfw
firewall_script="/usr/local/etc/ipfw/rc.firewall" # указываем путь, где будут лежать настройки ipfw

Идем в указанную папку и создаем там файл для правил ipfw:

# mkdir /usr/local/etc/ipfw && touch /usr/local/etc/ipfw/rc.firewall

Содержание этого конфига приведу в виде ссылки на скачивание уже готового файла с подробными комментариями. Думаю, вы без проблем разберетесь в настройках. Здесь не хочу на этом подробно останавливаться, все же тема настройки ipfw это отдельный разговор, у нас задача настроить роутер. Вот готовый набор правил — rc.firewall. Не забудьте указать свои интерфейсы и ip адреса. Если ошибетесь, потеряете доступ к серверу. Когда все настроите, отключите логирование. Там по-умолчанию стоит запись логов на правила nat и deny all.

Я не рекомендую настраивать firewall, не имея доступа к консоли сервера. Насколько бы вы ни были опытными администраторами, шанс ошибиться есть всегда. Хотя у меня многие вещи доведены до автоматизма и я настраиваю по отработанным шаблонам, все равно иногда возникают ситуации, когда я ошибаюсь и теряю доступ к серверу. Так что в любом случае, при конфигурировании фаервола, убедитесь, что сможете подключиться к серверу и исправить ошибку в случае необходимости.

Копируем скрипт безопасного редактирования правил и делаем его исполняемым:

# cp /usr/share/examples/ipfw/change_rules.sh /usr/local/etc/ipfw_change_rules
# chmod 0700 /usr/local/etc/ipfw_change_rules

Подробно о том, что это за скрипт и как он работает я рассказал в теме по настройке freebsd, ссылку на которую давал в начале. Активируем новые правила запуском скрипта:

# /usr/local/etc/ipfw_change_rules

Откроется список правил в редакторе по-умолчанию. Там уже будут все правила. Можете еще раз их проверить и если все в порядке, сохраняете файл и выходите из редактора. В консоли вы увидите следующее:

редактирование правил ipfw

Проверим примененные правила:

# ipfw show

список правил ipfw

Если доступ к роутеру не потеряли, значит все в порядке. Можно перезагрузить сервер и все добавленные параметры в rc.conf активируются. Сделайте это и попробуйте на каком-нибудь компьютере в сети пропинговать адрес в интернете по ip, к примеру 8.8.8.8. Если пинги пройдут, значит все в порядке.

Поле того, как убедитесь, что ipfw настроен корректно, правила применятся и доступ к серверу есть, можете перевести его из открытого режима работы (последнее правило автоматически устанавливается allow all from any to any) в закрытый. Для этого в файл /boot/loader.conf добавьте строку и перезагрузите сервер:

net.inet.ip.fw.default_to_accept=0

На этом основная настройка шлюза на Freebsd 10 окончена. Клиенты смогут выходить в интернет. Но для удобства необходимо на шлюз установить и настроить dhcp и dns сервер, для обслуживания запросов пользователей. Иначе придется вручную забивать сетевые параметры и использовать сторонний dns сервер.

Установка и настройка dnsmasq

Для нашего роутера на freebsd подойдет любой dns и dhcp сервер. Можно использовать традиционные named и dhcp-server. Но для простоты и удобства, когда не нужен дополнительный функционал, я предпочитаю использовать простой и быстрый в настройке dnsmasq.

Устанавливаем dnsmasq на Freebsd шлюз:

# pkg install dnsmasq

Приводим конфиг к следующему виду:

# mcedit /usr/local/etc/dnsmasq.conf
domain-needed
bogus-priv
interface=hn1
resolv-file=/etc/resolv.conf
dhcp-range=10.20.30.100,10.20.30.200,24h

Добавляем в /etc/rc.conf:

dnsmasq_enable="YES"

Запускаем программу:

# /usr/local/etc/rc.d/dnsmasq start

Все, теперь наш шлюз полностью готов. Настраиваем на клиентах получение настроек по dhcp и проверяем работу интернета.

настройка сетевых параметров по dhcp на клиенте

Информацию о выданных leases dhcp сервера dnsmasq можно посмотреть в файле /var/db/dnsmasq.leases.

Анализ сетевой активности в freebsd с помощью iftop

Иногда хочется посмотреть, что происходит на роутере и кто использует интернет в данный момент. По-умолчанию, в системе нет готового средства для получения этой информации. На помощь нам придет простая программа iftop, которая позволяет в режиме реального времени посмотреть активность на сетевом интерфейсе.

Устанавливаем iftop на настроенный Freebsd шлюз:

# pkg install iftop

Запускаем iftop с указанием интерфейса и отображением используемых портов:

# iftop -i hn1 -P

Видим любопытную картину — кто, куда, по какому порту и с какой скоростью лезет.

просмотр сетевой активности на шлюзе freebsd

Я для примера на одном из компьютеров запустил генератор трафика интернета. Он занял почти весь канал и это стало отлично видно на роутере с помощью iftop. Конечно, эта простая утилита не решает всех вопросов по мониторингу сетевой активности, но для представления текущей картины подходит, если вам не нужно что-то большее.

Заключение

Подведем итог того, что сделали. За короткое время настроили полноценный шлюз (по сути программный роутер) на базе Freebsd 10 для обеспечения выхода в интернет клиентов за сервером. При этом обеспечили автоматическое получение настроек. Даже на скромном виртуальном сервере такой шлюз способен переварить достаточно большой траффик.

Вся настройка занимает буквально 10-15 минут. Основное время уходит на сборку ядра. Чем выше версия Freebsd, тем дольше оно собирается, несмотря на то, что скорости железа существенно возрастают.

Пройдемся по пунктам и разберемся с тем, что конкретно мы сделали:

  1. Подготовили сервер к настройке шлюза.
  2. Пересобрали ядро с необходимыми параметрами.
  3. Настроили ipfw и nat, включили маршрутизацию.
  4. Установили и настроили dnsmasq для раздачи сетевых настроек по dhcp и dns сервера.
  5. Установили iftop для простейшего анализа сетевой активности на внешнем интерфейсе.

Этого достаточно для полноценной работы шлюза на Freebsd 10. Если есть необходимость подсчета пользовательского траффика или ограничения доступа к определенным ресурсам, можно настроить прокси сервер squid и sams2 к нему.

#FreeBSD #Router #lan2lan #ipfw #СерверИнтернет #Раздать_Интернет_на_60_компов_с_одного_ip_без_тормозов


Взламываем новейшую материнку ASUS Z270 Prime — сразу предупреждаю кто попутает модель или ревизию платы — смотреть  hiew или total commander на двоичное сравнение 2-х файлов bios — может сломать ее об коленку с жутким воплем (!) и получить полтысячи проколов — ну или отпаивать восьминожку биоса и нести на программатор. bios slic ( no slp ) Asus Prime  Z270-P кто первый раз видит — для активации винды 7  а потом на основании главной лицензии 7 (pro — ultimate) — 10, с каких дистрибутивов  ставить ищите сами. Прошивать bupdater 1.30 из под dos — можно не припаивать дисковод а загрузиться с hiren boot cd usb flash. http://santosha.no-ip.info/wordpress/Z270P608.CAP

Установка virutalbox Vbox oracle 5.1.22 на FreeBSD — это основная система хост для этого эмулятора — на винде 2012 через раз то не работает сетевой драйвер то нельзя подцепить жесткий диск целиком винчестер с другой системой!
на FreeBSD все работает
основная вещь сразу — know how —
диски без единой ошибки должны быть иначе перезагрузки замучают и собрать ядро oss virtualbox-ose-kmod все с svn и портов!
single user mode!
fsck -y
2 раза точно
tunefs -j disable ada0p2 где ada0p2 диск и раздел на котором freeBSD у меня 3 тб на ahci sata и соответственно такое имя
раздела если он UFS а у вас может и другой.
mount /
cd /
chflags noschg,nosunlnk *
rm .sujournal
повторить 2 раза 4 команды бо не помню в каком порядке
если фряха матом не ругается значит ошибок нет а так смотрим т что не то
tunefs -j enable ada0p2
если ругается то еще раз перезагрузка в однопользовательский режим выбрать 2 при загрузке и повторить не монтировав раздел
fsck -y /
у меня отловил 100500 испорченых блоков и из за них сервис перегружал систему постоянно — как исправилось работает уже полгода.
и еще права доступа на tmp вот так должно быть (а если не так то и portupgrade не работает!)
[code]
root@pc:/# chmod 1777 /tmp
root@pc:/# rm /tmp/.vbox*
rm: /tmp/.vbox-root-ipc: is a directory
root@pc:/# rm -rf /tmp/.vbox*
root@pc:/# virtualbox
[/code]
второй диск винчестер с другой системой или просто новый подсоединяется в virtualbox вот такой командой
[code]
root@pc:/# vboxmanage internalcommands createrawvmdk -filename new-disk-hdd1.vmdk -rawdisk /dev/ada1
смотрим как он там определился ls /dev/ad*
а если система windows 7 -10 вот это не забыть а то напишет лицензия потерялась
root@pc:/# VBoxManage setextradata «vm-windows-7» «VBoxInternal/Devices/acpi/0/Config/CustomTable» «/media/ASUS.BIN»
на новой версии почему то надо подправлять в файлике настроек виртуальной машины!
[/code]
поправляю на винде server 2012 тоже работает в новой версии 5.1.22
но лучше хост для virtualbox все же FreeBSD
сбросить флаг для диска read only
и запускать отключив uac совсем в gpedit.msc все администраторы работают через одобрение администратором
соответственно в параметрах безопасности — контроль учетных записей. Edge в таком режиме не запустится ставьте firefox ..

Re: VM on RAW disk on Windows 7 host

Postby Korkman » 16. Feb 2011, 02:34
Success!

In summary:

To gain full hard drive access in a VBox guest on Win7 host

0. close all open programs or documents on any partition on the disk to pass-through
1. run DISKPART (command line utility)*
2. select hard drive carefully using SELECT DISK. disk numbering starts at zero. you can roughly verify your selection with LIST PARTITION if you know what your partitions should look like or LIST DISK to see disk sizes.
3. offline the disk using OFFLINE DISK. all volumes will disappear from windows explorer.
4. ATTRIBUTES DISK CLEAR READONLY
5. verify with ATTRIBUTES DISK
6. create VMDK file as shown in several howtos on the web
7. enjoy

As always with the dumb numeric representation of physical disks in windows: keep an eye on the ordering of your disks, especially removables, before booting the wrong one.

*administrative rights required for operating vbox and utilities but not for desktop