Документация по ОС FreeBSD Понедельник, 29.04.2024, 11:37
Приветствую Вас Гость | RSS
Меню сайта

Категории каталога
Apache [58]
DNS [25]
FTP [27]
Mail [74]
Samba [24]
Squid [46]
SSH [23]
VPN [35]
РРР [20]
Net [173]

Главная » Статьи » Сеть » Squid

Пример скрипта автоматической настройки dummynet во FreeBSD [2008] (Часть 1)
Автоматический скрипт настройки firewall (ipfw) + shaper (dummynet) для двух-интерфейсной шлюзловой машины под FreeBSD. Данный скрипт расчитан на то, что кроме интернет шлюза, других сервисов на машине нет - иначе придется сделать соответствующие изменения в фаерволе. В скрипт включена поддержка шейпера dummynet. Вся конфигурация выполняется в виде списков доступа, что упрощает настройку фаервола неопытным пользователем, также предусмотрена некоторая оптимизация, отключающая неиспользуемые правила. Дополнительно реализованно несколько полезных с хозяйстве вешей (см. ниже коментарии в самом скрипте). В остальном скрипт базируется на стандартном /etc/rc.firewall.

Что касается использования dummynet: настройка каналов может быть не оптимальной, но как рабочий вариант вполне годится (man ipfw, man dummynet по вопросам тюнинга).

В крипте используется дуплексная эмуляция канала с отдельной настройкой ширины в  каждом напрвлении, с последующей группировкой пользовательких каналов в коллективную трубу. Возможна группировка ip адрессов пользователей в произвольное количество групп (в скрипте реализовано 3 группы, количество групп несложно увеличить) с возможностью дальнейшего задания толщины канала для каждой группы индивидуально.

И кое-что ещо - смотрите коментарии скрипта.

Скрипт приведен с примером рабочей конфигурации (ip адреса вымышленные).

P.S. может комуто понравится или даже поможет :)

#   /etc/rc.firewall
#   Firewall (ipfw) + shaper (dummynet) for gateway host (with natd)
#   Automated ipfw setup script for FreeBSD
#   v 0.7
#   (CopyLeft) Pavel Ustyugov aka Pahanivo
#
################################################################################
#
#   !!! WARNING !!!
#
#   Misconfiguring the firewall can put your computer in an unusable state,
#   possibly shutting down network services and requiring console access to
#   regain control of it.
#
################################################################################
#
#   Usage:
#   make your own settings
#   copy this file to /etc/rc.firewall
#   cd /etc
#   ./netstart &
#
#   For testing use (only show list of rules, do not apply
#   onto current firewall):
#   cd /etc
#   chmod 744 rc.firewall
#   ./rc.firewall testmode
#   Warning: if you run ./rc.firewall without arguments or with any other
#   arguments - firewall will reloaded and settings will apllied.
#
################################################################################
#
#   Before use this firewall you need to compile kernel with options:
#   (or load some as module)
#
#   #IPFW (required)
#   options IPFIREWALL
#   #enable verbose mode (for `log` options, optional)
#   options IPFIREWALL_VERBOSE
#   #enable forward rules (optional)
#   options IPFIREWALL_FORWARD
#   #default rule - allow any to any (optional)
#   options IPFIREWALL_DEFAULT_TO_ACCEPT
#
#   #divert socket (required for natd)
#   options IPDIVERT
#
#   #dummynet shaper (required, if you want use shaper)
#   options DUMMYNET
#   #enable device polling (recomended)
#   #you need enable polling on interface too - man polling
#   options DEVICE_POLLING
#   #pooling frequency (strongly recomended)
#   options HZ=1000 (or HZ=2000)
#
################################################################################
#
#   Shaper scheme (for incoming traffice)
#   ##############################
#
# --------------------external interface / incoming traffic---------------------
#    >                                                                         >
#    >    Unrestricted external resources group                                >
#    >      res1->all_users >=================== unlimit ====================> >
#    >      res2->all_users >=================== unlimit ====================> >
#    >      ...                                                                >
#    >                                                                         >
#    >    Unrestricted users group                                             >
#    >      internet->users1 >================== unlimit ====================> >
#    I      internet->users2 >================== unlimit ====================> >
#    N      ...                                                                >
#    C                                                                         >
#    O    Restricted external resources groups                                 >
#    M      Group 1                                 ---+                       >
#    I      res1_1->all_users \                         \                      >
#    N      res1_2->all_users  >==2048Kbit/s per user==> \                     >
#    G      res1_3->all_users /                           +-----------------\  >
#    >      Group 2                                        10240Kbit/s total > >
#    >      res2_1->all_users \                           +-----------------/  >
#    >      res2_2->all_users  >==1024Kbit/s per user==> /                     >
#    T      res3_3->all_users /                         /                      >
#    R      ...                                     ---+                       >
#    A                                                                         >
#    F    Restricted users groups                                              >
#    F      Group 1                                 ---+                       >
#    I      internet->user1_1 \                         \                      >
#    C      internet->user1_2  >==128Kbit/s per user==>  \                     >
#    >      internet->user1_3 /                           +-----------------\  >
#    >      Group 2                                        1024Kbit/s total  > >
#    >      internet->user2_1 \                           +-----------------/  >
#    >      internet->user2_2  >==256Kbit/s per user==>  /                     >
#    >      internet->user2_3 /                         /                      >
#    >      ...                                     ---+                       >
#    >                                                                         >
#    >    Other ungrouped traffic >============= unlimit ====================> >
#    >                                                                         >
# --------------------external interface / incoming traffic---------------------
#
#   Scheme for outgoing traffic absolutely analogous, but outgoing shaper work
#   on internal interface and all traffic directions in scheme is inverted.
#   Traffic bw for incoming and outgoing shapers setup separately.
#
################################################################################
# Setup
################################################################################

    #Prepare to work
    ##############################

    #Before use this script - recomend to set net.inet.ip.fw.autoinc_step=5
    #or less. Use sysctl or /etc/sysctl.conf

    #System paths
    ipfw_cmd="/sbin/ipfw"
    grep_cmd="/usr/bin/grep"
    dev_null="/dev/null"

