Syn
Содержание:
In general
DoS (Denial of Service) attack can cause overloading of a router. Which means that the CPU usage goes to 100% and router can become unreachable with timeouts. All operations on packets which can take significant CPU power like firewalling (filter, NAT, mangle), logging, queues can cause overloading if too many packets per second arrives at the router.
Generally there is no perfect solution to protect against DoS attacks. Every service can become overloaded by too many requests. But there are some methods for minimising the impact of an attack.
- Get a more powerful router or server
- Get a more faster uplink
- Reduce the number of firewall rules, queues and other packet handling actions
- Track attack path and block it closer to source (by upstream provider)
DDoS атаки на сеть жертвы
Общей целью такого типа атак является перегрузка сети. Атакер прямо или отраженно посылает большой объем трафика на веб-сервис жертвы. В результате, часть пользователей не имеет доступа к веб-сервису, или он становиться полностью недоступным. При прямой атаке запросы идут напрямую к веб-сервису жертвы. При отраженной атаке запрос с поддельным адресом отправителя идет на промежуточное звено, и жертва получает ответ на него.
Ping flood атака (или ICMP flood)
Алгоритм: Большое количество ICMP Echo запросов посылается жертве с разных IP. Эти запросы должны быть обработаны и сервер обычно должен отправить ответ. Если объем запросов и ответов превышает ширину полосы пропускания сети, сайт становиться не доступен для настоящих пользователей. Атака также может перегрузить CPU, если машина сайта относительно медленная. Чтобы атака была успешной, атакер должен иметь больший канал сети, чем жертва.
Противодействие:
- Отключение ответов на ICMP-запросы.
- Понижение приоритета обработки ICMP-запросов так, чтобы они обрабатывались в последнюю очередь по остаточному принципу.
- Ограничение скорости трафика ICMP так, чтобы когда превышены настроенные пороги, не принимать ICMP-пакеты.
- Настройка фильтров ограничения скорости ICMP глобально на отдельных Интерфейсах Ethernet и в шаблонах виртуального сервера.
Smurf атака
Алгоритм: Большое количество ICMP-запросов посылается в сеть. Такая сеть называется усиливающей. При этом в запросе IP-адрес отправителя меняется на IP-адрес жертвы. Таким образом, жертва получает большое количество ответов на ICMP-запросы, которые она не делала. Это ведет к снижению или полной блокировке канала сети жертвы.

Противодействие: Анализ загрузки сети и выявление причин перегрузки поможет в выявлении атаки. Можно настроить сервер так, чтобы вообще не отвечать ICMP-запросы или запретить пересылку пакетов по таким запросам. Или через настройки Sysctl отключить ping ответы на серверах.
Fraggle атака – разновидность Smurf атаки
Алгоритм: Атакер отправляет большое количество UDP-пакетов на седьмой и девятнадцатый порты усиливающей сети. В UDP-пакетах адрес отправителя меняется на адрес жертвы. Обычно многие компьютеры реагируют на UDP-пакет и отправляют ответ на адрес жертвы. В результате сеть терпит перегрузку, и веб-сервис может быть не доступен.
Противодействие: аналогичное, как для Smurf-атаки.
UDP-flood атака
Алгоритм: Атакер отсылает жертве большое количество UDP-пакетов на разные порты хост-системы. Система жертвы пытается безуспешно проверять приложения слушающие порт и, в конечном итоге, отправляет ICMP Destination Unreachable пакет. Так как атакер передает многочисленные UDP-пакеты, веб-сервис становиться недоступен для настоящих клиентов.

Противодействие: Для противодействия необходимо ограничить скорость от определенных IP адресов или количество отправки ICMP пакетов. Запретить передачу по UDP протоколу. Чтобы использовать UDP, его можно изолировать от внешней сети.
NTP amplification атака
Алгоритм: Атакер использует общедоступные серверы протокола сетевого времени (NTP). Передача данных идет по протоколу UDP. Он отправляет запрос с командой «monlist» на NTP-сервер, но свой IP-адрес заменяет поддельным IP-адресом. В результате ответ получает жертва. При большом трафике сеть жертвы перегружается, и становиться недоступной. Усиление атаки происходит за счет размера ответа, который может от 20 до 200+ раз превышать размер запроса. Так же для усиления может использоваться botnet.
Противодействие: Сложность смягчения таких атак в том, что трафик от NTP-сервера считается легитимным. Особую угрозу несет степень усиление, которое может нанести вред даже устойчивой инфраструктуре. Для смягчения атаки можно использовать специальный софт для фильтрации трафика.

