Mac os firewall terminal

Mac os firewall terminal

In an effort to automate the addition of a firewall exception for the latest version of Apple Remote Desktop, I found a way to use the defaults write command in the Terminal to create the rule without using the System Preferences panel. Below is an example of the command I used; in this case to add the ARD exceptions. The only problem I encountered with this method is that the defaults command tends to change the ownership of the com.apple.sharing.firewall file from -rw-r--r-- root admin, which also disables the firewall. Changing the permissions back and rebooting will reactivate the built-in firewall.

[robg adds: To make the above command presentable, I broke it onto multiple rows. There’s a space at the end of the first row, then all the remaining rows should be joined into one with no additional spaces.]

  • Currently 2.33 / 5

You rated: 5 / 5 (6 votes cast)

Hint Options

Of course, the other way to do this is to learn how to use the BSD derived ipfw tool directly, and dispense with managing the firewall in the GUI. To learn about this approach, read the manpage for ipfw, or do a Google search for it; to see your current settings, just do a `ipfw list`.

The nice thing about the manual ipfw approach is that you get a lot more control over how the firewall is configured (for example, separate management of TCP and UDP traffic, and of incoming and outgoing traffic);the downside to this approach is that the GUI settings no longer work, so it’s all or nothing this way.

The nice thing about this hint is that it’s a compromise. You can do coarse-grained command line firewall management on the command line — which is great for managing basic setup of remote computers (e.g. with ARD or ssh) — but you don’t break the ability to control the firewall under Sharing preferences. Very useful — thanks for the idea!


DO NOT LEAVE IT IS NOT REAL

Or you could use a GUI that actually encompasses all of the power of the ipfw ruleset (clunky as ipfw and its syntax are, they are very powerful).

That’s why I’m building such an app. I don’t use the Apple firewall tool and the other GUI tools just don’t cut it. I’ve got most of the rule features covered, but not the checkstate and a number of the other advanced options. And yes, it can read the existing rules (and export the whole thing as something that can be fed to ipfw).

My goal is to get all the options in and make the GUI comfortable to use (it’s already more convenient to me than the command line).

Or you could use a GUI that actually encompasses all of the power of the ipfw ruleset (clunky as ipfw and its syntax are, they are very powerful).

Ah, yes, good point. In that case, you’ll want to take a look at BrickHouse. It may be a bit outdated at this point — the last update seems to have been in October 2001, when it was rebuild for OSX 10.1 — but the fundamentals really haven’t changed since then and as far as I can tell it should still work just fine.


DO NOT LEAVE IT IS NOT REAL

Brickhouse was one of my reasons for building my own. It has some good features, but it has some glaring omissions.

You can’t build divert, tee or forward rules or «import» the existing ipfw rules to be edited via it’s UI. It does provide an Expert mode, but that’s just editing a text file — why use Brickhouse if you have to use it’s Expert mode?

It also feels clunky to me; the viewing area for the rules is too small and it takes a sheet and another window to get to some additional ipfw features.

Don’t get me wrong, I think Brickhouse is a good tool, but I think Brickhouse is aimed at a different audience than mine. I imagine, in the end, my software will feel more comfortable to users who don’t want to use the CLI or edit text files, but want the features of a GUI also powerful rule editing.

sunShield, mentioned in another comment (and one I’d never heard of before), is more my «competition» than Brickhouse.

I use sunshield Preference Pane. It shows the current ipfw stuff and allows you to add lines sort of GUI.

That seems to work pretty well and look pretty good.

Guess I know where the competition is, heh 😉

Actually, I haven’t been able to find ipfw.conf in OS X client, although I’ve been using it in Server. I presume it’s there somewhere, but it must be cloaked.

Which file do you use to manually add firewall rules, if not ipfw.conf? Or, if you have it, why don’t I? I do have a functioning firewall.

Читайте также:  Elementary linux системные требования

to add firewall rules via the terminal i use this command:
add 0 deny udp from any to any 5900 or
add 0 allow tcp from any to any 5900

