Introdução ao firewall do Mac OSX IPFW

Todos os sistema operacionais baseados em Unix possuem ferramentas nativas de firewall. No caso do Mac OS X não é diferente ele vêm embutido no Kernel do SO. Para usuários não experientes é possível habilitar o recurso através do painel de controle System Preference/Security na Aba firewall marcando simplesmente para ativar o recurso. Mas isto não é tudo, a interface gráfica não é tão poderosa quanto todas as opções que podem ser exploradas no shell, e para isso podemos utilizar o ipfw ( Ip Firewall ) do Mac OSX.
O IPFW é um sistema de firewall nativo no Mac OSX, veja abaixo um exemplo de saída do comando de firewall para listar todas as regras ACL’s carregadas no sistema. Para isso abra o terminal e como super-usuário digite:

ipfw list

O exemplo de saída deste comando é algo como:

2000 allow ip from any to any via lo*
02010 deny ip from 127.0.0.0/8 to any in
02020 deny ip from any to 127.0.0.0/8 in
02030 deny ip from 224.0.0.0/3 to any in
02040 deny tcp from any to 224.0.0.0/3 in
02050 allow tcp from any to any out
02060 allow tcp from any to any established
02070 allow tcp from any to any 80 in
02080 allow tcp from any to any 427 in
12190 deny tcp from any to any
65535 allow ip from any to any

O ipfw é o coração do sistema de firewall do Mac OS X, ele lista e configura as regras de firewall. Vamos análisar um exemplode de saída do comando ipfw list abaixo:

02010 deny ip from 127.0.0.0/8 to any in

02010 - Indica o número da regra de firewall;
deny ip from 127.0.0.0/8 to any in - Nega todas as entradas para o IP 127.0.0.0/8

Ativando o sistema de firewall para carregar no boot do OSX:

sudo sysctl -w net.inet.ip.fw.verbose=1

Exemplos de logs do sistema:
Assim como no Netfilter Iptables do Linux, os logs do firewall são gravados no syslog o arquivo encontra-se no diretório /var/log/system.log. Um exemplo de registro do Ipfw no syslod do OSX pode ser algo como o exemplo abaixo:

Nov 9 21:12:18 Peter-Hickmans-Computer kernel: ipfw: 2060
Accept TCP 216.65.98.71:119 192.168.1.100:54609 in via en0

Como limpar as regras de firewall configurada?
Simples use o seguinte comando:

sudo /sbin/ipfw -f flush

Criando um exemplo de regra para bloquear o acesso ao servidor WEB na porta 80

sudo /sbin/ipfw add 02070 deny tcp from any to any 80 in

Criando um script de firewall no OSX
Aqui iremos criar um script simples de firewall em nosso servidor com OSX, para isso execute os passos descritos abaixo:

sudo mkdir /Library/StartupItems/Firewall

Insira o conteúdo do script abaixo no arquivo de script em /Livrary/StartupItems/Firewall/Firewall

#!/bin/sh
## Boot Script for firewall
#
# thanks and acknowledgements for examples and explanations to
# barijaona
# (see http://homepage.mac.com/barijaona/macintosh/osxpb4.html)
# daniel co^te’
# (http://www3.sympatico.ca/dccote/firewall.html)
# Dru Lavigne
# (http://www.onlamp.com/pub/a/bsd/2001/04/25/FreeBSD_Basics.html)
# and brian hill
# (see http://personalpages.tds.net/~brian_hill/brickhouse.html),
# I recommend brian’s brickhouse for purchase if you’re going to
# do a lot of firewall configuration, it’s a great product
#
# Also see http://www.macdevcenter.com/pub/a/mac/2002/12/27/macosx_firewall.html
# for additional information
#
# Finally, ipfw uses the /subnet mask denotation for declaring network ranges
# For example, 152.2.0.0/16 is the same as 152.2.0.0 with a 255.255.0.0, the
# /16 means that 16 bits of the 32 possible bits are masked.
# Basically, the smaller the /index, the larger the range of addresses encompassed
# This system is somewhat confusing to some folks, but there’s a good online
# subnet calculator you can use to figure out what ranges are covered
# http://ccna.exampointers.com/subnet.htm
#
# Non-stateful, can’t get stateful working under tiger
#
# This version is designed to work with Timelox versions of ssh
# and TheHand but it works as a standalone as well
#
#
#
# 02/06/07 Updated to match standard startup scripts

. /etc/rc.common; # include the file with support for the service functions

########
# Set Variables
########

# Decide how to call ipfw (so you can run in test mode, etc, as you like)
IPFW=”/sbin/ipfw -f”;

