Как заблокировать ip адреса на fortigate

от admin

TravelingPacket – A blog of network musings

Fortigate 6.0 Adding and removing IPs from Quarantine list

Starting in 5.4.1 you could “Quarantine” an IP address. This means that the quarantined host cannot communicate through the firewall.

There are many different parts of the firewall the quarantine an IP address. For example the AV and IPS can both automatically quarantine an IP if it meets a defined violation.

In 6.0 you can view the IPs that have been quarantined by going to Monitor- Quarantine. From here you can see what IPs are blocked, and for what reason. As you can see in the image below 5.188.86.10 has been blocked for 26 days by an admin. If an admin blocks an IP address (as we will see) it shows up with “Administrative” as the source.The other IPs have been blocked by the IPS engine. The below image shows the monitor section.

So, lets say that you look into Fortiview and see that a remote IP is sending/receiving a ton of bandwidth and you want make sure that stops. in this example lets quarantine the IP 67.247.21.7.

In this example we can act like I was looking through Fortiview and found an issue that makes me want to block the above IP. You can just click on the IP you would like to block, right click and then select to “quarantine”. When you do this, it will pop up and ask for the length of time you would like to block them for.

block

The above shows that it will ban the IP from communication for the given period of time.

So, lets say we want to remove an IP address that has been quarantined – No problem, just need to go to Monitor-Quarantine and click on the IP and delete that individual or click to delete all entries.

delete-block

You can modify how long and for what reason the IPS/AV quarantine an address for within the policy. For example, below shows modifying the reason/time of quarantine. The AV settings are within the CLI of the AV policy under “nac-quar”. Something to note, sources are not quarantined by default.

Threat Feed in Fortigate (external IP blacklist).

This post shows how to use external black or white list of IP addresses using a new feature called Threat Feed. Starting with FortiOS 6.2 it’s possible to import external IP address and Domain Name lists for using in Firewall Policies and DNS Filter profiles. FortiOS 6.0 allowed using imported lists in Proxy Polices, but not in Firewall Policies. I will use FortiOS 6.2.3 for demo purposes.

Before we start

It is recommended to use the latest version of FortiOS, because even version 6.2.1 contains some minor bugs related to Threat Feed. For example, one of the problems with 6.2.1 is that it won’t work with HTTP servers using chunked transfer encoding.

Step 1. Create a list of IP addresses.

Create a text file which contains the list of IP addresses. The following list contains valid formats of IP addresses/subnets/ranges:

Step 2. Host the file on HTTP server

Upload the created file to your HTTP server, because Fortigate will download the file from the server via HTTP protocol. If you don’t know which web server to use you can read this post, which shows how to setup lightweight HTTP server using Chrome extension.

Check that your file is accessible via HTTP protocol. As you can see I can access my file with IP addresses using the following URL http://192.168.0.185:8887/blacklist.txt :

Step 3. Create a Threat Feed

Go to Security Fabric -> Fabric Connectors and click on Create New.

Scroll down to Threat Feeds category and select IP address.

Set the Name and the URI of external resource to configure the Threat Feed. Disable HTTP authentication if you don’t use one. Click OK to save. Use the screenshot for reference:

Step 4. Verify the status of a new Threat Feed.

After you create the new Threat Feed you should see it in Security Fabric -> Fabric Connectors. Make sure it has a green up arrow which means it successfully downloaded the text file:

You can also right-click the new Thread Feed and select View Entries. You should see the imported entries like this:

Step 5. Use the Threat Feed in a policy

Go to Policy&Objects -> IPv4 Policy and create a new policy. Now you can add the newly created Threat Feed as a Source or Destination. As you can see on the image below the Blacklist resource was added to the list of available entries to choose from:

You can hover the mouse over the Threat Feed resource and will see the details just like with any other entry:

Conclusion

Now you know how to create your own black or white list of IP addresses and use it in your firewall policies. Thank you for reading.

Как заблокировать внешнюю атаку с помощью FortiGate и Flowmon ADS

Как заблокировать внешнюю атаку с помощью FortiGate и Flowmon ADS 06.05.2021 14:00

Часто возникает вопрос — как использовать Flowmon для блокирования атаки? Flowmon не является встроенным устройством, стоящим на пути входящего трафика, поэтому он сотрудничает со сторонними поставщиками, которые поставляют оборудование, такое как брандмауэры или унифицированные шлюзы безопасности.

В этой статье мы рассмотрим, как настроить брандмауэр Fortinet FortiGate на блокировку трафика в ответ на обнаруженную с помощью Flowmon ADS аномалию или атаку. Эта конкретная интеграция предназначена для автоматической блокировки трафика брандмауэром и остановки его по периметру.

Что вам понадобится