the problem with this is that you get a bad message that other firewall software is running already when opening the system preferences. you can get around this by just placing all your rules in above syntax into the /etc/ipfw.conf file. if it doesnt exists, create it, and all your rules from there as well as from the control panel will be honored.

to add a rule via cli the exact command is
sudo ipfw add 0 deny udp from any to any 5900

to add a rule into /etc/ipfw.conf the syntax is
add 0 deny udp from any to any 5900

ipfw is located in /sbin. If you want to configure ipfw using the terminal, you can do the following:

— stop the built-in firewall in system prefs. if you have it running.
— create the folder /Library/StartupItems/ipfw
— copy ipfw into that folder using this command in the terminal:
— using the terminal, we’ll create «StartupParameters.plist» in the folder /Library/StartupItems/ipfw so type the following:
— now paste in the following:
— save it and exit pico
— from the terminal, you will add your firewall rules to the file /etc/ipfw.conf To open pico in the terminal, and create the ipfw.conf file, type this: — Now add your firewall rules. Here is a very basic example: — when you’re finished adding all your rules, save the file and exit pico.
— if you want firewall logging to be routed into the ipfw.log, you’ll need to edit the /etc/syslog.conf, because by default, ipfw logging will show up in the system.log
— to enable logging to the ipfw.log, type this in the terminal:
— then add this to replace the existing ipfw.log info:
— since ipfw is already running you’ll need to stop it, and start it again to activate your rules.
— to disable, and then enable ipfw, type this in the terminal:
— to verify your current firewall rules, type this from terminal:
— this should show the rules that you just entered into /etc/ipfw.conf
— to see the parameters that apply to ipfw, type this in terminal:
— it should show enable=1, and if you want verbose logging (if it doesn’t show verbose=1) type this in terminal:
— you can also set a limit on the number of log entries (provided that you added «log» to any of your ipfw rules) by setting verbose_limit to the maximum number of log entries that you choose, for example:
— this is good if you know that you’re going to have people pounding on your firewall, so you don’t have a ton of log entries, otherwise you don’t really need to set it.

And that’s basically all there is to it. Users who are new to the terminal, or who aren’t familiar with firewall rules, and what they do, should read up on it, or ask someone for help. The man page for ipfw is a place to start. If you’re sharing things from your machine, you’ll want to create rules to allow these functions. If you find that something doesn’t work anymore after enabling ipfw, that’s the first place you should start looking.

I thought that the purpose of the «0» was to make the rule being added the top rule, however all the rules I try to add with the 0 are tacked onto the END of my ruleset whether I use the 0 or not. What the heck? Am I missing something? I’m running 10.3.9.

>sudo ipfw 0 add deny ip from 1.1.1.1 to any
12290 deny ip from 1.1.1.1 to any

Why does it get stuck as rule 12290 (the last rule barring 65535)?

SunShield Preference Pane 2.0.3.1 crashing every time when I try to open it
here is pop-up which I getting: System Preferences quit unexpectedly while using the sunShield plug-in.
this system dump:
Process: System Preferences [2833]
Path: /Applications/System Preferences.app/Contents/MacOS/System Preferences
Identifier: com.apple.systempreferences
Version: 7.0 (7.0)
Build Info: SystemPrefsApp-1750100

19
Code Type: X86 (Native)
Parent Process: . [1]

PlugIn Path: /Library/PreferencePanes/sunShield.prefPane/Contents/MacOS/sunShield
PlugIn Identifier: org.spf.sunShield
PlugIn Version: 2.0.3 (2.0.3)
.

If you need entire dump drop me a PM and I will send it to you.

any suggestions?
Do you planing to release version for 10.7 or 10.6 with 64-bit support

Источник

About the application firewall

OS X includes an application firewall you can use to control connections made to your computer from other computers on your network.

OS X v10.5.1 and later include an application firewall you can use to control connections on a per-application basis (rather than a per-port basis). This makes it easier to gain the benefits of firewall protection, and helps prevent undesirable apps from taking control of network ports open for legitimate apps.