# Set up a trusted hosts range
# These numbers represent the main CS networks at UNC
# Change them to meet your needs.
TrustedHosts=”152.2.128.0/20, 204.85.191.0/24″;

# Set up a range of hosts you trust somewhat, but not so much
# In this example, we’re looking at the main unc.edu subnets
NotSoTrustedHosts=”152.2.0.0/16, 152.19.0.0/16, 152.23.0.0/16″;

StartService ()
{
echo “Starting Firewall”

########
# Enable Logging
########
#
# Logged entries go into /var/log/system.log
# But there’s no point in logging unless you’re going to check the
# entries. In this script, all deny are tagged with a log

if [ `/usr/sbin/sysctl -n net.inet.ip.fw.verbose` == 0 ] ; then
/usr/sbin/sysctl -w net.inet.ip.fw.verbose=1
fi

## To disable logging, comment out the above lines and uncomment the following:
#/usr/sbin/sysctl -w net.inet.ip.fw.verbose=0

/usr/sbin/sysctl -w net.inet.ip.fw.dyn_max=8192 > /dev/null;
/usr/sbin/sysctl -w net.inet.ip.fw.dyn_buckets=512 > /dev/null;
/usr/sbin/sysctl -w net.inet.ip.fw.dyn_ack_lifetime=300 > /dev/null;
/usr/sbin/sysctl -w net.inet.ip.fw.dyn_syn_lifetime=20 > /dev/null;
/usr/sbin/sysctl -w net.inet.ip.fw.dyn_fin_lifetime=5 > /dev/null;
/usr/sbin/sysctl -w net.inet.ip.fw.dyn_rst_lifetime=5> /dev/null;
/usr/sbin/sysctl -w net.inet.ip.fw.dyn_short_lifetime=10 > /dev/null;

########
# Flush
########

# Purge existing rules, this blanks any existing rules
${IPFW} flush;

########
# Localhost Settings
########

# User verify reverse path to stop spoofed packets
${IPFW} add deny log ip from any to any not verrevpath in;

# Allow everything on the localhost (127.0.0.1)
# This way the machine can connect to itself via the localhost interface

${IPFW} add allow ip from me to me;

# Now check for spoofing attacks via localhost and source routed
# deny and log
${IPFW} add deny log ip from 127.0.0.0/8 to any in;
${IPFW} add deny log ip from any to 127.0.0.0/8 in;
${IPFW} add deny log ip from any to any ipoptions ssrr,lsrr in;

# Allow multicasts that are local
${IPFW} add allow ip from ${TrustedHosts} to 224.0.0.0/3 in;

# Deny tcp packets sent to multicast
# (that makes some sense as multicasts are UDP)
${IPFW} add deny log tcp from any to 224.0.0.0/3 in;

# Deny multicasts in
# For most users this is fine, but it will disable some media software
# and some CIFS server functions
#${IPFW} add deny log ip from 224.0.0.0/3 to any in;

# This one blocks scanning for port 0 to see if machine is there
${IPFW} add deny tcp from any to any 0 in;

########
# Minimal Requirements
########

# Non-stateful, can’t get stateful working under tiger
# Also set the rule number here high, that way timelox generated
# firewall rules have room (by default, TheHand puts them in
# starting at 500)
${IPFW} add 25000 allow tcp from any to any established;

# Allow all outbound
${IPFW} add allow ip from any to any out ;

# Trusted Hosts
${IPFW} add allow ip from ${TrustedHosts} to any in;

########
# ICMP
########

# Allow outbound icmp
${IPFW} add allow icmp from any to any out;

# If you want to allow anyone to ping you, or run a tracroute to you
#${IPFW} add allow icmp from any to any in;

# This lets this machine receive ping replies and
# the icmp errors that traceroute depends upon
${IPFW} add allow icmp from any to me icmptypes 0,3,11 in

# ICMP settings, this rules allow ICMP from any of the main unc network ranges.
# Allow ICMP (ping and traceroute) from main unc hosts
# For unc folks this is a good way to limit it.
${IPFW} add allow icmp from ${NotSoTrustedHosts} to any in;

########
# Core Services
########

# This section holds rules that govern services your machine must have
# working to use the internet.

# DHCP Settings
# Shouldn’t be needed since the servers should be part of your TrustedHosts,
# but I left these in the file in
# case anyone has problems. If you boot, and can’t get an IP number, or can’t
# resolve IP names to numbers, or sync clocks
# try uncommenting the rules in this sections.
#
# Allow DHCP from any server
#${IPFW} add allow udp from any 67 to any 68 in
# If you know what server you use for DHCP, you can refine this a bit,
# which reduces the chance of getting the wrong number. It also reduces
# the chance of getting any number, especially if you are mobile.
# 1021 and 1022 are set up for computer science affiliates registered with our
# DHCP server.
#${IPFW} add allow udp from 152.2.131.228 67 to any 68 in;
#${IPFW} add allow udp from 152.2.131.227 67 to any 68 in;
# If the above doesn’t work, you might need to uncomment these
#${IPFW} add allow udp from any 68 to 255.255.255.255 67 out
#${IPFW} add allow udp from any 67 to 255.255.255.255 68 in

# DNS Settings
# Shouldn’t be needed since we’re checking state, but left in the file in;
# case anyone has problems. If you boot, and can’t get host or nslookup to
# resolve names, try uncommenting this.
# This rule opens the firewall to any DNS server, so if you have a laptop that
# moves from network to network, this may be the best rule to use.
#${IPFW} add allow udp from any 53 to any in;
# These rules allow DNS only from known servers. The first two lines are the dns servers for CS.
# Users outside of CS should use the main unc servers, 152.2.21.1 and 152.2.253.100
#${IPFW} add allow udp from 152.2.131.228 53 to any in;
#${IPFW} add allow udp from 152.2.131.227 53 to any in;
#${IPFW} add allow udp from 152.2.21.1 53 to any in;
#${IPFW} add allow udp from 152.2.253.100 53 to any in;

# NTP (Network Time)
# Again, this shouldn’t be needed since we’re tracking state, but
# if you can’t get a time server to work, uncomment this.
# This rule allows this machine to use any NTP server
# ${IPFW} add allow udp from any to any 123 in;
# Or if you what the time server is, you can restrict it.
#${IPFW} add allow udp from 152.2.21.1 to any 53 in;

########
# Standard Services
########

# Don’t open these unless you want to run the service.
# Also consider who would need access, for example, it’s very unlikely
# you’ll need to allow ssh from the entire internet. But most
# folks want the web server wide open
#
# Most of these are set up such that it’s the ${NotSoTrustedHosts} range
# to which a service is open. Remember, ${TrustedHosts} are allow to connect
# to all ports

# Allow web service from anywhere
#${IPFW} add allow tcp from any to any 80 setup;
#${IPFW} add allow tcp from any to any 443 setup;

# SSH
#${IPFW} add allow tcp from ${NotSoTrustedHosts} to any 22 in setup;
#${IPFW} add allow tcp from any to any 22 in setup;

# AppleShare File Sharing
#${IPFW} add allow tcp from ${NotSoTrustedHosts} to any 548 in setup;
#${IPFW} add allow tcp from ${NotSoTrustedHosts} to any 427 in setup;

# SMB/CIFS (windows networking)
#${IPFW} add allow ip from ${NotSoTrustedHosts} to any 137-139 in setup;

# LDAP (in case you run an ldap server)
#${IPFW} add allow tcp from ${NotSoTrustedHosts} to any 389 setup
#${IPFW} add allow udp from ${NotSoTrustedHosts} to any 389

# Quicktime Streaming Service
# Allow QTSS from anywhere
#${IPFW} add allow tcp from any to any 545 in setup;
# Allow RTSP from anywhere (part of QTSS)
#${IPFW} add allow tcp from any to any 554 setup;
# Allow UDP RTSP data from any where
#${IPFW} add allow udp from any to any 6970-6999 in ;

# iTunes
# Allow iTunes sharing
${IPFW} add allow ip from any to any 3689 in setup;

# Allow Rendevous
${IPFW} add allow ip from any to any 5353 in setup;

#######
# Closing up
#######

# Block and log all ip packets not matched by a prior rule
# so basically we’re defaulting to deny rather than accept
# In terms of udp reject is stealthier
# since the way you scan for UDP ports is to look for ports that
# don’t send you an error on connect
${IPFW} add 65530 reject udp from any to any in;
${IPFW} add 65531 deny tcp from any to any in;
${IPFW} add 65532 deny ip from any to any in;

} # end of StartService