Скрипты интеграции доступны для загрузки с нашего партнерского портала. Также опубликована и полная документация.

В настоящее время интеграция работает только с диапазонами адресов IPv4, так как для достижения этой цели с помощью IPv6 потребуется еще один вызов API для создания объекта адреса, но в действительности это зависит от вашего сетевого подключения. Если у вас есть только IPv4, доступный на WAN-интерфейсе, то нет необходимости в блокировке IPv6.

Подготовка

Один из способов блокировать атаки на устройстве FortiGate с включенной службой IPSec VPN — это настройка политики локального входа. По умолчанию политика локального входа разрешает доступ ко всем адресам, но вы можете создавать группы адресов для блокировки определенных IP-адресов. Одна такая группа может содержать до 600 IP-адресов, хотя ограничение будет варьироваться между отдельными платформами. Существует таймер, который удалит IP-адреса из списка через заданный период, чтобы сделать ротацию списка и сохранить его коротким.

Теперь, чтобы заставить Flowmon ADS блокировать IP-адреса, вам нужно видеть сетевой трафик до того, как он достигнет FortiGate.

Другими словами, вам нужны данные NetFlow / IPFIX от зонда Flowmon Probe, размещенного перед межсетевым экраном. Не рекомендуется использовать сам FortiGate для получения этих данных, потому что его flow-данные не содержат флаги TCP, а это означает, что многие методы обнаружения не дадут надежных результатов. Это касается даже последней версии FortiOS 6.4.

Когда у вас есть источник flow-данных и ваш Flowmon ADS настроен для обнаружения аномалий, вы можете установить упомянутый выше пользовательский пакет скриптов. Он использует вызовы REST API для создания адресных объектов из событий Flowmon ADS в FortiGate и сохраняет базу данных ранее заблокированных IP-адресов для дальнейшего использования.

Этот Python скрипт требует дополнительной библиотеки, которую вы обычно не найдете на своем устройстве Flowmon, но вы можете найти ее в пакете и установить там.

Установка

Во-первых, загрузите пакет (ag-mitigation.tar.gz) и импортируйте его через Configuration Center, как и любой другой программный пакет Flowmon. Тогда он будет находиться в /data/components/fgt-mitigation/.

01_list-of-packages-in-flowmon-configuration-center

Список установленных пакетов в Центре конфигурации Flowmon

Пакет содержит конфигурационный файл и два скрипта: ag-mitigation.py отвечает за блокировку и потребует загрузки в Flowmon ADS (см. ниже), а другой, ag-timeout.py, удаляет заблокированные адреса с помощью таймаута.

После установки вы сможете запустить/остановить скрипт таймаута из пользовательского интерфейса. Он использует базу данных SQLite3 для хранения информации о заблокированных IP-адресах и их времени жизни в этих записях. Вы можете настроить, как долго они должны оставаться на месте и, изменив планировщик cron, как часто должен выполняться скрипт.

Затем вам нужно включить локальную политику входа в FortiGate с действием по умолчанию, чтобы блокировать любой трафик в группе Flowmon ADS, работающей всегда.

02_FortiGate-local-in-policy-configured

Консоль FortiGate с настроенной политикой локального входа

В начале эта группа состоит всего из одной записи, которая в основном означает «нет IP-адреса». Это происходит только потому, что группа FortiGate не может быть пустой, и эта одна запись ничего не блокирует.

03_FortiGate-configuration-interface-with-address-group

Веб — интерфейс конфигурации FortiGate с группой адресов, настроенной для скрипта

Затем настройте один интерфейс мониторинга устройства Flowmon, подключенного к коммутатору управления в качестве WAN-порта для FortiGate. Это позволяет собирать весь трафик, проходящий через точку наблюдения, и видеть любую атаку на IP-адреса FortiGate WAN.

Используя конфигурацию Flowmon ADS, загрузите скрипт без каких-либо параметров и добавьте его в качестве пользовательского сценария запуска для работы с возможными проблемами безопасности при обнаружении события средней серьезности или выше.

04_Flowmon-ADS-custom-script-configuration

Настройка пользовательского скрипта Flowmon ADS

Блокирование

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

05_successful-ping-command

Успешная команда ping с IP — адресом FortiGate

При запуске скрипта информация в FortiGate обновляется через REST API, включая диапазон IP-адресов или определение подсети и включение в группу адресов Flowmon ADS.

06_IP-address-added-from-Flowmon-ADS

IP-адрес, добавленный Flowmon ADS с идентификатором события

07_event-in-the-address-group

Событие также появляется в группе адресов

Теперь список обновлен, и машина с IP-адресом 192.168.47.79 больше не может пинговать FortiGate или подключаться к нему ни на одном из своих портов. Это означает, что брандмауэр блокирует его на основе инструкций от Flowmon ADS.