Configuring the application firewall in OS X v10.6 and later

Use these steps to enable the application firewall:

  1. Choose System Preferences from the Apple menu.
  2. Click Security or Security & Privacy.
  3. Click the Firewall tab.
  4. Unlock the pane by clicking the lock in the lower-left corner and enter the administrator username and password.
  5. Click «Turn On Firewall» or «Start» to enable the firewall.
  6. Click Advanced to customize the firewall configuration.
Читайте также:  Редактор реестра windows 10 что можно удалить

Configuring the Application Firewall in Mac OS X v10.5

Make sure you have updated to Mac OS X v10.5.1 or later. Then, use these steps to enable the application firewall:

  1. Choose System Preferences from the Apple menu.
  2. Click Security.
  3. Click the Firewall tab.
  4. Choose what mode you would like the firewall to use.

Advanced settings

Block all incoming connections

Selecting the option to «Block all incoming connections» prevents all sharing services, such as File Sharing and Screen Sharing from receiving incoming connections. The system services that are still allowed to receive incoming connections are:

  • configd, which implements DHCP and other network configuration services
  • mDNSResponder, which implements Bonjour
  • racoon, which implements IPSec

To use sharing services, make sure «Block all incoming connections» is deselected.

Allowing specific applications

To allow a specific app to receive incoming connections, add it using Firewall Options:

  1. Open System Preferences.
  2. Click the Security or Security & Privacy icon.
  3. Select the Firewall tab.
  4. Click the lock icon in the preference pane, then enter an administrator name and password.
  5. Click the Firewall Options button
  6. Click the Add Application (+) button.
  7. Select the app you want to allow incoming connection privileges for.
  8. Click Add.
  9. Click OK.

You can also remove any apps listed here that you no longer want to allow by clicking the Remove App (-) button.

Automatically allow signed software to receive incoming connections

Applications that are signed by a valid certificate authority are automatically added to the list of allowed apps, rather than prompting the user to authorize them. Apps included in OS X are signed by Apple and are allowed to receive incoming connections when this setting is enabled. For example, since iTunes is already signed by Apple, it is automatically allowed to receive incoming connections through the firewall.

If you run an unsigned app that is not listed in the firewall list, a dialog appears with options to Allow or Deny connections for the app. If you choose Allow, OS X signs the application and automatically adds it to the firewall list. If you choose Deny, OS X adds it to the list but denies incoming connections intended for this app.

If you want to deny a digitally signed application, you should first add it to the list and then explicitly deny it.

Some apps check their own integrity when they are opened without using code signing. If the firewall recognizes such an app it doesn’t sign it. Instead, it the «Allow or Deny» dialog appears every time the app is opened. This can be avoided by upgrading to a version of the app that is signed by its developer.

Enable stealth mode

Enabling stealth mode prevents the computer from responding to probing requests. The computer still answers incoming requests for authorized apps. Unexpected requests, such as ICMP (ping) are ignored.

Firewall limitations

The application firewall is designed to work with Internet protocols most commonly used by applications – TCP and UDP. Firewall settings do not affect AppleTalk connections. The firewall may be set to block incoming ICMP «pings» by enabling Stealth Mode in Advanced Settings. Earlier ipfw technology is still accessible from the command line (in Terminal) and the application firewall does not overrule any rules set using ipfw. If ipfw blocks an incoming packet, the application firewall does not process it.

Источник

Настройка брандмауэров в OC Apple macOS 10

Графическая оболочка брандмауэра в операционной системе Apple macOS у любого более или менее подготовленного пользователя вызывает вопросы из-за отсутствия возможности тонкой настройки собственных правил. Она как «рубильник», имеющий лишь два пограничных состояния «ВКЛ» и «ВЫКЛ». О том, что с этим делать и как настроить собственные правила, например, открывающие тот или иной порт в macOS, мы и поговорим в данной заметке.

Под капотом графической оболочки этого упрощённого брандмауэра в ОС Apple macOS скрывается демон socketfilterfw, известный также как «Application Firewall» или «Socket Firewall».

