- Пожалуйста, расскажите почему?
- Почему?
- Advantage: can be saved for further analysis
- Advantage: most complete look at network traffic
- Asset discovery/passive reconnaissance
- Capturing our first packet
- Colasoft capsa
- Disadvantage: large file sizes
- Disadvantage: too much information
- Filtering
- Formats, libraries, and filters, oh my!
- How does packet capture work?
- How to read a packet capture
- How to run a packet capture on a fortigate (cli)
- Intrusion detection
- Kismet
- Packet analysis
- Packet capture and packet sniffer use cases
- Packet capture formats
- Solarwinds network performance monitor
- Tcpdump
- Writing a basic packet capture engine
- Полезно
- Телефония
Пожалуйста, расскажите почему?
![]()
Почему?
😪Мы тщательно прорабатываем каждый фидбек и отвечаем по итогам анализа. Напишите, пожалуйста, как мы сможем улучшить эту статью.
Advantage: can be saved for further analysis
Packet captures can be saved for further analysis or inspection in industry-standard .pcap and .pcapng formats. This allows, for example, suspicious traffic to be saved by a network engineer and then later reviewed by a security analyst. A wide variety of tools support this format, including security analysis tools.
Advantage: most complete look at network traffic
Packet capture is by definition a duplicate copy of the actual packets traversing a network or network link. It is, therefore, the most thorough look at network traffic possible. Packet captures contain a great level of detail not available in other monitoring solutions, including complete payload, all IP header fields, and in many cases even information about the capture interface. This can make capturing the only viable solution in cases when lots of detail is required.
Asset discovery/passive reconnaissance
Packets by their very nature include source and destination addresses, so a packet capture can be used to discover active endpoints on a given network. With enough data, it’s even possible to fingerprint the endpoints. When done for legitimate business purposes, this is called discovery or inventory.
However, the passive nature of a packet capture makes it an excellent way for malicious attackers to gather information for further stages of an attack. Of course, the same technique can be used by red teamers testing an organization’s security
Capturing our first packet
Итак , мы определили интерфейс и готовы к захвату пакетов. Рассмотрим пример — testpcap1.c:
Если вы соблюдаете все правила , то вывод должен быть типа:
destination address — в данном случае должен быть гейтом. Проверим роутинг: теперь наберем команду arp для получения адреса ethernet:
Обратите внимание на то , что адрес гейта — 192.168.1.1 -соответствует destination address пакета. Все пакеты , посылаемые с вашей машины , если они не прдназначены для конкретной машины, посылаются через гейт.А откуда наш компьютер знает адрес гейта?
Этот Hardware-адрес получается с использованием Address Resolution Protocol или ARP. ARP описан в RFC826. Когда вы посылаете пакет, ядро проверяет arp cache , если там destination address.
Давайте удалим destination address из кеша: После чего компьютер пытается сделать широковещательный запрос — broadcast (ff:ff:ff:ff:ff:ff), пытаясь отыскать IP 192.168.1.1.
Допустим наша сетка имеет пропускную способность в 10Mb/s.
Первое поле ETH_ALEN есть destination ethernet address пакета. Второе поле ETH_ALEN — источник. Третье поле — тип пакета. id-шники протоколов из net/ethernet.h Нам итересен прежде всего IP и немного ARP.
Colasoft capsa
ColaSoft makes a commercial packet sniffer aimed at enterprise customers, but also offers a pared-down edition aimed at students and those just getting into networking. The tool boasts a variety of monitoring features to aid in real-time troubleshooting and analysis.
Disadvantage: large file sizes
Full packet capture can take up large amounts of disk space – in some cases up to 20 times as much space as other options. Even when filtering is applied, a single capture file may take up many gigabytes of storage. This can make packet captures unsuitable for long-term storage. These large file sizes can also result in lengthy wait times when opening a .pcap in a network analysis tool.
Disadvantage: too much information
While packet captures to provide a very complete look at network traffic, they’re often too comprehensive. Relevant information can often get lost in vast sums of data. Analysis tools have features order, sort, and filter capture files, but many use cases might be better served by other options.
It’s often possible to troubleshoot a network or spot signs of an attack with just the summarized versions of network traffic available in other monitoring solutions. One common approach is to use a technology like NetFlow to monitor all traffic and turn to a full packet capture as needed.
Filtering
Full packet capture can take quite a bit of space and demand more resources from the capturing device. It’s also overkill in most cases – the most interesting information is typically only a small portion of the total traffic being observed. Packet captures are often filtered to weed out the relevant information. This can be based on everything from the payload to IP address to a combination of factors.
A large number of different tools are available to capture and analyze the packets traversing your network. These are sometimes known as packet sniffers. Here are some of the most popular:
Formats, libraries, and filters, oh my!
When it comes to packet captures, there’s a range of related terminology that can get confusing rather quickly. Let’s break down some of the most common and important terms you might hear:
How does packet capture work?
There’s more than one way to catch a packet! Packet captures can be done from a piece of networking equipment like a router or switch, from a dedicated piece of hardware called a tap, from an analyst’s laptop or desktop, and even from mobile devices.
Capturing packets from your own machine is the easiest way to get started, but there are a few caveats. By default, network interfaces only pay attention to traffic destined for them. For a more complete view of network traffic, you’ll want to put the interface in promiscuous mode or monitor mode.
How to read a packet capture
In order to understand and analyze a packet capture, you’ll need some fundamental knowledge of basic networking concepts, especially the OSI model. While there may be differences between specific tools, packet captures will always consist of a payload and some headers.
The payload consists of the actual data being transferred – this could be bits of a streaming movie, e-mails, ransomware, or anything else traversing a network. Packet headers contain all the critical information that helps network equipment decide what to do with each packet.
Most important are the source and destination addresses, but IP packets have a total of 14 headers covering everything from Class of Service to Protocol Type. A professional network analyst will have detailed knowledge of all of these fields, but a general understanding of packet structure is all it takes to get started troubleshooting performance issues or learning more about how networks operate.
| Version | Header Length | DSCP Value | ECN | Total Packet Length |
| Identification | Flags | Fragment Offset | ||
| Time to Live (TTL) | Protocol | Header Checksum | ||
Source IP Address | ||||
Destination IP Address | ||||
Optional | ||||
Apart from source and destination addresses, some of the most important fields from a troubleshooting perspective may include Differentiated Services Code Point (DSCP), Flags, and TTL. DSCP is used to ensure Quality of Service (QoS), and is an important field for real-time traffic like Voice over IP (VoIP).
Flags are most often used to control packet fragmentation and can become a problem when a packet that has the Don’t Fragment flag also exceeds the Maximum Transmission Unit (MTU) size of a network link. TTL values are decremented after each hop and can provide important clues about a packet’s path through the network.
How to run a packet capture on a fortigate (cli)
This is a quick reference guide showing how to run a packet capture on a Fortigate. it is important to remember that the packet capture will only show packets that are being handled via the Kernal (Not being offloaded to an ASIC) you can however disable this on the policy as follows:
1 – Disable ASIC offload for traffic (Optional)
I have put optional as you don’t need to but ensures you get the packets to look at.
2 – Setup the capture
The syntax is a spin off tcpdump, essentially it is tcpdump under the hood but most filters will work. the syntax is as follows, options and verbose level are optional. I ussually use verbose 4 so I can see the interface names
all flags / options apart from interface are optional
interface – The actual interface you want the sniffer to run on or capture packets on, you can use the word any for all interfaces or specify the name of the interface
options – The tcpdump filter options you want to use, these must be surrounded by double or single quotes
verbose level – This can be a number between 1 and 6 and is defined as follows:
1: print header of packets
2: print header and data from ip of packets
3: print header and data from ethernet of packets (if available)
4: print header of packets with interface name
5: print header and data from ip of packets with interface name
6: print header and data from ethernet of packets (if available) with intf name
count – limit of packets you want to count, when this number is reached sniffer will stop, use 0 for unlimited
timestamp format – The format for timestamp, by default it is the number in seconds and milliseconds from when you started the capture to when the displayed packet is recieved on the listening interface. Other options are a or l, a for absolute time and l for local time.
3 – example 1 – all icmp
This example is to capture all icmp traffic and show the interface name
I setup a test ping to the Fortigate whilst the sniffer was running
So with the verbose 4 flag I can see the request is coming in on port 2 (The icmp echo request) and the reply is being sent out via port 2. This makes sense as I a pinging the interface itself. I also get the timestamp right at the beginning which is by default relative to the time you started sniffing, so in my case, it was 2.216830 seconds after I entered the command that I received the echo request. You can change this so it shows an actual timestamp.
Same example however I add an additional flag which again is optional. 0 for the number of packets (Which means unlimited) and l for local time, this uses the time local to the Firewall defined under system time.
You can now see I have some output with an actual timestamp.
Other examples
These are some examples for the filter (The bit between the quotes) common ones which are good and I use most times. Obviously you can get extremely complex with it but here are a few examples
By ip address (Either source or destination)
Replace 10.1.1.1 with the IP address.
By network
so if you want to sniff track to or from 10.1.1.0/24 you would use this
Replace the network with any you need
By port number
This is useful if you are looking for traffic on a certain port
Again replace the port number with whatever port you need. This is for both TCP & UDP.
source or destination
Use this if you want to see traffic as the source or the destination. Useful if you only want initiatng traffic to be shown.
Protocol
You can filter by protocol e.g. tcp, udp icmp and so on
This for example would show only TCP traffic
Using AND
So if you need source = 10.1.1.1 and destination = 8.8.8.8 and its icmp you could string them together.
AND logic says both must be true.
Using OR
The logic of or is if one of the statement is true, whereas AND you need both to be true.
So if the source is either 10.1.1.1 or 10.1.1.2 this also means if there is traffic from both of these then it will show as the filter is run against each packet.
Combining AND and OR
So lets say you need the source is 10.1.1.1 or 10.1.1.2 and the port is 22 and the protocol is tcp you would have to use brackets as follows.
Notice how I put them in brackets, this bit is done first so I am saying source is 10.1.1.1 or 10.1.1.2 AND port is 22 and its tcp.
If you don’t use brackets its will still take it as a valid filter but it won’t yield what you want it to.
Using ! to negate
You can negate most things, so anything but this , not this.
So all ports except port 22 would be
Again you could add multiple to this list.
Thoughts?
So that’s a brief info into what you could potentially use the Fortigate’s built in packet capture for.
It comes in handy when troubleshooting a firewall issue. Couple this with a packet flow (More on that another time) and you can debug most situations for firewall policies.
It is also useful for routing , you may sometimes receive the traffic on the incorrect interface which will cause the reverse path lookup to fail as an anti-spoofing mechanism that most stateful firewall’s incorporate.
Thanks for reading, if you have any questions about this or need some help on a specific filter please feel free to leave a comment or get in touch.
If you are interested in looking more into the filters then look at tcpdump most of these will work.
Intrusion detection
Suspicious network traffic can be saved as packet capture and fed into an IDS, IPS, or SIEM solution for further analysis. Attackers go to great lengths to blend in with normal network traffic, but a careful inspection can uncover covert traffic.
Known malicious IP addresses, telltale payloads, and other minute details can all be indicative of an attack. Even something as innocuous as a DNS request, if repeated at a regular interval, could be a sign of a command and control beacon.
Kismet
Kismet is a utility devoted to capturing wireless traffic and detecting wireless networks and devices. Available for Linux, Mac, and Windows platforms, this tool supports a wide range of capture sources including Bluetooth and Zigbee radios. With the right setup, you can capture packets from all of the devices on the network.
Packet analysis
В этом разделе мы затронем тему выделения информации. Для этого неплохо бы знать соответственные RFC: RFC 791 (IP),RFC 768 (UDP),RFC 826 (ARP),RFC 792 (ICMPv4) и конечно RFC 793 (TCPv4).
Настоятельно рекомендую вам использовать другой сниффер для подтверждения всего того, что я тут наговорил.Например,tcpdump или ethereal. Оба этих снифера могут анализировать как пакеты, так и сами данные.
Следующая программа будет построена на основе предыдущих, с небольшим изменением callback function, которая передается в pcap_loop() или pcap_dispatch(). Рассмотрим следующий пример:
Эта программа будет использована в качестве заготовки для дальнейших программ. Вы могли заметить, что я передаю u_char* ( NULL) в pcap_loop(). Это делается для передачи первого аргумента. Итак, нам нужно прочитать тело TCP packets.
Важнейшим элементом любого хидера является тип пакета. Структура struct ether_header из net/ethernet.h:
Это дает нам возможность конвертации ethernet headers в читаемый ascii. конвертация ethernet address в HOSTNAME Кое-что тут было позаимствовано из небезизвестного Steven’s-а. А вот и callback function для управления ethernet headers, распечатки source и destination — адресов:
В исходниках вы найдете пример disect1.c.
Давайте теперь подробнее посмотрим на IP-хидер:
Packet capture and packet sniffer use cases
While the term Packet Sniffer may conjure up images of hackers covertly tapping into sensitive communications, there are plenty of legitimate uses for a packet sniffer. The following are some typical use cases for packet sniffers:
Packet capture formats
While packet capture tools like Wireshark can be used to inspect traffic in real-time, it’s more common to save captures to a file for later analysis. These files can be saved in a variety of formats. .pcap files are the most common and are generally compatible with a wide range of network analyzers and other tools. .pcapng builds on the simple .pcap format with new fields and capabilities and is now the default format when saving files in Wireshark. Some commercial tools may also use proprietary formats.
Solarwinds network performance monitor
This commercial tool has long been a favorite for its ease of use, visualizations, and ability to classify traffic by application. Though the tool only installs on Windows platforms, it can sniff and analyze traffic from any type of device.
Tcpdump
Lightweight, versatile, and pre-installed on many UNIX-like operating systems, tcpdump is a CLI junkie’s dream come true when it comes to packet captures. This opensource tool can quickly capture packets for later analysis in tools like Wireshark but has plenty of its own commands and switches to make sense of vast sums of network data.
Writing a basic packet capture engine
В этом разделе обсуждается такая тема,как написание енжина по захвату пакетов. Нам нужно научиться анализировать и фильтровать пакеты.
Рассмотрим следующий библиотечный метод pcap :
Он будет использован нами как один из базовых. Во время цикла pcap_loop(..) будет происходить захват пакетов, которые будут передаваться в callback function типа pcap_handler. Здесь представляют интерес аргументы 2 и 3, хидер для pcap packet и константа u_char.
В качестве примера напишем программу , которая захватывает в цикле n пакетов.
Allright then, lets give her a whirl!
Как вы видите , my_callback(. ) была вызвана 7 раз. Весь анализ пакетов мы положили внутрь my_callback. Но это не совсем правильное решение. Первая проблема в том , что pcap_loop(..) может подвиснуть в случае отсутствия пакетов. Было бы неплохо установить тайм-аут на чтение.
************ pcap_dispatch() используется для сбора пакетов. cnt — определяет максимальное число пакетов. cnt = -1 говорит о том , что все пакеты возвращаются в одном буфере. cnt = 0 обрабатывает пакеты до тех пор , пока не произойдет ошибка. callback — подпрограмма , вызываемая 3-м аргументом:u_char — указатель на нее, туда входит структура pcap_pkthdr и данные. pcap_dispatch() возвращает число прочитанных пакетов. -1 означает ошибку, для ее вывода можно использовать pcap_perror() или pcap_geterr(). ************
Нам неинтересны все пакеты,гуляющие по сети. Что нужно для того , чтобы захватить пакеты , зная номер хоста и номер порта ? Использовать pcap_compile(..) и pcap_setfilter(. ).
Мы можем захватить все пакеты и отсортировать их. Но трафик может быть нешуточным. В библиотеке libpcap есть интерфейс,позволяющий определить точно , какие пакеты нас интересуют. Для этого нужно передать фильтр в форме строки функции pcap_compile(). Есть волшебная программа tcpdump и ее man page.
Используем эту информацию в качестве отправной точки. Допустим,в моей локальной сетке 2 машины — линуксовая и виндовая, которые соединены через хаб. Если я сетевую карту на линуксовой машине установлю в promiscuous mode, я смогу увидеть весь трафик,идущий через виндовую машину.
Рассмотрим следующую программу :
Полезно
Узнать IP — адрес компьютера в интернете
Онлайн генератор устойчивых паролей
Онлайн калькулятор подсетей
Калькулятор инсталляции IP — АТС Asterisk
Руководство администратора FreePBX на русском языке
Руководство администратора Cisco UCM/CME на русском языке
Телефония
FreePBX и Asterisk
Настройка программных телефонов