StopService ()
{
${IPFW} flush;
ERROR_NUMBER=${?};
if [[ ${ERROR_NUMBER} == "0" ]]
then
ConsoleMessage “Firewall has been stopped”;
else
ConsoleMessage “There was a problem stopping the Firewall”;
exit 1;
fi
}

RestartService ()
{
StopService
StartService
}

RunService “${1:-start}”;

Agora devemos habilitar o script acima para execução, para isso entraremos com o seguinte comando:

chmod +x /Library/StartupItems/Firewall/Firewall

Tente executar o script rodando o comando abaixo

sudo /Library/StartupItems/Firewall/Firewall

Nas próximas semanas estarei aprimorando mais este tutorial de IPFW no Mac OSX, até breve.

Referências:
Mac DevCenter O’Reilly
Apple

76 Comments so far

  1. Trorneimmorge on March 9th, 2009

    cooooolest domain name)))
    ————————
    internet signature: http://pedeno.ru/

  2. Lemelafejef on March 10th, 2009

    great domain name for blog like this)))
    ————————
    ads: http://werato.ru/

  3. trierSminGnat on March 10th, 2009

    yo, great name for site)))
    ————————
    sponsor: http://car-auto-loan.xetisa.ru/

  4. mwcyj rpbkxgh on March 23rd, 2009

    mdshyciof ezrlkcdj iwmde dknar lzdqawhuy qgnz oibe

  5. wabfrertitawn on March 24th, 2009

    ynrt +1 odaback.1d cialis cialis rn241

  6. calton,hirschi on March 31st, 2009

    Хай,хозяин сайта!!!
    У вас на странице буквы как квадратики- исправьте, ато хочется прочитать

  7. calorio(hiroshi on April 1st, 2009

    Добрый день,аффтар!!!
    У вас на сайте символы как квадратики- решите проблему, ато хочется почитать

  8. calogero>hochmayer on April 2nd, 2009

    Хело,аффтар!!!
    У вас на блоге текст как абракадабр- отремонтируйте, ато хочется узнать инфу

  9. calliari/homayoun on April 15th, 2009

    Драсте,блогер!!!
    Очень понравилась пост. полистал статьи, то скажу, что пишете очень познавательно и выбираете актуальные рубрики информации. Большое Спасибо!!!

  10. pavla on April 27th, 2009

    Making Waves

  11. marimyanka on April 29th, 2009

    Thank you author

  12. pavlusya on April 29th, 2009

    WTF O.o

  13. mayunya on April 30th, 2009

    Hokay hokay hokay.

  14. enyusha on April 30th, 2009

    World cannot afford to ignore climate change

  15. tyusha on May 1st, 2009

    Links

  16. milasha on May 2nd, 2009

    PES2008 Anti-Aliasing solution

  17. AkBilly on May 4th, 2009

    Хм,согласен с предыдущими вы ораторами

  18. yeomanry on May 5th, 2009

    Ку,блогер!!!
    Сильно понравилась пост. полистал новости, то скажу, что печатаете очень интелектуально и выбираете интересные топики информации. Большое Спасибо!!!

  19. venediktych on May 7th, 2009

    Thank you author

  20. sampson on May 20th, 2009

    Зачёт
    Очень понравилась ваша заметка! Так держать! Блог в закладки и в ридер!

  21. Easeglels on May 25th, 2009

    Огромное вам человеческое спасибо, очень актуальная заметка. ! )

  22. Beenteeding on May 25th, 2009

    Hiya all of youz!..
    How are yaz doing?

  23. Отличный пост. Хочу тоже поделиться прикольной ссылкой - скачать NFS Undercover

  24. форум фанов on May 27th, 2009

    Форум известных людей к вашим услугам.

  25. buy viagra online on May 27th, 2009

    If you need you can buy viagra today!!! Enjoy…

  26. автовыкуп on May 29th, 2009

    Есть ненужное авто? Мы проводим выкуп отечественных автомобилей

  27. zithromax purchase on May 29th, 2009
  28. Совесть? Свят, свят, нечистая! продам диплом аттестат

  29. zithromax pills on June 1st, 2009
  30. ricardos on June 1st, 2009

    Не отметай опыт, - дворником станешь! купить диплом вуза

  31. rodrigos on June 1st, 2009

    Для иного фига - самый широкий жест. диплом специалиста

  32. Давольно познавательно. Хочу тоже поделиться суперской ссылкой - фильмы онлайн бесплатно

  33. Все ещё ищите где можно продать? Тогда специально для вас наше предложение - интернет аукцион мобильных телефонов

  34. букет on June 2nd, 2009

    А не думали сделать блог про интерьер? Мне кажется у вас отлично получится

  35. медицина on June 2nd, 2009

    Пришло лето. Все раздеваются - гормоны бъют в голову

  36. культура секса on June 2nd, 2009

    Ну что опять про любовь? Вам ещё не надоело?

  37. похудание on June 2nd, 2009

    Да уж, нынче наша медицина оставляет желать лучшего

  38. строительство on June 2nd, 2009

    А что это за странные постройки на фото?

  39. ролики on June 3rd, 2009

    Особенно невыносимы идиоты, которые смотрят на тебя как на равного.

  40. видео смс on June 5th, 2009

    А удовольствия должны быть дорогими….

  41. oricluber on June 6th, 2009

    oriclub

  42. Отличный пост. Дамаю для ваших подписчиков была бы еще полезна статья на тему “предоставляем данные номинального директора

  43. Wheemnecy on June 7th, 2009

    Хм,несогласен с предыдущими высказываниями
    Споки Bye

  44. nida on June 11th, 2009

    Шествие НБП «Антикапитализм-120»

  45. бизнес мен on June 11th, 2009

    Размер не важен, важен рост, иначе это просто хвост..

  46. white lable affiliate program on June 11th, 2009

    Interesting topic. That what you think about 2 tier affiliate program.

  47. шуба on June 12th, 2009

    Автору респект - интресный пост. Давно читаю ваш ресурс и давно хочу спросить что вы думаете насчет таких вещей к примеру как шуба из норки?

  48. семейный бюджет  on June 12th, 2009

    Хотелось бы внести и свой вклад в развитие вашего блога и поделиться интересной ссылкой с посетителями. доллар прогноз - вот собственно и ссылка…

  49. новости on June 13th, 2009

    Если все думают, что цены поднимутся, цены поднимутся. (”Первый инфляционный закон”) :)

  50. poker casino on June 13th, 2009
  51. Отличный пост. Узнал для себя прилично нового и интересного. Кстати, вот тоже хочу поделиться интересной ссылочкой - объявления калуга. Пусть это будет мой вклад в развитие вашего блога; )

  52. Abira on June 19th, 2009

    Sorry. The male is a domestic animal which, if treated with firmness, can be trained to do most things.
    I am from Seychelles and now teach English, please tell me right I wrote the following sentence: “Buy imitrex canada drugs the canadian pharmacy of choice for purchasing your discount prescription drugs and medication.”

    Thank :-) Abira.

  53. новости шансона on June 21st, 2009

    Пятачок для Винни-Пуха был разменной монетой.

  54. Kessoceavoina on June 22nd, 2009

    Hi,
    I have added you to the SPOG mailing list.
    Please check your mailbox.

  55. Bainconsona on June 23rd, 2009

    I follow your posts for a long time and should tell that your articles always prove to be of a high value and quality

    for readers.

  56. для windows on June 24th, 2009

    Отличная новость. Я вот тоже решил поделиться полезной ссылкой. Здесь можно русские программы компьютера. Так что заходите - не пожалеете.

  57. finasteride propecia on June 24th, 2009

    Only today buy propecia online pharmacy on our site.

  58. voffadock on June 24th, 2009

    Do add more stuff to this Blog man!

  59. free spades download on June 24th, 2009

    Interesting information. If you have free time, pleas came to my blog. Thith is it - internet spades.

  60. Складно пишете. Но не пойму почему ваш пост вызвала воспоминания о детстве, и не отходя от темы - Купить детские игрушки. И не забрасывайте блог; )

  61. ingeglinoft on June 25th, 2009

    I’m new to the site and just purchased lots of items last night, and still have not received an email with the items. How long does it normally take to get the items? I understood that as soon as I paid everything would be emailed to me. Just wondering……
    Thanks

  62. Вот тоже решил поделиться полезной ссылкой - экономика скачать бесплатно
    Буду рад услышать ваше мнение.

  63. …задета не только КОРА головного мозга, но и так сказать сама его ДРЕВЕСИНА...

  64. Прно бесплатно on June 27th, 2009

    Все мы за чертой бедности, но с разных её сторон.

  65. музыка on June 29th, 2009

    Алкоголь - это анестезия, позволяющая перенести операцию под названием жизнь.

  66. доска бесплатных объявлений on June 29th, 2009

    Отличный пост. А вы пробывали разместить объявление о своем сайте?

  67. Меня вдохновил ваш пост. А вы не думали над тем чтобы разместить объявление о своем ресурсе?

  68. see request variables on July 1st, 2009

    Do you want know your dns records tools?

  69. Domains lookup tools on July 1st, 2009
  70. your IP on July 1st, 2009

    It’s interesting - find my ip address

  71. my IP lookup on July 1st, 2009

    You still there? Follow link and see - my IP geo info

  72. Заставляет задуматься. Как у со стажем блогера хотел бы узнать вашего мнения по поводу - негабарит

  73. Заходите и вы к нам в блог - скачать тибериум варс. Будем рады вас у нас видеть!

  74. domain nslookup tool on July 3rd, 2009

    online nslookup tools - it’s free for you

  75. whats my user agent on July 3rd, 2009

    It will be interesting to you http user agent info

  76. view email's mx record on July 3rd, 2009

    New service for webmasters - mx record lookup

Leave a Reply

« Back to text comment