08_ping-command-without-a-response

Команда ping без ответа

Скрипт таймаута используется для очистки списка заблокированных IP-адресов. После нескольких итераций сценария тайм-аута все возвращается в исходное состояние.

09_mutiple-executions-of-the-timeout-script

Многократное выполнение сценария таймаута

На приведенном выше экране показано, что в группу был добавлен еще один IP-адрес. Он будет храниться в базе данных как целочисленный тип для облегчения манипуляций.

В заключение

Это один из способов использования Flowmon в сочетании со сторонним встроенным устройством для автоматической минимизации последствий атак. Другой вариант — вы также можете использовать стандартную политику брандмауэра, где вы можете использовать дополнительный IP-адрес для интерфейса обратной связи, чтобы нежелательный трафик мог быть заблокирован. Все дело в приспособлении продуктов к вашим потребностям и обстоятельствам.

In Fortinet: how to simply block certain incoming ip!

Hi,
I tried something that should have been really simple: top rule = block those incoming ip’s!

It looks like this:
Image: post content

Читать:
Как заправить картридж hp 650 черный в домашних условиях

But it doesnt work.
And Fortinet Support explains that in a weird logic of theirs: «Destination ALL» doesn’t mean «ALL»

So they said that Virtual IPs do not belongs to ALL and that I would have to . first said » # set match-vip enable » but that doesn’t work for some reasons.

Then they say I have to create a rule that includes all my VIP and use that to block incoming ips. but everysingle time I add a VIP: I would have to remember to go back into that special rule and add the new VIP there which seems prone to risk of forgeting.

I asked them to put on their road maps a fix that will make «All» start behaving like all means all. but that doens’t seems to be interesting to them
Any ideas?

User: Philippe Janson

Are Your Applications Hybrid Cloud Ready?

31 Replies

Author Bojan Zajc

Bojan Zajc This person is a Verified Professional

  • check 81 Best Answers
  • thumb_up 394 Helpful Votes

. and there isn’t even a possibility to create an address object «Real_All» ?

Author Philippe Janson

I could probably create an object «All VIP» and put it in a deny rule for this but still need to build rules for other non-vip objects.

Author Bojan Zajc

Bojan Zajc This person is a Verified Professional

  • check 81 Best Answers
  • thumb_up 394 Helpful Votes

Well, I’m glad I’m not on Fortinet and that my Firewall very well understands what means «Any».

I’m not sure what you actually reference as «VIP» in Fortinet terminology — if that are the WAN IP’s or the internal IP addresses used in SNAT.

Still this should be IP address ranges. Usually address ranges, that are pretty well known. So it should be possible to create address objects by listing IP address ranges? Or does this simply not work? If not. than that is a HUGE fail of the firmware. — the worst part of it would be, that you are not warned, that it won’t work.

Author Austen Lowe

zer0kbps This person is a Verified Professional

What about a policy route for the offending IP to send it to a null/fake interface or something ?

At least it will never communicate back assuming the idea works

Author Philippe Janson

Bojan Zajc : they are good at a lot of things but they do suck for this one.
VIP means Virtual IP so it is just a «if you see internet request for this port, send it to that server on that port» or some 1:1 also.
I can’t understand why Fortinet would go to the trouble of building ips lists like «Known Malware ips» but not activate it by default in the system. everone of their clients need to :
1- Figure out that those lists of know hackers exists
2- Figure out how to block them
And Support clearly don’t want to send this issue to «Product Management RoadMaps Improuvements».

zer0kbps
Maybe. I could create a VIP that points to nowhere but . I would need to create one object per ips. that would be a paine and it would pollute my VIP listing sections.

Author Ethan Harris

Ethan6123 This person is a Verified Professional

A VIP is just a NAT and yes, Fortigates tend to be quirky when it comes to NATs. Like other things once you know the quirks you can watch out for them.

Perhaps the block rule is being applied before the Network Address Translation occurs (Tada! I blocked traffic to everyone on my list but now it’s a different ip address I’m not blocking traffic to).

It does seem like All should mean All.

You already asked this exact same question on another thread and were given an answer from a Fortinet rep so what was wrong with that answer ? It seems to me that you perhaps lack sufficient understanding of the workings of Firewalls. Firstly your example above clearly says

«set status disable»

So straight away there it will never work

Then the question is what is contained within that object you have defined as the srcipaddr «pjMaliciousIP» . Can you please show us the output of that address object because I have a FortiGate and there is no such predefined object like that within FortiOS? Address objects are not magic, you can’t just give one a name and hope that by some form of tech wizardry it is just automatically going to be populated with the IP addresses you hope to block. FQDN objects can do that because they are auto populated via DNS lookups. Fortinet’s malicious DB exists in it’s FortiGuard updates. There is an entire BotNet data base that can be invoked , as the guy from Fortinet said, by using the IPS ruleset.