################################################################################
  
    #IPFW interfaces setup   
    ##############################

    #Interfaces setup
   
    #Outside interface setup
    oif="xl0"
    onet="123.123.32.0"
    omask="255.255.255.248"
    oip="123.123.32.1"

    #Inside interface setup
    iif="fxp0"
    inet="192.168.0.0"
    imask="255.255.0.0"
    iip="192.168.0.1"

################################################################################

    #Access lists setup
    ##############################

    #ACL - list of allowed (or denied) IPs or newtworks in CIDR notation
    #ACL may contain comments, but any comments in ACL must begin from `#`
    #and not contain any space chars (because ACL process by word).
    #ACLs maybe used in any script's loop (see below).
    #Any of this ACLs maybe loaded from file. Use "`cat /path/file_name`"
    #command inside ACL for loading from file.
    #Example:
    #  pass_lan_users_acl="
    #  10.0.1.0/24
    #  10.0.2.0/24
    #  `cat /etc/ALLOWED_USERS`
    #  "

    #Denied external hosts

    #You can use this for stoping attacks from outside.
    deny_wan_hosts_acl="
    #flooder
    123.123.0.233
    "

    #From LAN to Internet access

    #Denied IPs process before allowed. Access allowed for all IPs in
    #allowed ACL except IPs in denied ACL.

    #Denied LAN users
    deny_lan_users_acl="
    #stupids
    192.168.10.15
    192.168.10.33
    "

    #Allowed LAN users
    pass_lan_users_acl="
    192.168.0.0/16
    "

    #Anti-spambot protection

    #Reject all incoming connection from LAN to any external SMTP servers,
    #except allowed servers (yes or no)
    anti_spambot_enable="yes"

    #Allowed SMTP servers
    #If this ACL empty, anti-spambot feature will automatically disabled,
    #and traffic to any SMTP servers will allowed.
    anti_spambot_allowed_servers_acl="
    #own_smtp_relay
    123.123.32.2
    #own_smtp_relay
    123.123.32.3
    #provider_smtp_relay
    123.123.0.11
    "

    #SSH

    #SSH access to this server from outside
    pass_ssh_acl="
    #admin1
    124.124.124.124
    #admin2
    125.125.125.125
    "

    #Shaper's ACLs

    #Enable shaper (yes or no)
    shaper_enable="yes"

    #Not shaped external resouces
    #All LAN users will have unlimited bw to and from this IPs.
    not_shaped_ext_res_acl="
    #own_smtp_relay
    123.123.32.2
    #own_smtp_relay
    123.123.32.3
    #provider_smtp_relay
    123.123.0.11
    "

    #Not shaped users
    #This users will have unlimit bw from and to any.
    not_shaped_users_acl="
    #Admin's_net
    192.168.33.0/24
    "

    #Shaped external resources - similarly to `shaped user` (see below), but for
    #specific external hosts only. Traffic match this shaper not process by
    #`shaped user`.

    #External resource group 1
    shaped_ext_res_g1_name="own_dataservers"
    shaped_ext_res_g1_acl="
    #own_dataservers
    123.123.32.4
    123.123.32.5
    "

    #External resource group 2
    shaped_ext_res_g2_name="isp_dataservers"
    shaped_ext_res_g2_acl="
    #isp_dataservers
    123.123.0.2
    123.123.0.3
    123.123.0.4
    "

    #External resource group 3
    shaped_ext_res_g3_name="servers_3"
    shaped_ext_res_g3_acl="
    "

    #Add more groups below
    #...

    #Shaped users - will have restricted bw. Other allowed users will have unlimit
    #bw from any to any (except shaped external resources). Shaped users separated
    #by groups. See below for restrictions setup for all groups.
    #Groups process in succession: group 1, group 2 etc. Inside group IPs process
    #in list order. Once processed IP (or subnet) will not process more.
    #Because overlaps in group and between groups not a problem.

    #User group 1
    shaped_users_g1_name="slow"
    shaped_users_g1_acl="
    #looosers
    192.168.20.0/24
    192.168.21.1
    192.168.21.2
    "

    #User group 2
    shaped_users_g2_name="fast"
    shaped_users_g2_acl="
    #BOSS
    192.168.0.5
    "

    #User group 3
    shaped_users_g3_name="default"
    shaped_users_g3_acl="
    192.168.0.0/16
    "

    #Add more groups below
    #...