Помимо socketfilterfw в ОС есть ещё один, более мощный и функциональный, брандмауэр, скрытый от глаз обычного пользователя — Packet Filter (PF), который пришёл ещё в OS X Lion (10.7) из OpenBSD.

Как в macOS включать pf автоматически во время загрузки ОС?

После внедрения System Integrity Protection (SIP) в OS X El Capitan (10.11) важные для системы каталоги и файлы пользователю доступны только в режиме чтения, поэтому файл демона /System/Library/LaunchDaemons/com.apple.pfctl.plist отредактировать без отключения SIP возможным не представляется. Однако, отключать защиту целостности системы для модифицирования системных файлов затея, сама по себе, не очень правильная. Поэтому мы не будем рассматривать такой метод.

Мне известно два способа заставить pf загружаться по умолчанию при старте системы – запускать pf скриптом из собственного домена или запускать в режиме обработки rc.server

Запуск pf в качестве демона

Суть этого способа заключается в том, чтобы создать собственного демона, который будет запускать pf напрямую, либо через скрипт:

В примере будем использовать скрипт, который будет включать pf и загружать кастомную конфигурацию:

Разрешим выполнение скрипта:

Дополнительная конфигурация /etc/pf.custom.conf необходима из-за того, что файл /etc/pf.conf каждый раз при обновлении macOS переписывается на дефолтный, так же как и подключаемые в нём правила /etc/pf.anchors/com.apple , поэтому и редактировать их напрямую не имеет смысла. Скорее всего, подобное поведение связано с параметрами «Блокировать все входящие подключения» и «включить режим невидимости» в графическом брандмауэре. Включение этих параметров включает pf и добавляет правила в » com.apple/250.ApplicationFirewall «.

Читайте также:  Windows 10 службы список лучших

Создадим файл кастомной конфигурации pf:

Настроим правила файрвола под свои нужды:

Обратите внимание на то, что в нашем примере таблица «Temp» пустая. Она необходима для динамического управления правилами, без перезапуска PF.

По умолчанию pf работает с /etc/services , поэтому для открытия ssh не обязательно указывать порт 22, можно указать имя сервиса.

Проверим конфигурацию на наличие ошибок:

Если ошибок нет, загрузим службу в систему:

Проверим состояние pf:

Если по какой-то причине нет желания связываться с запуском скрипта из демона и хочется запускать PF напрямую, например, без правил Apple, то можно изменить контент XML таким образом, чтобы запускался не скрипт, а pfctl с указанным конфигом.

В этом случае какие-либо параметры из /etc/pf.conf загружены не будут.

Запуск pf в режиме обработки rc.server

Суть второго способа запуска pf сводится к созданию файла /etc/rc.server , который обрабатывается системой в процессе каждой загрузки.

Ситуация в этом случае аналогичная, после запуска macOS выполняется скрипт, который запускает pfctl с указанной конфигурацией.

Скрипт можно запустить вручную командой вида:

Таким образом каждый раз при загрузке macOS файрвол pf будет загружаться в систему с настроенными правилами автоматически.

Базовые примеры работы с pfctl

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

Перезапуск pf с указанной конфигурацией:

Просмотр всех подключенных правил:

Просмотр системных подключенных правил для работы Bonjour:

Добавить 10.185.62.15 в таблицу Temp:

Просмотреть адреса в таблице Temp:

Удалить 10.175.62.15 из таблицы Temp:

Удалить все записи в таблице Temp:

Просмотр статистики по всем таблицам:

Просмотр активных соединений:

Для тех, кто не хочет использовать окно терминала, но хочет испробовать pf, можно взять на вооружение приложение Murus. Murus Lite бесплатен для некоммерческого использования.

Демон адаптивного брандмауэра

Если Вы устанавливаете Server.app из AppStore, то pf будет включаться автоматически, как уже было сказано выше. Так же появится несколько дополнительных подключаемых конфигураций с правилами и демон адаптивного файрвола /Applications/Server.app/Contents/ServerRoot/usr/libexec/afctl . Для переопределения параметров запуска pf используется конфиг /Library/Server/Firewall/Anchors/combined_anchor.txt .