Under the fabric external connectors there is an option to import IP address threat feeds. So if you have access to a threat feed database you can use this to populate that object BUT you have to realise that all DB’s are only as good as the last update. Malicious websites and IP’s are springing up the whole time. As the guy from Fortinet clearly stated the implicit rule will stop any IP that has not been explicitly allowed. You don’t protect your internal network by trying to block all malicious external addresses entering you segment your network, you constrain inside out behaviour so that your users don’t open themselves up for attack so using SSL deep inspection to de-obfuscate all traffic, use URL filtering- if they can’t get to malicious webservers they can’t download bad stuff, AV prevents MALWARE piggy backing on other streams, IPS looks for indicators of attack and blocks them, Application firewalling prevents your users using things that SSL DI can’t deep inspect e.g. Skype, ToR browser, BiTTorrent.

Having a rule that blocks from the outside in will NEVER NEVER NEVER block those IP’s reaching your users if they have initiated the connection to those IP’s from the inside. A firewall process rules from top down parsing and everything is session based. If you invoke a session from the inside out, traffic will automatically be allowed back in as part of that same session. It won’t matter if your block policy is above the user policy, when the return traffic comes back, even from one of those IP’s the FW will look in it’s session table, see the corresponding initiating session and allow the return. ALL vendors Firewalls work the exact same way.

Now if you are exposing a web server that is a whole other topic because that traffic is initiated from the outside but from your other thread that is not what you are trying to deal with.

Author Philippe Janson

1- Everyone asking question on ANY forum , by Definition, lacks understanding johnwilson19
= that’s the whole point of those forums.

2- If you see «set status disable» it is simply because it is a «reduce» EXAMPLE of all my incoming denies rules. I should have obfuscated it in my printscreen.

3- No, I am not satisfied with the answer Fortinet Support provided, they clearly don’t understand the impracticability of it and I hope to find somewhere some wise firewall guy that operates outside the realm of «theory» like the Fortinet techs and has found a way around this limitation in the real world. there is often ways. like the good idea zer0kbps proposed

4- pjMaliciousIP is obviously I group that I, PJ, created and I am adding manually in that group ip’s of known attackers.

5- I also uses default group that are build in the fortigate: Botnet-C&C_Server, Malicious-Malicious.Server, Phishing-Phishing_Server, Spam-Spamming_Server.

6- «Address objects are not magic, you can’t just give one a name and hope that by some form of tech wizardry it is just automatically going to be populated with the IP addresses you hope to block. »
= stating the obvious there .

7- » Under the fabric external connectors there is an option to import IP address threat feeds. So if you have access to a threat feed database you can use this to populate that object BUT you have to realise that all DB’s are only as good as the last update. «
= yes that is good but the problem here is not «finding the malicious SOURCE»: it is to have it blocked.

8- » As the guy from Fortinet clearly stated the implicit rule will stop any IP that has not been explicitly allowed.» :
= yes . this is already obvious.
The whole question here is «how to simply block certain (source) ip’s «.
No one build a rule to let only some ip pass (rarely) most often a rule will allow all external ip pass to reach an internal resource like a web server. So the «implicit» deny rule is useless to stop specific ip . thus the desire to block specific ip’s.

9- » You don’t protect your internal network by trying to block all malicious external addresses entering you segment your network, . «
= Yes you can. «all» would be difficult but some more problematic then others: why not.

10- «. you constrain inside out behaviour so that your users don’t open themselves up for attack so using SSL deep inspection to de-obfuscate all traffic, use URL filtering- if they can’t get to malicious webservers they can’t download bad stuff, AV prevents MALWARE piggy backing on other streams, IPS looks for indicators of attack and blocks them, Application firewalling prevents your users using things that SSL DI can’t deep inspect e.g. Skype, ToR browser, BiTTorrent.»
= These are other complementary layers of protections. They are not mutually exclusive.

11- » Having a rule that blocks from the outside in will NEVER NEVER NEVER block those IP’s reaching your users if they have initiated the connection to those IP’s from the inside . »
= this is obvious. But again, the question here isn’t this.

12- » Now if you are exposing a web server that is a whole other topic because that traffic is initiated from the outside but from your other thread that is not what you are trying to deal with. »
= that is probably your source of confusions. forget the other thread: the question here is really «How to block certain Incoming ip’s. » . to whatever internal destination .

Bojan Zajc and Ethan6123 : if you are not on Fortinet: what are you on? I used checkpoint for 9 years and I do miss it from time to time. they did not had this limitation Fortinet has . but they were just too expensive to buy at this new place.

Похожие статьи