Unintentional DDoS атака
Алгоритм: Ссылка на небольшой сайт жертвы добавляется на очень популярный сайт. Трафик веб-сайта значительно увеличивается, что приводит к перегрузке сети. Такой тип атак критичен для сайтов, которые могут обрабатывать только очень ограниченный трафик. Таким образом, происходит DDoS атака через реальный трафик.
Detecting SYN flood Attack
The generic symptom of SYN Flood attack to a web site visitor is that a site takes a long time to load, or loads some elements of a page but not others. If you suspect a SYN Flood attack on a web server, you can use netstat command to check the web server connection requests that are in “SYN_RECEIVED” state.
If it shows numerous connections with this state, the server could be under SYN Flood attack. If the attack is direct with large number of SYN_RECV packets from a single IP address, you can stop this attack by adding that IP address in the firewall. If you have APF or CSF firewall installed on your server, you can accomplish this by executing the following command:
Methods of mitigation
While modern operating systems are better equipped to manage resources, which makes it more difficult to overflow connection tables, servers are still vulnerable to SYN flood attacks.
There are a number of common techniques to mitigate SYN flood attacks, including:
Micro blocks—administrators can allocate a micro-record (as few as 16 bytes) in the server memory for each incoming SYN request instead of a complete connection object.
SYN cookies—using cryptographic hashing, the server sends its SYN-ACK response with a sequence number (seqno) that is constructed from the client IP address, port number, and possibly other unique identifying information. When the client responds, this hash is included in the ACK packet. The server verifies the ACK, and only then allocates memory for the connection.
RST cookies—for the first request from a given client, the server intentionally sends an invalid SYN-ACK. This should result in the client generating an RST packet, which tells the server something is wrong. If this is received, the server knows the request is legitimate, logs the client, and accepts subsequent incoming connections from it.
Stack tweaking—administrators can tweak TCP stacks to mitigate the effect of SYN floods. This can either involve reducing the timeout until a stack frees memory allocated to a connection, or selectively dropping incoming connections.
Obviously, all of the above mentioned methods rely on the target network’s ability to handle large-scale volumetric DDoS attacks, with traffic volumes measured in tens of Gigabits (and even hundreds of Gigabits) per second.

Imperva mitigates a 38 day-long SYN flood and DNS flood multi-vector DDoS attack.
Imperva DDoS protection leverages Anycast technology to balance the incoming DDoS requests across its global network of high-powered scrubbing centers. With the combined capacity of its global network, Incapsula can cost-effectively exceed attacker resources, rendering the DDoS attack ineffective. The service is build to scale on demand, offering ample resources to deal with even the largest of volumetric DDoS attacks.
To assure business continuity, Imperva filtering algorithm continuously analyzes incoming SYN requests, using SYN cookies to selectively allocate resources to legitimate visitors. This enables transparent DDoS mitigation, wtih no downtime, latency of any other business disruptions.
Attack description
When a client and server establish a normal TCP “three-way handshake,” the exchange looks like this:
- Client requests connection by sending SYN (synchronize) message to the server.
- Server acknowledges by sending SYN-ACK (synchronize-acknowledge) message back to the client.
- Client responds with an ACK (acknowledge) message, and the connection is established.
In a SYN flood attack, the attacker sends repeated SYN packets to every port on the targeted server, often using a fake IP address. The server, unaware of the attack, receives multiple, apparently legitimate requests to establish communication. It responds to each attempt with a SYN-ACK packet from each open port.
The malicious client either does not send the expected ACK, or—if the IP address is spoofed—never receives the SYN-ACK in the first place. Either way, the server under attack will wait for acknowledgement of its SYN-ACK packet for some time.