################################################################################

    #Pipes setup (shaper)
    ##############################

    #Shaped external resources
   
    #External resources group 1
    #Pipe's number
    shaped_ext_res_g1_pipe_num_in="1011"
    shaped_ext_res_g1_pipe_num_out="1012"
    #BW
    shaped_ext_res_g1_bw_in="3Mbit/s"
    shaped_ext_res_g1_bw_out="3Mbit/s"
    #Queue size, in slots or KBytes (see man ipfw).
    shaped_ext_res_g1_q_in="50"
    shaped_ext_res_g1_q_out="50"

    #External resources group 2
    #Pipe's number
    shaped_ext_res_g2_pipe_num_in="1021"
    shaped_ext_res_g2_pipe_num_out="1022"
    #BW
    shaped_ext_res_g2_bw_in="1024Kbit/s"
    shaped_ext_res_g2_bw_out="1024Kbit/s"
    #Queue size, in slots or KBytes (see man ipfw).
    shaped_ext_res_g2_q_in="50"
    shaped_ext_res_g2_q_out="50"

    #External resources group 3
    #Pipe's number
    shaped_ext_res_g3_pipe_num_in="1031"
    shaped_ext_res_g3_pipe_num_out="1032"
    #BW
    shaped_ext_res_g3_bw_in="512Kbit/s"
    shaped_ext_res_g3_bw_out="512Kbit/s"
    #Queue size, in slots or KBytes (see man ipfw).
    shaped_ext_res_g3_q_in="40"
    shaped_ext_res_g3_q_out="40"   

    #Add more groups below
    #...
   
    #Collective external resource's pipe (max allowed summary bw for
    #external resources, except not shaped).
    #Pipe's number
    sum_shaped_ext_res_pipe_num_in="1901"
    sum_shaped_ext_res_pipe_num_out="1902"
    #BW
    sum_shaped_ext_res_bw_in="6Mbit/s"
    sum_shaped_ext_res_bw_out="6Mbit/s"   
    #Queue size, in slots or KBytes (see man ipfw)
    sum_shaped_ext_res_q_in="50"
    sum_shaped_ext_res_q_out="50"

    #Personal pipe for each user (with separate by group)

    #User group 1
    #Pipe's number
    shaped_users_g1_pipe_num_in="2011"
    shaped_users_g1_pipe_num_out="2012"
    #BW
    shaped_users_g1_bw_in="160Kbit/s"
    shaped_users_g1_bw_out="160Kbit/s"
    #Queue size, in slots or KBytes (see man ipfw).
    shaped_users_g1_q_in="18"
    shaped_users_g1_q_out="18"

    #User group 2
    #Pipe's number
    shaped_users_g2_pipe_num_in="2021"
    shaped_users_g2_pipe_num_out="2022"
    #BW
    shaped_users_g2_bw_in="512Kbit/s"
    shaped_users_g2_bw_out="512Kbit/s"
    #Queue size, in slots or KBytes (see man ipfw).
    shaped_users_g2_q_in="40"
    shaped_users_g2_q_out="40"

    #User group 3
    #Pipe's number
    shaped_users_g3_pipe_num_in="2031"
    shaped_users_g3_pipe_num_out="2032"
    #BW
    shaped_users_g3_bw_in="256Kbit/s"
    shaped_users_g3_bw_out="256Kbit/s"
    #Queue size, in slots or KBytes (see man ipfw).
    shaped_users_g3_q_in="25"
    shaped_users_g3_q_out="25"

    #Add more groups below
    #...

    #Collective user's pipe (max allowed summary bw for users, except not
    #shaped).
    #Pipe's number
    sum_shaped_users_pipe_num_in="2901"
    sum_shaped_users_pipe_num_out="2902"
    #BW
    sum_shaped_users_bw_in="768Kbit/s"
    sum_shaped_users_bw_out="768Kbit/s"   
    #Queue size, in slots or KBytes (see man ipfw)
    sum_shaped_users_q_in="50"
    sum_shaped_users_q_out="50"

