Iptables для mac os

iptables эквивалент для Mac OS X

Я хочу пересылать запросы от 192.168.99.100:80 к 127.0.0.1:8000 . Вот как я бы сделал это в Linux, используя iptables :

Как мне сделать то же самое в MacOS X? Я попробовал комбинацию ipfw команд без особого успеха:

(Для меня успех — указать браузер http://192.168.99.100 и получить ответ от сервера разработки, на котором я работаю localhost:8000 )

Так я узнал , что есть способ сделать это. Я не уверен, что это предпочтительный способ, но он работает! На вашей любимой оболочке:

(Псевдоним, lo0 кажется, недостающая часть)

Если вы хотите, чтобы (поддельный) домен указывал на этот новый псевдоним, убедитесь, что в / etc / hosts есть строка:

Я был в состоянии получить эту работу , используя ifconfig и pfctl команды на Mac 10.10.2. При следующем подходе я успешно картографирование 127.0.0.1:3000 к mydomain.com локально на моей машине.

В командной строке введите следующие две команды для переадресации соединений 127.0.0.1:3000 на 10.0.0.1 :

Затем отредактируйте файл /etc/hosts или /private/etc/hosts файл и добавьте следующую строку, чтобы сопоставить свой домен 10.0.0.1 .

После сохранения файла hosts очистите локальный DNS:

Теперь откройте mydomain.com в браузере, и вы увидите сервер, расположенный на вашем локальном порту (то есть 127.0.0.1:3000 ). По сути, этот процесс сопоставляет :

новое с тем, чтобы вы могли затем сопоставить хост с этим IP.

Недавно мне тоже пришлось сделать нечто подобное, и при поиске натолкнулся на этот ответ. К сожалению, ответ Nafe использует, ipfw который в настоящее время устарел и недоступен в OSX; и ответ Кевина Лири действительно немного хакерский. Поэтому я должен был сделать что-то лучше (чище) и решил поделиться этим здесь для потомков. Этот ответ в значительной степени основан на подходе, упомянутом в этой сущности .

Как упоминается в OP, указание браузера на 192.168.99.100 должно получить ответ от сервера по адресу localhost: 8000. Добавление псевдонима в ifconfig действительности не является необходимым, pfctl одного достаточно: для достижения этого необходимо изменить pf.conf файл /etc/pf.conf .

Сначала мы создаем (с Судо) новый файл якорный (назовем его redirection ) по адресу: /etc/pf.anchors/redirection . В основном это обычный текстовый файл и содержит следующую строку (так же , как в ответ Кевин Лири): rdr pass on lo0 inet proto tcp from any to 192.168.99.100 port = 80 -> 127.0.0.1 port 8000 . Как только новый файл привязки был создан, на него нужно ссылаться в pf.conf файле. Откройте pf.conf файл с помощью sudo и добавьте rdr-anchor «redirection» после последней строки rdr-anchor (которая есть rdr-anchor «com.apple/*» ) и добавьте load anchor «redirection» from «/etc/pf.anchors/redirection» в конце.

В конечном итоге, так должен выглядеть файл pf.conf:

И это почти все. Просто перезапустите pfctl , sudo pfctl -d выполнив сначала команду, чтобы отключить ее, а затем sudo pfctl -fe /etc/pf.conf снова запустить.

Теперь, если вам нужно, чтобы это происходило автоматически после каждого перезапуска, нужно выполнить еще одну крошечную часть работы: pfctl необходимо обновить демон запуска для (ссылка на gist указывает на то, что pf включается автоматически при загрузке, однако это не похоже на случай с просмотром кода). Откройте (с помощью sudo) System/Library/LaunchDaemons/com.apple.pfctl.plist и посмотрите на это:

и добавьте строку, -e чтобы в конечном итоге сделать это так:

Это должно сделать это.

Предостережение : Apple больше не позволяет изменять файлы запуска демона просто так (не с помощью sudo, ни chmod, ни чего-либо еще). Только путь повозиться с системой защиты от целостности настроек: загрузиться в режиме восстановления и запуска терминала. Проверьте состояние SIP с помощью csrutil status , как правило, он должен быть включен. Отключите его csrutil disable и перезагрузите в обычном режиме, а затем внесите изменения в файл plist, как описано выше. После этого вернитесь в режим восстановления и снова включите защиту (она установлена ​​по уважительной причине), выдав команду csrutil enable .

Источник

linux-notes.org

Я уже рассказал о том, как можно себя защитить от различных атак. Иногда, приходиться додумывать различные методы использования защиты, т.к СА (системный администраторы) зачастую закрывают все порты ( не все конечно. Открытые используются для работы). При этом, клиенты хотят использовать сервер из вне ( подключаться к нему и работать). А бывает так, что вообще нужно забанить определенную особь. При статическом IP на стороне клиента, трудно угадать какой ИП разрезать/запрещать — в такой ситуации хорошо подойдет MAC-фильтрацию через IPTables.

Iptables имеет модуль, который обеспечивает MAC-фильтрацию пакетов на определенные порты. Эта статья «Фильтрация MAC используя Iptables в Linux» покажет как можно использовать данный модуль на готовых примерах.

Разрешить полный доступ к конкретной MAC

Ниже команда которая позволит работать со всеми портами для определенного MAC-адреса (например 5D:E5:66:B4:44:3A).

Читайте также:  Unity для linux ubuntu

Разрешить/Запретить SSH доступ к определенным MAC

С IPtables можно разрешать и запрещать подключения к серверу через mac-адрес.

Разрешить SSH доступ к определенным MAC.

Ниже команда разрешит доступ на сервер через SSH (порт 22) с MAC-адресом 5D:E5:66:B4:44:3A.

Запретить SSH доступ к определенным MAC.

Ниже команда запретит доступ на сервер через SSH (порт 22) с MAC-адресом 5D:E5:66:B4:44:3A.

Ограничить SSH для всех, кроме специфического MAC

Ниже команда позволит получить SSH доступ (порт 22) для системы, имеющие физический адрес 5D:E5:66:B4:44:3A.

На этом все, я завершаю свою статью «Фильтрация MAC используя Iptables в Linux».

Источник

MacOS X — iptables?

Where is iptables in MacOS X? I’m running Yosemite 10.10.5 (14F27) and it seems to be missing. If it’s not actually native to OS X, what’s the best way to install it for this operating system? If for some reason it’s just not compatible, please suggest the relevant alternative, instead.

1 Answer 1

There is a thing similar to iptables called pf.

Configuration

The configuration file is located in the /etc/pf.conf

To get started, let’s look at the /etc/pf.conf configuration file that comprises pf:

load anchor «com.apple» from «/etc/pf.anchors/com.apple»

Here, you can see that pf is configured with a number of anchors. An anchor is a collection of rules and tables. Basically, the anchor file being loaded is /etc/pf.anchors/com.apple.

When you make change changes to your pf.conf , you can use this command to check the validness of the config:

When testing, run in verbose mode with:

If you set it up correctly, it should show something like pf enabled

can also add information on the fly. For example, to add a table of 127.0.0.0/24 call localsub: sudo pfctl -t localsub -T add 127.0.0.0/24

Once the configuration is clear, you can run pfctl -q to turn on quiet mode to make things faster.

There is more information in more detail on the reference site.

Источник

Iptables MAC Address Filtering

L AN or wireless access can be filtered by using the MAC addresses of the devices transmitting within your network. A mac address is acronym for media access control address, is a unique address assigned to almost all-networking hardware such as Ethernet cards, routers, mobile phones, wireless cards and so on (see mac address at wikipedia for more information). This quick tutorial explains how to block or deny access using MAC address using iptables – Linux administration tool for IPv4 packet filtering and NAT.

Linux Iptables comes with the MAC module. This module matches packets traveling through the firewall based on their MAC (Ethernet hardware) address. It offers good protection against malicious users who spoof or change their IP address. Remember that mac filtering only makes sense for packets coming from an Ethernet device and entering the following chains:

Examples: Access Restrictions Using MAC Address

Drop all connection coming from mac address 00:0F:EA:91:04:08 (add the following command to your firewall script):

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Allow port 22 from mac address 00:0F:EA:91:04:07:

You can also use the interface name such as eth1:

You can also use FORWARD chain:

You can also use NEW and other supported states as follows so that a known MAC address can be forwarded:

How Do I Skip Certain MAC Address?

Use the following syntax:

The ! symbol means NOT. Your firewall will DROP packets destined to port 22 so long as they do NOT originate from your own computer with the desired MAC address.

Protecting MAC Address Spoofing From a Trusted Systems

Malicious user can spoof their MAC address with a trusted systems. To stop this kind of attacks use VLANS and/or static ARP entries.

See iptables man page for more information:
man 8 iptables

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

hello, how to blok ALL mac address, so i can permit only privileged mac adresses. thanks in advance

You can setup default policy to drop all packets and allow selected incoming packets from MAC based ip filtering.
Set default INPUT to deny all

# Setting default filter policy
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -A INPUT -m mac –mac-source
00:0F:EA:91:04:08 -j ACCEPT

Would this work? As everyone is asking for ACL of MAC addresses.

# Setting default filter policy
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -A INPUT -m mac –mac-source
00:0F:EA:91:04:08 -j ACCEPT
00:0F:EA:91:AA:BB -j ACCEPT
..
..

Does anybody know if this works on Suse 10.0? I need to filter a few MACs.

Is there a way to get the MAC address of an attacker via iptable logging? All of the log levels that I’ve tried give me my server’s MAC address. I’d love to get the MAC of the person I’m blocking so I can block on their MAC in case they try using a proxy.

ex: -A RH-Firewall-1-INPUT -s ATTACKER_IP_HERE -j LOG –log-level 4 –log-prefix “DROP ATTACKER: ”

this results in logs such as…
Mar 21 13:38:41 server_name kernel: DROP ATTACKER: IN=eth0 OUT= MAC=MY_SERVER_MAC_ADDR_HERE SRC=ATTACKER_IP_HERE DST=MY_SERVER_IP LEN=48 TOS=0x00 PREC=0x00 TTL=114 DF PROTO=TCP SPT=39616 DPT=80 WINDOW=65535 RES=0x00 SYN URGP=0

hello i am using iptables

now i need that only those mac id can accept all other droped who can i do this

Hello. I have a problem when i try to log with iptables. iptables v1.3.8: Unknown arg `LOG’
what should i do ?

please i want to ban everyone of using my shell which is port 22 but keep their access on other ports and i owuld like only my PC to log to shell from my MAC address, anyone can help plz.

Allow an ip or network group to conect via SSH
/etc/host.allow

SSHD:192.168.0.4 or something like this 192.168.0.

Deny all conection on SSH
/etc/host.deny

I think it will help you

You are good ones
Caveman

Is there a way to use this in conjunction with the source IP. So that you can enforce a MAC address to only be allowed through if it is using a specific IP address?

Sure, you can use -s IP-address option. Verify source IP 192.168.1.200 along with MAC 00:0F:EA:91:04:08 and if both matched drop it:
iptables -A INPUT -p tcp -s 192.168.1.200 -m mac —mac-source 00:0F:EA:91:04:08 -j DROP

Could someone help.
I have to arm machines whit linux kernel 2.6
I wan’t to make a remote acess but i can’t…
one I have been defined a mac address ifconfig eth0 hw ether 0B:62:9D:6D:1A:34
I made ping suceful but when I try ftp ore telnet it refuse the conection…

I wanna config a router with iptables for my WLAN. my problem, there is a database (mysql) there are all mac adresses, whitch have access…

is there a way to marry iptables with mysql??

I don’t think so.. you need to take help of perl or python and send those IPs using system or exec or “ call to iptables.

Coop>
Here is a script i use to write my iptables.

I also made one for dhcpd so unknown mac’s logging on my wireless will be in a diffrent subnet.

Thanks for sharing perl script.

How do I execute this Perl script?

please help me i have different prb facing i m running LAN network with LInux i m facing the prb of mac spoofing but some of users whom i blocked by my server they user mac address changer different softwares and by this software they detect any Online Active user mac address and just change the IP Address and use internet and when i try to block that mac address by iptables but i cant block that mac address because its mine online active users mac and who users blocked the connection of my LAN they do these things and use mac address changing software and get solid and valid legal mac address by network scanning. …. what i do i m much confused

Sorry to say this but using Mac address filtering to control access to your network is like using a locked screen door to control access to your house. It keeps the generally honest out but doesn’t stop those who’s motives are less than pure. It’s a good general backup to the main security, but it is not a main security measure in and off itself. We use passwords and Mac filtering. Mac Address filtering makes it harder to use a stolen or hacked password.

to Zohaib Hussain
if you have a proxy server then use password authentication
better if you have a managed switch
statically fix the ip address and MAC for every switch port
that way the only way to access the network is to use a certain IP address with the Original MAC address of the NIC while plugged to the correct switch port
and i don’t think that there is any way around this
check also VLAN

is it possible to put the info in a separate file and call it from your main firewall script?
lets say, there is a file called /root/scripts/ip-mac-list
where u have the info written as,
[code] 192.168.0.1 00:13:xx:xx:xx:xx
[/code]

I want to block all MAC address except 1. Any clue.

I do not want to block TCP or UDP Traffic at all.

Can I use this tutorial to create a MAC filter between a wireless network switch and the core? I need access to the network resources so I can’t use a router. What would you suggest?

I wanna block internet some computer PC with mac address which rule can do it

Is it possible to block all MACs except a range? For example, I want to allow all devices from a specific manufacturer such as 11.22.33.00.00.00 through 11.22.33.FF.FF.FF?

Jim, i think no because i haven’t found in man special mac-adress diapason system support (like for IP-adresses)

Hi,
someone knows why that command:

iptables -A INPUT -i eth0 -p tcp –dport 1234 -m mac –mac-source XX:XX:XX:XX:XX -j ACCEPT

works properly in a pc with iptables 1.4.4 and it give me this error:

iptables: No chain/target/match by that name.

on a pc with iptables 1.4.12.1

Can anyone let me know how to block all the mac addresses except two mac addresses in the linux server..

Warning on trying to use –mac-source when on a VM instance: It may not work.

For instance, in Hyper-V , the VM host machine’s IP address for the switch is what will *always* show as the source mac address, rather than the true mac address.

It may also be true for VMware, depending on configuration of the switch on the host.

Thanks for this post. I don’t really see this anywhere else in the IPTables documentation, though I could be missing it.
I wish a –match mac –mac-destination xx:xx:xx:xx:xx:xx had been implemented. It wouldn’t really stop a Man-in-the-Middle (MITM) attack but it would serve as a deterrent.
If one fails (maybe just forgets) to implement a prohibition on source routing (i.e. on a new install), it would be possible to source route (or partially source route) even an non-route-able packet to a destination in a LAN, ostensively from the IPTables protected host, and then to respond to that opened pinhole (related connection) in the IPTables firewall. I presently see rogue hosts, which are NOT DNS servers, sending unsolicited DNS responses (UDP/TCP port 53) to various hosts on my LAN (as well as faux ICMP responses) to try to open that pinhole to respond to. The ploy is almost as prevalent as MITM attacks, though, since it’s really difficult to detect good MITM attacks, how many MITM attacks can really be identified?

by using the above commands i’m getting the following error..
iptables v1.4.12:ether
can any1 help pls?

I’m having a hard time getting a simple iptable working for mac filtering. I’m using the following:

This SHOULD allow the mac address full access.. But all packets are still being dropped. The client has no access to the internet. Can anyone help me out. What am I doing wrong? This is on DD-WRT. Thanks

]# iptables -A INPUT -i enp0s25 -p tcp –destination-port 22 -m mac –mac-source 14-58-D0-B7-2C-A7 -j ACCEPT
iptables v1.4.21: ether
Try `iptables -h’ or ‘iptables –help’ for more information.
[root@localhost

Wrong format: 14-58-D0-B7-2C-A7
Need to be in 14:58:D0:B7:2C:A7

This works only in a LAN enviroment or in a internet public webserver?

i want to write a rule in IPtable so that i can any single MAC address to telnet on port 2333. any suggestions??

Источник

Читайте также:  How to find which windows version
Оцените статью