Progression of a SYN flood.
During this time, the server cannot close down the connection by sending an RST packet, and the connection stays open. Before the connection can time out, another SYN packet will arrive. This leaves an increasingly large number of connections half-open – and indeed SYN flood attacks are also referred to as “half-open” attacks. Eventually, as the server’s connection overflow tables fill, service to legitimate clients will be denied, and the server may even malfunction or crash.
While the “classic” SYN flood described above tries to exhaust network ports, SYN packets can also be used in DDoS attacks that try to clog your pipes with fake packets to achieve network saturation. The type of packet is not important. Still, SYN packets are often used because they are the least likely to be rejected by default.
See how Imperva DDoS Protection can help you with TCP DDoS attacks.
Request Demo
or learn more
Обнаружение DDoS и защита от атак.
Для настройки firewall Mikrotik на обнаружение и защиты от DDOS-атак взята за основу на официальном Wiki Mikrotik.
Для того, чтобы выявить DDoS атаку нам необходимо захватывать все новые соединения и перенаправлять их в отдельную цепочку chain=detect-ddos.
Далее создаем новую цепочку chain=ddos, в которой для каждой пары хостов «SrcIP:DstIP» разрешаем определенное количество соединений. Для избежания блокирования важных хостов, например DNS-сервер с адресом 192.168.0.1, можно добавить правило, которое будет возвращать соединения с сервером в стандартную цепочку.
Здесь стоит обратить внимание на параметр dst-limit. Первое значение rate, второе burst
Для burst задано значение 42 и интервал в 1 секунду — это значит, что в течении первой секунды количество соединений может быть увеличено до 42. Значение burst не должно быть меньше rate, потому-что в этом случае правило правило будет пропускать в первую секунду меньшее количество соединений и по истечении секунды сработает Rate.
Сейчас нам надо обработать те соединения, которые превысили заданные лимиты — их мы добавим в address-list ‘ddoser’ (атакующий) и ‘ddosed’ (атакуемый). Тайм-аут жизни списка 10 минут или определите сами для себя.
Теперь мы можем блокировать хосты ведущие DDoS атаку на основе созданных списков. Сбрасывать пакеты можно в стандартной цепочке firewall таким образом:
Либо создать правило в Raw, чтобы отбрасывать пакеты до их маршрутизации и снизить нагрузку на процессор.
HTTP-флуд
Количество процессов ps
aux |
grep
apache |
wc
-l
Количество конектов на 80 порту netstat
-na
|
grep
«:80\ »
|
wc
-l
Просмотреть список IP- адресов, с которых идут запросы на подключение: netstat
-na
|
grep
«:80\ »
|
sort
|
uniq
-c
|
sort
-nr
sysctl
Защита от спуфинга net.ipv4.conf.default.rp_filter = 1
Проверять TCP-соединение каждую минуту. Если на другой стороне — легальная машина, она сразу ответит. Дефолтовое значение — 2 часа. net.ipv4.tcp_keepalive_time = 60
Повторить пробу через десять секунд net.ipv4.tcp_keepalive_intvl = 10
Количество проверок перед закрытием соединения net.ipv4.tcp_keepalive_probes = 5
Attack description
User Datagram Protocol (UDP) is a connectionless and sessionless networking protocol. Since UDP traffic doesn’t require a three-way handshake like TCP, it runs with lower overhead and is ideal for traffic that doesn’t need to be checked and rechecked, such as chat or VoIP.
However, these same properties also make UDP more vulnerable to abuse. In the absence of an initial handshake, to establish a valid connection, a high volume of “best effort” traffic can be sent over UDP channels to any host, with no built-in protection to limit the rate of the UDP DoS flood. This means that not only are UDP flood attacks highly-effective, but also that they could be executed with a help of relatively few resources.
Some UDP flood attacks can take the form of DNS amplification attacks, also called “alphabet soup attacks”. UDP does not define specific packet formats, and thus attackers can create large packets (sometimes over 8KB), fill them with junk text or numbers (hence the “alphabet soup”), and send them out to the host under attack.
When the attacked host receives the garbage-filled UDP packets to a given port, it checks for the application listening at that port, which is associated with the packet’s contents. When it sees that no associated application is listening, it replies with an ICMP Destination Unreachable packet.