################################################################################

    #Numeration
    ##############################

    #All ipfw rules split onto section. First rule in each section
    #begin from fixed number. All other rules will numbers by ipfw, consider
    #net.inet.ip.fw.autoinc_step. This script use `skipto` rules, because
    #needs for fixed number. Usually you don't need to change this values,
    #if you have problems this large quantity of rules only.

    f_num_acb=1000   
    f_num_aacb=2000
    f_num_outshb=3000
    f_num_routshb=4000
    f_num_routshb_inj=5500
    f_num_uoutshb=6000
    f_num_uoutshb_inj=7500
    f_num_natb=8000
    f_num_inshb=9000
    f_num_rinshb=10000
    f_num_rinshb_inj=11500
    f_num_uinshb=12000
    f_num_uinshb_inj=13500
    f_num_stdb=14000
    f_num_pcb=30000 # please read below about this
    f_num_lastb=40000

################################################################################
   
    #Auto-config
    ##############################
   
    for loop in \
      ${shaped_ext_res_g1_acl} \
      ${shaped_ext_res_g2_acl} \
      ${shaped_ext_res_g3_acl}
    do
      echo $loop | ${grep_cmd} -v "^#" > ${dev_null}
      if [ $? -eq 0 ]; then
        shaped_ext_res_ne_flag="yes"
        break
      fi
    done

    for loop in \
      ${shaped_users_g1_acl} \
      ${shaped_users_g2_acl} \
      ${shaped_users_g3_acl}
    do
      echo $loop | ${grep_cmd} -v "^#" > ${dev_null}
      if [ $? -eq 0 ]; then
        shaped_users_ne_flag="yes"
        break
      fi
    done

    for loop in ${anti_spambot_allowed_servers_acl}
    do
      echo $loop | ${grep_cmd} -v "^#" > ${dev_null}
      if [ $? -eq 0 ]; then
        anti_spambot_allowed_servers_ne_flag="yes"
        break
      fi
    done

    if [ -z ${anti_spambot_allowed_servers_ne_flag} ]; then
      anti_spambot_enable="no"
    fi
   
    if [ -z ${shaped_ext_res_ne_flag} ] && [ -z ${shaped_users_ne_flag} ]; then
      shaper_enable="no"
    fi

    if [ "$1" = "testmode" ]; then
      ipfw_cmd="echo ipfw"
    fi