Настраивать pf или подключать свои правила нужно именно через конфиг /Library/Server/Firewall/Anchors/combined_anchor.txt .

В /etc/pf.anchors/com.apple подключится адаптивный файрвол

Так же добавится конфигурация правил /etc/pf.anchors/com.apple.server-firewall , которая подключает пустые дочерние конфиги правил, которые так же можно использовать:

Демон адаптивного файрвола afctl необходим для автоматических блокировок хостов с подозрительной активностью: неправильные запросы, большое число неудачных попыток входа и тому подобное. Блокировки по умолчанию на 15 минут. Полезно использовать при публикации macOS напрямую в интернет. В локальной сети в нём нет особого смысла, только если для экспериментов.

Так как демон afctl располагается в нестандартном месте, добавим его путь для быстрого вызова в профиль

/.zprofile текущего пользователя или глобально для всех пользователей в /etc/zprofile .

Посмотреть временный чёрный список можно двумя способами:

Через afctl, получим просто список

Или прочитать файл /var/db/af/blacklist

В файле дополнительно содержится информация о времени удаления из чёрного списка в формате Unix timestamp — количество секунд от 01.01.1970 00:00 UTC. Для преобразования Unix timestamp в понятный для человека формат:

При необходимости, хосты можно блокировать вручную и на больший срок, например, на 90 минут:

Командное управление socketfilterfw

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

/.zprofile или /etc/zprofile

Рассмотрим доступные ключи.

  • Firewall is disabled. (State = 0) — Файрвол выключен
  • Firewall is enabled. (State = 1) — Файрвол включен
  • Firewall is enabled. (State = 2) — Файрвол выключен, запрещены все входящие соединения.

Включить или выключить:

Запретить или запретить все входящие соединения:

Разрешить или запретить встроенным приложениям взаимодействовать с сетью:

Разрешить или запретить подписанным приложениям взаимодействовать с сетью:

Разрешить или запретить ICMP:

Включить или отключить логирование:

Уровень детализации лога:

Добавить приложение в фаервол, по умолчанию трафик разрешается:

Заблокировать входящий трафик приложения:

Разрешить входящий трафик приложения:

Удалить приложение из фаервола:

Сосуществование socketfilterfw и pf

Разумеется, лучшей практикой является комбинирование двух решений: Packet Filter и socketfilterfw.

Все входящие соединения сперва обрабатываются pf, затем socketfilterfw.

Если требуется создать правило для организации NFS сервера, добавим правило в socketfilterfw:

Затем добавим в правило в pf и перезапустим его:

Таким образом мы не просто откроем TCP и UDP порты в системе, но и ограничим приложения, которые могут принимать соединения.

Диагностика и отладка

В решении проблем, которые могут возникнуть при работе с брандмауэрами, можно воспользоваться их логированием.

Для настройки логирования pf в файле правил /etc/pf.anchors/FilterRules добавим правила логирования, которые должны находится над разрешающими правилами.

Читаем интерфейс с помощью tcpdump:

Лог с интерфейса можно просматривать и другими средствами, например wireshark.

После завершения диагностики, можно удалить интерфейс (либо он будет удалён при последующей перезагрузке ОС):

Если необходимо, чтобы интерфейс pflog0 автоматически создавался при старте системы, необходимо добавить «ifconfig pflog0 create» в /etc/pf.start.sh или в /etc/rc.server , в зависимости от того, что используется.

Если с логированием PF всё более или менее ясно, то с логированием socketfilterfw всё несколько иначе, и, я бы даже сказал, странно. При включении лога файл создаётся /var/log/appfirewall.log , но он всегда пустой. В форумах обсуждают проблему уже достаточно давно (apple, macrumors, stackexchange), но решения нет. Если кто-то знает, как заставить socketfilterfw писать лог, прошу поделится этим тайным знанием

Источник

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