Imperva mitigates a massive UDP (DNS) flood, peaking at over 25 million packets per second
It should be noted that both amplified and non-amplified UDP floods could originate from botnet cluster of various sizes. The use of multiple machines will classify this attack as Distributed Denial of Service (DDoS) threat. With such attack the offender’s goal is to overbear firewalls and other components of the more resilient network infrastructures.
See how Imperva DDoS Protection can help you with UDP flood attacks.
Request Demo
or learn more
Methods of mitigation
At the most basic level, most operating systems attempt to mitigate UDP flood attacks by limiting the rate of ICMP responses. However, such indiscriminative filtering will have an impact on legitimate traffic.
Traditionally, UDP mitigation method also relied on firewalls that filtered out or block malicious UDP packets. Yet, such methods are now becoming irrelevant, as modern high-volume attacks can simply overbear firewalls, which are not designed with overprovisioning in mind.
Imperva DDoS protection leverages Anycast technology to balance the attack load across its global network of high-powered scrubbing servers, where it undergoes a process of Deep Packet Inspection (DIP).
Using proprietary scrubbing software, specifically designed for inline traffic processing, Incapsula identifying and filters out malicious DDoS packets, based on combination of factors like IP reputation, abnormal attributes and suspicious behavior.
The processing is performed on-edge, and with zero delay, allowing only clean traffic to reach the origin server.
Slow Session Attack
In a Slow Session Attack, attackers send valid TCP-SYN packets and perform TCP three-way handshakes with the victim to establish valid sessions between the attacker and victim. The attacker first establishes a large number of valid sessions then slowly responds with an ACK packet and incomplete requests to keep the sessions open for long periods of time. Normally, the attacker will set the attack to send an ACK packet with an incompleted request typically before the session time-out is triggered by the server. The “held-open” sessions can eventually exhaust the victim server’s resources used to compute this irregularity. Low-and-slow tools have also been designed to consume all 65,536 available “sockets” (source ports) resulting in a server’s inability to establish any new sessions. Slow Session Attacks are always non-spoofed in order to hold sessions open for long periods of time.
TOS Flood
In a TOS (Type of Service) Flood, attackers use the ‘TOS’ field of an IP header. This field has evolved over time and is now used for Explicit Congestion Notification (ECN) and Differentiated Services (DiffServ). While this type of flood isn’t seen too often, there are two types of attacks which may be launched based on this field. In the first, the attacker spoofs ECN packets in order to reduce the throughput of individual connections. This could cause the server to appear out of service or unresponsive to customers. In the second, the attacker utilizes the DiffServ class flags in order to potentially increase the priority of the attack traffic over that of non-attack traffic. Utilizing DiffServ flags isn’t a DDoS attack in itself; this function is aimed at increasing the effectiveness of the attack.
Specially Crafted Packet
In a Specially Crafted Packet Attack, attackers take advantage of websites with poor designs, vulnerable web applications and/or have improper integration with backend databases. For example, attackers can exploit vulnerabilities in HTTP, SQL, SIP, DNS etc., and generate specially crafted packets to take advantage of these protocol “stack” vulnerabilities to ultimately take the servers offline. They can also generate requests that will lock up database queries. These attacks are highly specific and effective because they consume huge amounts of server resources and often are launched from a single attacker. An example of a Specially Crafted Denial of Service attack is MS13-039.
Защита от основных видов DoS-атак
Чтобы защитится от HTTP-flood нужно прибавить одновременное количество максимальных подключений к БД сервера, нужно установить перед апачем еще и энжинкс для кэширования всех запросов. Данный конфиг приведу файликом, который можно глянуть:
nginx.conf
Защита от ICMP-flood
Расскажу сейчас как бороться от ICMP-flood, а всего то нужно отключить ответы на запросы ICMP ECHO:
# sysctl net.ipv4.icmp_echo_ignore_all=1
Так же это можно сделать с помощью брандмауэра:
# iptables -A INPUT -p icmp -j DROP --icmp-type 8
Защита от UDP-flood
Т.к UDP-пакеты посылаются на разные UDP-сервисы, то собственно достаточно вырубить их от мира и прописать собственно ограничение на количество соединений к DNS-серверу:
# iptables -I INPUT -p udp --dport 53 -j DROP -m iplimit --iplimit-above 1
Защита от SYN-flood
Эта данная защита заключается в выключении самой очереди «полуоткрытых» TCP-соединений:
# sysctl -w net.ipv4.tcp_max_syn_backlog=1024
Так же нужно включить сам механизм TCP syncookies, для этого следует выполнить:
# sysctl -w net.ipv4.tcp_syncookies=1
Следующим этапом мы ограничиваем максимального число «полуоткрытых» соединений с 1-го IP для нужного порта:
# iptables -I INPUT -p tcp --syn --dport 80 -m iplimit --iplimit-above 10 -j DROP
У вас должна быть настроена система, которая будет анализировать трафик и которая сможет своевременно узнать о ДДос-атаке, а так же по мере возможности, принимать меры по ее избежанию.
Защита от DDoS с iptables, готовый скрипт
Защита от спуфинга
Для этого нужно выполнить:
# net.ipv4.conf.default.rp_filter = 1
Проверяем TCP-соединение каждую минуту (если на др стороне — нормальный сервер, то сразу ответит. (Стандартное значение — 2ч):
# net.ipv4.tcp_keepalive_time = 60
Проверяем через 10 сек:
# net.ipv4.tcp_keepalive_intvl = 10
Устанавливаем количество проверок перед закрытием соединения:
# net.ipv4.tcp_keepalive_probes = 5
Я очень бегло рассказал и описал что и как, но постепенно ( со временем) я буду рассказывать и приводить примеры по борьбе с ДДосиками, так же я буду более глубоко уделять вниманию каждому из видов атак. Чтобы это я мог сделать, мне нужно время, время для того чтобы я смог найти нужный и полезный материал, а так же более подробно расписал, чтобы всем было понятно. Надеюсь я нормально пишу статьи, если есть замечания или может предложения, добавляйтесь в группы, можно и в друзья, а так же можете просто писать в комментах.
Собственно, я завершу наверное на этом «защита от ddos атак», надеюсь было полезно. Спасибо что посещаете мой сайт https://linux-notes.org