################################################################################
# Firewall rules
################################################################################

    #Flush all before set new rules
    ${ipfw_cmd} -f flush
    ${ipfw_cmd} -f pipe flush
    ${ipfw_cmd} -f queue flush

################################################################################

    #Loopback rules (required)
    ${ipfw_cmd} add pass all from any to any via lo0 // loopback
    ${ipfw_cmd} add deny all from any to 127.0.0.0/8 // loopback
    ${ipfw_cmd} add deny all from 127.0.0.0/8 to any // loopback

###############################################################################

    # Stop spoofing
    ${ipfw_cmd} add deny all from ${inet}:${imask} to any in via ${oif} // anti-spoofing
    ${ipfw_cmd} add deny all from ${onet}:${omask} to any in via ${iif} // anti-spoofing

###############################################################################

    #Access control
    ##############################

    #Denied external hosts

    #Apply deny_wan_hosts_acl
    for loop in ${deny_wan_hosts_acl}
    do
      echo $loop | ${grep_cmd} -v "^#" > ${dev_null}
      if [ $? -eq 0 ]; then
        ${ipfw_cmd} add deny all from $loop to any in via ${oif} // denied WAN IPs
      fi
    done

    #Skip all incoming traffic up to divert rules
    ${ipfw_cmd} add skipto ${f_num_natb} all from any to any in via ${oif} // skip incoming traffic up to NAT

    #Allow ICMP for all from inside
    ${ipfw_cmd} add skipto ${f_num_outshb} icmp from ${inet}:${imask} to any in via ${iif} // allow ICMP for any from inside

    #Access from LAN

    ${ipfw_cmd} add ${f_num_acb} count all from any to any // begin access control block

    #Allow SSH from LAN if you are accidentally add yourself in denied users list
    for loop in ${deny_lan_users_acl}
    do
      echo $loop | ${grep_cmd} -v "^#" > ${dev_null}
      if [ $? -eq 0 ]; then
        ${ipfw_cmd} add skipto ${f_num_stdb} tcp from ${inet}:${imask} to ${iip} 22 in via ${iif} // allow SSH from LAN for allowed users
        break
      fi
    done

    #Apply deny_lan_users_acl
    for loop in ${deny_lan_users_acl}
    do
      echo $loop | ${grep_cmd} -v "^#" > ${dev_null}
      if [ $? -eq 0 ]; then
        ${ipfw_cmd} add deny all from $loop to any in via ${iif} // denied LAN IPs
      fi
    done

    #Apply pass_lan_users_acl
    for loop in ${pass_lan_users_acl}
    do
      echo $loop | ${grep_cmd} -v "^#" > ${dev_null}
      if [ $? -eq 0 ]; then
        ${ipfw_cmd} add skipto ${f_num_aacb} all from $loop to any in via ${iif} // allowed LAN IPs
      fi
    done


Источник: http://www.opennet.ru/base/net/ipfwdummynet.txt.html
Категория: Squid | Добавил: oleg (26.03.2008) | Автор: Pavel Ustyugov
Просмотров: 1718 | Рейтинг: 0.0/0 |
Всего комментариев: 0
Добавлять комментарии могут только зарегистрированные пользователи.
[ Регистрация | Вход ]
Форма входа

Beastie

Друзья сайта

Статистика

Онлайн всего: 1
Гостей: 1
Пользователей: 0
links

Copyright MyCorp © 2024