Протокол передачи команд и сообщений об ошибках icm

From Wikipedia, the free encyclopedia

This article is about the support protocol for IPv4 (ICMPv4). For ICMPv6, see ICMPv6.

Internet Control Message Protocol

Communication protocol

A general header for ICMPv4

Purpose Auxiliary protocol for IPv4[1]
Developer(s) DARPA
Introduction 1981
OSI layer Network layer
RFC(s) RFC 792

The Internet Control Message Protocol (ICMP) is a supporting protocol in the Internet protocol suite. It is used by network devices, including routers, to send error messages and operational information indicating success or failure when communicating with another IP address, for example, an error is indicated when a requested service is not available or that a host or router could not be reached.[2] ICMP differs from transport protocols such as TCP and UDP in that it is not typically used to exchange data between systems, nor is it regularly employed by end-user network applications (with the exception of some diagnostic tools like ping and traceroute).

ICMP for IPv4 is defined in RFC 792. A separate ICMPv6, defined by RFC 4443, is used with IPv6.

Technical details[edit]

ICMP is part of the Internet protocol suite as defined in RFC 792. ICMP messages are typically used for diagnostic or control purposes or generated in response to errors in IP operations (as specified in RFC 1122). ICMP errors are directed to the source IP address of the originating packet.[2]

For example, every device (such as an intermediate router) forwarding an IP datagram first decrements the time to live (TTL) field in the IP header by one. If the resulting TTL is 0, the packet is discarded and an ICMP time exceeded in transit message is sent to the datagram’s source address.

Many commonly used network utilities are based on ICMP messages. The traceroute command can be implemented by transmitting IP datagrams with specially set IP TTL header fields, and looking for ICMP time exceeded in transit and Destination unreachable messages generated in response. The related ping utility is implemented using the ICMP echo request and echo reply messages.

ICMP uses the basic support of IP as if it were a higher-level protocol, however, ICMP is actually an integral part of IP. Although ICMP messages are contained within standard IP packets, ICMP messages are usually processed as a special case, distinguished from normal IP processing. In many cases, it is necessary to inspect the contents of the ICMP message and deliver the appropriate error message to the application responsible for transmitting the IP packet that prompted the ICMP message to be sent.

ICMP is a network-layer protocol, this makes it layer 3 protocol by the 7 layer OSI model. Based on the 4 layer TCP/IP model, ICMP is an internet-layer protocol, which makes it layer 2 protocol (internet standard RFC 1122 TCP/IP model with 4 layers) or layer 3 protocol based on modern 5 layer TCP/IP protocol definitions (by Kozierok, Comer, Tanenbaum, Forouzan, Kurose, Stallings).[citation needed] Forouzan and Kurose use network-layer instead of internet-layer in their TCP/IP model definition. These differences between models often lead to pointless and endless debates.[according to whom?]

There is no TCP or UDP port number associated with ICMP packets as these numbers are associated with the transport layer above.[3]

Datagram structure[edit]

The ICMP packet is encapsulated in an IPv4 packet.[2] The packet consists of header and data sections.

[edit]

The ICMP header starts after the IPv4 header and is identified by IP protocol number ‘1’.[4] All ICMP packets have an 8-byte header and variable-sized data section. The first 4 bytes of the header have fixed format, while the last 4 bytes depend on the type/code of that ICMP packet.[2]

ICMP header format

Offsets Octet 0 1 2 3
Octet Bit 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
0 0 Type Code Checksum
4 32 Rest of header
Type
ICMP type, see § Control messages.
Code
ICMP subtype, see § Control messages.
Checksum
Internet checksum (RFC 1071) for error checking, calculated from the ICMP header and data with value 0 substituted for this field.
Rest of header
Four-byte field, contents vary based on the ICMP type and code.

Data[edit]

ICMP error messages contain a data section that includes a copy of the entire IPv4 header, plus at least the first eight bytes of data from the IPv4 packet that caused the error message. The length of ICMP error messages should not exceed 576 bytes.[5] This data is used by the host to match the message to the appropriate process. If a higher level protocol uses port numbers, they are assumed to be in the first eight bytes of the original datagram’s data.[6]

The variable size of the ICMP packet data section has been exploited. In the «Ping of death», large or fragmented ICMP packets are used for denial-of-service attacks. ICMP data can also be used to create covert channels for communication. These channels are known as ICMP tunnels.

Control messages[edit]

Control messages are identified by the value in the type field. The code field gives additional context information for the message. Some control messages have been deprecated since the protocol was first introduced.

Notable control messages[7][8]

Type Code Status Description
0 – Echo Reply[6]: 14  0 Echo reply (used to ping)
1 and 2 unassigned Reserved
3 – Destination Unreachable[6]: 4 [9] 0 Destination network unreachable
1 Destination host unreachable
2 Destination protocol unreachable
3 Destination port unreachable
4 Fragmentation required, and DF flag set
5 Source route failed
6 Destination network unknown
7 Destination host unknown
8 Source host isolated
9 Network administratively prohibited
10 Host administratively prohibited
11 Network unreachable for ToS
12 Host unreachable for ToS
13 Communication administratively prohibited
14 Host Precedence Violation
15 Precedence cutoff in effect
4 – Source Quench 0 deprecated Source quench (congestion control)
5 – Redirect Message 0 Redirect Datagram for the Network
1 Redirect Datagram for the Host
2 Redirect Datagram for the ToS & network
3 Redirect Datagram for the ToS & host
6 deprecated Alternate Host Address
7 unassigned Reserved
8 – Echo Request 0 Echo request (used to ping)
9 – Router Advertisement 0 Router Advertisement
10 – Router Solicitation 0 Router discovery/selection/solicitation
11 – Time Exceeded[6]: 6  0 TTL expired in transit
1 Fragment reassembly time exceeded
12 – Parameter Problem: Bad IP header 0 Pointer indicates the error
1 Missing a required option
2 Bad length
13 – Timestamp 0 Timestamp
14 – Timestamp Reply 0 Timestamp reply
15 – Information Request 0 deprecated Information Request
16 – Information Reply 0 deprecated Information Reply
17 – Address Mask Request 0 deprecated Address Mask Request
18 – Address Mask Reply 0 deprecated Address Mask Reply
19 reserved Reserved for security
20 through 29 reserved Reserved for robustness experiment
30 – Traceroute 0 deprecated Information Request
31 deprecated Datagram Conversion Error
32 deprecated Mobile Host Redirect
33 deprecated Where-Are-You (originally meant for IPv6)
34 deprecated Here-I-Am (originally meant for IPv6)
35 deprecated Mobile Registration Request
36 deprecated Mobile Registration Reply
37 deprecated Domain Name Request
38 deprecated Domain Name Reply
39 deprecated SKIP Algorithm Discovery Protocol, Simple Key-Management for Internet Protocol
40 Photuris, Security failures
41 Experimental ICMP for experimental mobility protocols such as Seamoby [RFC4065]
42 – Extended Echo Request[10] 0 Request Extended Echo (XPing — see Extended Ping (Xping))
43 – Extended Echo Reply[10] 0 No Error
1 Malformed Query
2 No Such Interface
3 No Such Table Entry
4 Multiple Interfaces Satisfy Query
44 through 252 unassigned Reserved
253 Experimental RFC3692-style Experiment 1 (RFC 4727)
254 Experimental RFC3692-style Experiment 2 (RFC 4727)
255 reserved Reserved

Source quench[edit]

Source Quench requests that the sender decrease the rate of messages sent to a router or host. This message may be generated if a router or host does not have sufficient buffer space to process the request, or may occur if the router or host buffer is approaching its limit.

Data is sent at a very high speed from a host or from several hosts at the same time to a particular router on a network. Although a router has buffering capabilities, the buffering is limited to within a specified range. The router cannot queue any more data than the capacity of the limited buffering space. Thus if the queue gets filled up, incoming data is discarded until the queue is no longer full. But as no acknowledgement mechanism is present in the network layer, the client does not know whether the data has reached the destination successfully. Hence some remedial measures should be taken by the network layer to avoid these kind of situations. These measures are referred to as source quench.

In a source quench mechanism, the router sees that the incoming data rate is much faster than the outgoing data rate, and sends an ICMP message to the clients, informing them that they should slow down their data transfer speeds or wait for a certain amount of time before attempting to send more data. When a client receives this message, it automatically slows down the outgoing data rate or waits for a sufficient amount of time, which enables the router to empty the queue. Thus the source quench ICMP message acts as flow control in the network layer.

Since research suggested that «ICMP Source Quench [was] an ineffective (and unfair) antidote for congestion»,[11] routers’ creation of source quench messages was deprecated in 1995 by RFC 1812. Furthermore, forwarding of and any kind of reaction to (flow control actions) source quench messages was deprecated from 2012 by RFC 6633.

Source quench message[6]: 9 

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 4 Code = 0 Checksum
unused
IP header and first 8 bytes of original datagram’s data

Where:

Type must be set to 4
Code must be set to 0
IP header and additional data is used by the sender to match the reply with the associated request

Redirect[edit]

An example of how an ICMPv4 redirect message works

Redirect requests data packets be sent on an alternative route. ICMP Redirect is a mechanism for routers to convey routing information to hosts. The message informs a host to update its routing information (to send packets on an alternative route). If a host tries to send data through a router (R1) and R1 sends the data on another router (R2) and a direct path from the host to R2 is available (that is, the host and R2 are on the same subnetwork), then R1 will send a redirect message to inform the host that the best route for the destination is via R2. The host should then change its route information and send packets for that destination directly to R2. The router will still send the original datagram to the intended destination.[12] However, if the datagram contains routing information, this message will not be sent even if a better route is available. RFC 1122 states that redirects should only be sent by gateways and should not be sent by Internet hosts.

Redirect message[6]: 11 

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 5 Code Checksum
IP address
IP header and first 8 bytes of original datagram’s data

Where:

Type must be set to 5.
Code specifies the reason for the redirection, and may be one of the following:
Code Description
0 Redirect for Network
1 Redirect for Host
2 Redirect for Type of Service and Network
3 Redirect for Type of Service and Host
IP address is the 32-bit address of the gateway to which the redirection should be sent.
IP header and additional data is included to allow the host to match the reply with the request that caused the redirection reply.

Time exceeded[edit]

Time Exceeded is generated by a gateway to inform the source of a discarded datagram due to the time to live field reaching zero. A time exceeded message may also be sent by a host if it fails to reassemble a fragmented datagram within its time limit.

Time exceeded messages are used by the traceroute utility to identify gateways on the path between two hosts.

Time exceeded message[6]: 5 

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 11 Code Checksum
unused
IP header and first 8 bytes of original datagram’s data

Where:

Type must be set to 11
Code specifies the reason for the time exceeded message, include the following:
Code Description
0 Time-to-live exceeded in transit.
1 Fragment reassembly time exceeded.
IP header and first 64 bits of the original payload are used by the source host to match the time exceeded message to the discarded datagram. For higher-level protocols such as UDP and TCP the 64-bit payload will include the source and destination ports of the discarded packet.

Timestamp[edit]

Timestamp is used for time synchronization. The originating timestamp is set to the time (in milliseconds since midnight) the sender last touched the packet. The receive and transmit timestamps are not used.

Timestamp message[6]: 15 

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 13 Code = 0 Checksum
Identifier Sequence number
Originate timestamp
Receive timestamp
Transmit timestamp

Where:

Type must be set to 13
Code must be set to 0
Identifier and Sequence Number can be used by the client to match the timestamp reply with the timestamp request.
Originate timestamp is the number of milliseconds since midnight Universal Time (UT). If a UT reference is not available the most-significant bit can be set to indicate a non-standard time value.

Timestamp reply[edit]

Timestamp Reply replies to a Timestamp message. It consists of the originating timestamp sent by the sender of the Timestamp as well as a receive timestamp indicating when the Timestamp was received and a transmit timestamp indicating when the Timestamp reply was sent.

Timestamp reply message[6]: 15 

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 14 Code = 0 Checksum
Identifier Sequence number
Originate timestamp
Receive timestamp
Transmit timestamp

Where:

Type must be set to 14
Code must be set to 0
Identifier and Sequence number can be used by the client to match the reply with the request that caused the reply.
Originate timestamp is the time the sender last touched the message before sending it.
Receive timestamp is the time the echoer first touched it on receipt.
Transmit timestamp is the time the echoer last touched the message on sending it.
All timestamps are in units of milliseconds since midnight UT. If the time is not available in milliseconds or cannot be provided with respect to midnight UT then any time can be inserted in a timestamp provided the high order bit of the timestamp is also set to indicate this non-standard value.

The use of Timestamp and Timestamp Reply messages to synchronize the clocks of Internet nodes has largely been replaced by the UDP-based Network Time Protocol and the Precision Time Protocol.[13]

Address mask request[edit]

Address mask request is normally sent by a host to a router in order to obtain an appropriate subnet mask.

Recipients should reply to this message with an Address mask reply message.

Address mask request

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 17 Code = 0 Checksum
Identifier Sequence number
Address mask

Where:

Type must be set to 17
Code must be set to 0
Address mask can be set to 0

ICMP Address Mask Request may be used as a part of reconnaissance attack to gather information on the target network, therefore ICMP Address Mask Reply is disabled by default on Cisco IOS.[14]

Address mask reply[edit]

Address mask reply is used to reply to an address mask request message with an appropriate subnet mask.

Address mask reply

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 18 Code = 0 Checksum
Identifier Sequence number
Address mask

Where:

Type must be set to 18
Code must be set to 0
Address mask should be set to the subnet mask

Destination unreachable[edit]

Destination unreachable is generated by the host or its inbound gateway[6] to inform the client that the destination is unreachable for some reason. Reasons for this message may include: the physical connection to the host does not exist (distance is infinite); the indicated protocol or port is not active; the data must be fragmented but the ‘don’t fragment’ flag is on. Unreachable TCP ports notably respond with TCP RST rather than a destination unreachable type 3 as might be expected. Destination unreachable is never reported for IP multicast transmissions.

Destination unreachable message[6]: 3 

00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Type = 3 Code Checksum
unused Next-hop MTU
IP header and first 8 bytes of original datagram’s data

Where:

Type field (bits 0–7) must be set to 3
Code field (bits 8–15) is used to specify the type of error, and can be any of the following:
Code Description
0 Network unreachable error.
1 Host unreachable error.
2 Protocol unreachable error (the designated transport protocol is not supported).
3 Port unreachable error (the designated protocol is unable to inform the host of the incoming message).
4 The datagram is too big. Packet fragmentation is required but the ‘don’t fragment’ (DF) flag is on.
5 Source route failed error.
6 Destination network unknown error.
7 Destination host unknown error.
8 Source host isolated error.
9 The destination network is administratively prohibited.
10 The destination host is administratively prohibited.
11 The network is unreachable for Type Of Service.
12 The host is unreachable for Type Of Service.
13 Communication administratively prohibited (administrative filtering prevents packet from being forwarded).
14 Host precedence violation (indicates the requested precedence is not permitted for the combination of host or network and port).
15 Precedence cutoff in effect (precedence of datagram is below the level set by the network administrators).
Next-hop MTU field (bits 48–63) contains the MTU of the next-hop network if a code 4 error occurs.[15]
IP header and additional data is included to allow the client to match the reply with the request that caused the destination unreachable reply.

See also[edit]

  • ICMP tunnel
  • ICMP hole punching
  • ICMP Router Discovery Protocol
  • Pathping
  • Path MTU Discovery
  • Smurf attack

References[edit]

  1. ^ F. Baker (June 1995). Baker, F (ed.). Requirements for IP Version 4 Routers. p. 52. RFC 1812.
  2. ^ a b c d Forouzan, Behrouz A. (2007). Data Communications And Networking (Fourth ed.). Boston: McGraw-Hill. pp. 621–630. ISBN 978-0-07-296775-3.
  3. ^ «The OSI Model’s Seven Layers Defined and Functions Explained». Microsoft Support. Retrieved 2014-12-28.
  4. ^ «Protocol Numbers». Internet Assigned Numbers Authority. Retrieved 2011-06-23.
  5. ^ Requirements for IP Version 4 Routers. doi:10.17487/RFC1812. RFC 1812.
  6. ^ a b c d e f g h i j k Postel, J. (September 1981). Internet Control Message Protocol. IETF. doi:10.17487/RFC0792. RFC 792.
  7. ^ «IANA ICMP Parameters». Iana.org. 2012-09-21. Retrieved 2013-01-07.
  8. ^ Kurose, J.F; Ross, K.W. (2006). Computer Networking: A Top-Down Approach. World student series. Addison-Wesley. ISBN 9780321418494.
  9. ^ «Internet Control Message Protocol (ICMP) Parameters». www.iana.org. Retrieved 2023-09-13.
  10. ^ a b PROBE: A Utility for Probing Interfaces. doi:10.17487/RFC8335. RFC 8335.
  11. ^ RFC 6633
  12. ^ «When Are ICMP Redirects Sent?». Cisco Systems. 2008-06-28. Retrieved 2013-08-15.
  13. ^ D.L. Mills (September 1985). Network Time Protocol (NTP). doi:10.17487/RFC0958. RFC 958. It is evolved from the Time Protocol and the ICMP Timestamp message and is a suitable replacement for both.
  14. ^ «Cisco IOS IP Command Reference, Volume 1 of 4: Addressing and Services, Release 12.3 — IP Addressing and Services Commands: ip mask-reply through ip web-cache». Cisco Systems. Archived from the original on 2013-01-02. Retrieved 2013-01-07.
  15. ^ Extended ICMP to Support Multi-Part Messages. doi:10.17487/RFC4884. RFC 4884.

Sources[edit]

RFCs[edit]

  • RFC 792, Internet Control Message Protocol
  • RFC 950, Internet Standard Subnetting Procedure
  • RFC 1016, Something a Host Could Do with Source Quench: The Source Quench Introduced Delay (SQuID)
  • RFC 1122, Requirements for Internet Hosts – Communication Layers
  • RFC 1716, Towards Requirements for IP Routers
  • RFC 1812, Requirements for IP Version 4 Routers
  • RFC 4884, Extended ICMP to Support Multi-Part Messages

External links[edit]

  • IANA ICMP parameters
  • IANA protocol numbers
  • Explanation of ICMP Redirect Behavior at the Wayback Machine (archived 2015-01-10)


4 minute read

Internet Control Message Protocol или просто ICMP описан в RFC 792. Данный протокол определяет набор различных сообщений, целью которых является управление сетью.

ICMP сообщения могут классифицироваться как сообщения об ошибках, а также как сообщения типа “запрос — ответ”.

graph TD
C{ICMP}
C —> D[Error message]
C —> E[Query-Response]

Ниже представлен основной формат пакета ICMP

Структура протокола ICMP

Пакеты ICMP определяются по их типу (Type), однако, большинство типов могут иметь более специфичные типы, они определяются по полю Code. RFC 1700 определяет все основные типы и коды для протокола ICMP.

В следующей таблице перечислены данные поля с их описанием

Тип Код Название
0 0 Echo Reply
3   DESTINATION UNREACHABLE
0 Network Unreachable
1 Host Unreachable
2 Protocol Unreachable
3 Port Unreachable
4 Fragmentation Needed and Don’t Fragment Flag Set
5 Source Route Failed
6 Destination Network Unknown
7 Destination Host Unknown
8 Source Host Isolated
9 Destination Network Administratively Prohibited
10 Destination Host Administratively Prohibited
11 Destination Network Unreachable for Type of Service
12 Destination Host Unreachable for Type of Service
4 0 SOURCE QUENCH (deprecated)
5   REDIRECT
0 Redirect Datagram for the Network (or Subnet)
1 Redirect Datagram for the Host
2 Redirect Datagram for the Network and Type of Service
3 Redirect Datagram for the Host and Type of Service
6 0 ALTERNATE HOST ADDRESS
8 0 ECHO
9 0 ROUTER ADVERTISEMENT
10 0 ROUTER SELECTION
11   TIME EXCEEDED
0 Time to Live Exceeded in Transmit
1 Fragment Reassembly Time Exceeded
12   PARAMETER PROBLEM
0 Pointer Indicates the Error
1 Missing a Required Option
2 Bad Length
13 0 TIMESTAMP
14 0 TIMESTAMP REPLY
15 0 INFORMATION REQUEST (Obsolete)
16 0 INFORMATION REPLY (Obsolete)
17 0 ADDRESS MASK REQUEST (Near-Obsolete)
18 0 ADDRESS MASK REPLY (Near-Obsolete)
30 Traceroute

Данную информацию не следует учить, как и другую представленную в статьях, главное научиться понимать что это и для чего используется, остальное приходит с опытом работы. Тем более, что вся представленная информация общедоступна каждому из нас бесплатно.

Одни из наиболее часто встречающихся примеров ICMP сообщений являются Echo и Reply. По ссылке можно скачать дамп, показывающий выполнение команды ping в сторону адреса 8.8.8.8. Ниже будут представлены вырезки Echo и Reply из данных дампов.

ICMP Request
ICMP Reply

Далеко не все типы пакетов ICMP можно встретить сегодня в современных сетях, но некоторые из них имеют важное значение для функционала маршрутизации, например, редирект — ICMP Type 5.

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

Предположим, что в одной канальной среде с конечным устройством есть два маршрутизатора Router-London и Router-Moscow. Маршрутизатор Router-Moscow является шлюзом по умолчанию для конечного устройства. Конечное устройство отправляет пакет на маршрутизатор Router-Moscow, в свою очередь маршрутизатор Router-Moscow имеет достижимость адреса на который отправил конечный хост через маршрутизатор Router-London.

Получается, что маршрутизатор Router-Moscow должен отправить пакет в тот же самый интерфейс на котором он получил изначальный пакет. Маршрутизатор Router-Moscow отправляет пакет маршрутизатору Router-London, а также отправляет сообщение ICMP Redirect конечному устройству, информируя его о том, что все следующие пакеты он должен отправлять непосредственно через маршрутизатор Router-London (имеется в виду только до сети, куда был отправлен первый пакет, все пакеты до других сетей отправляются также на шлюз по умолчанию)

Практика

Рассмотрим пример с ICMP Redirect на практике. Имеется простая схема с двумя маршрутизаторами в одной канальной среде

Схема ICMP Redirect

Вся адресация представлена на схеме. В качестве простоты эксперимента рассмотрим ситуацию когда клиент будет отправлять пинг на адрес внешнего интерфейса маршрутизатора Router-London, маршрутизатор Router-Moscow является шлюзом для клиента.

На маршрутизаторе Router-Moscow дополнительно настроен статический маршрут до сети 172.17.0.0/24 через адрес внутреннего интерфейса маршрутизатора Router-London.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Router_Moscow# show ip route static
Codes: L - local, C - connected, S - static, R - RIP, M - mobile, B - BGP
       D - EIGRP, EX - EIGRP external, O - OSPF, IA - OSPF inter area 
       N1 - OSPF NSSA external type 1, N2 - OSPF NSSA external type 2
       E1 - OSPF external type 1, E2 - OSPF external type 2
       i - IS-IS, su - IS-IS summary, L1 - IS-IS level-1, L2 - IS-IS level-2
       ia - IS-IS inter area, * - candidate default, U - per-user static route
       o - ODR, P - periodic downloaded static route, H - NHRP, l - LISP
       a - application route
       + - replicated route, % - next hop override, p - overrides from PfR

Gateway of last resort is not set

      172.17.0.0/24 is subnetted, 1 subnets
S        172.17.0.0 [1/0] via 192.168.1.254
Router_Moscow#

Включив дебаг на маршрутизаторе Router-Moscow с помощью команды debug ip icmp, можно заметить как данный маршрутизатор отправляет сообщение ICMP Redirect клиенту.

1
2
3
4
5
Router_Moscow# debug ip icmp 
ICMP packet debugging is on
Router_Moscow#
*Oct  9 11:46:43.504: ICMP: redirect sent to 192.168.1.100 for dest 172.17.0.254, use gw 192.168.1.254
Router_Moscow#

При этом первый пакет на клиенте потеряется из-за того, что маршрутизатор Router-London не будет знать куда отправлять ответ на первый ICMP Request клиента, т.к. его кэш ARP будет пуст и ему придется отправить ARP Request чтобы узнать MAC-адрес клиента.

Потеря первого пакета при пинге клиента

Для того чтобы убедиться в правдивости моих слов предлагаю скачать дампы с двух интерфейсов маршрутизатора Router-London и Router-Moscow и посмотреть весь процесс самим.

Помните: так как все устройства находятся в общей широковещательной среде, то все пакеты отправленные на широковещательный адрес ffff.ffff.ffff будут видны в каждом из дампов.

Дамп с интерфейса gi0/0 маршрутизатора Router-Moscow
Дамп с интерфейса gi0/0 маршрутизатора Router-London

По умолчанию редирект включен на устройствах cisco. Данное поведение можно отключить на интерфейсе, выполнив команду no ip redirects

P.S. вся информация представленная здесь используется исключительно в образовательных целях. Все совпадения с реальными объектами, адресами, именами и т.д. случайна и не несёт цели получить от этого выгоду или причинить кому-либо вред.

Back to top ↑

Протокол Internet Control Message Protocol (ICMP) является важным протоколом сетевого уровня в компьютерных сетях. Он обеспечивает стандартизированный механизм передачи сетевыми устройствами важной информации, такой как подключение и состояние сети. Все устройства, подключенные к сети, включая маршрутизаторы и конечные устройства, могут обрабатывать сообщения ICMP. ICMP адаптирован для работы как с IPv4, так и с IPv6.

Подробнее о компьютерных сетях »

Далее мы обсудим некоторые распространенные варианты использования ICMP.

Отчеты об ошибках

Сообщения об ошибках ICMP информируют о сетевых ошибках – например, о недоступных местах назначения, тайм-аутах или проблемах фрагментации. Сообщения особенно важны для протокола пользовательских дейтаграмм (UDP), который использует модель коммуникации без подключения.

UDP не обеспечивает надежную упорядоченную доставку пакетов. При отправке пакета UDP существует вероятность, что пакет может быть утерян или доставлен с ошибками, например с ошибками контрольной суммы. Если это происходит, получатель отправляет сообщения об ошибках ICMP отправителю, чтобы уведомить его о проблеме.

Диагностика

ICMP можно использовать для диагностики сети. Чаще всего он используется для команд ping и traceroute.

Команда ping проверяет доступность сетевых устройств, отправляя пакеты эхо-запроса ICMP на целевое устройство. Если устройство доступно, оно возвращает эхо-ответ ICMP. Благодаря этому надежно проверяется задержка в сети и обеспечивается доступность устройства.

Команда traceroute отслеживает путь пакетов от источника до места назначения. Для этого команда отправляет сообщения эхо-запроса и эхо-ответа в указанное место назначения.

Эхо-запросы содержат значение времени жизни (TTL), которое уменьшается на единицу при каждом прохождении пакета через маршрутизатор. Когда пакет достигает маршрутизатора с нулевым значением TTL, маршрутизатор отправляет сообщение ICMP обратно источнику.

В сообщении содержится информация о маршруте, пройденном пакетом. С помощью команды Traceroute можно узнать точный путь пакета, чтобы получить представление о производительности сети.

сетевая безопасность;

ICMP можно использовать для обнаружения несанкционированного сетевого трафика и разрешать только законный трафик в сети. Брандмауэры используют ICMP для разрешения или блокировки определенных типов трафика. Сетевые администраторы также используют инструменты мониторинга ICMP для отслеживания состояния и подключения сетевых устройств, а также обнаружения неизвестных устройств.

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

Internet Control Message Protocol (ICMP) is a network layer protocol used to diagnose communication errors by performing an error control mechanism. Since IP does not have an inbuilt mechanism for sending error and control messages. It depends on Internet Control Message Protocol(ICMP) to provide error control. 

ICMP is used for reporting errors and management queries. It is a supporting protocol and is used by network devices like routers for sending error messages and operations information. For example, the requested service is not available or a host or router could not be reached.

Uses of ICMP 

ICMP is used for error reporting if two devices connect over the internet and some error occurs, So, the router sends an ICMP error message to the source informing about the error. For Example, whenever a device sends any message which is large enough for the receiver, in that case, the receiver will drop the message and reply back ICMP message to the source.

Another important use of ICMP protocol is used to perform network diagnosis by making use of traceroute and ping utility. We will discuss them one by one.

Traceroute: Traceroute utility is used to know the route between two devices connected over the internet. It routes the journey from one router to another, and a traceroute is performed to check network issues before data transfer. 

Ping: Ping is a simple kind of traceroute known as the echo-request message, it is used to measure the time taken by data to reach the destination and return to the source, these replies are known as echo-replies messages.

How Does ICMP Work?

ICMP is the primary and important protocol of the IP suite, but ICMP isn’t associated with any transport layer protocol (TCP or UDP) as it doesn’t need to establish a connection with the destination device before sending any message as it is a connectionless protocol.

The working of ICMP is just contrasting with TCP, as TCP is a connection-oriented protocol whereas ICMP is a connectionless protocol. Whenever a connection is established before the message sending, both devices must be ready through a TCP Handshake.

ICMP packets are transmitted in the form of datagrams that contain an IP header with ICMP data. ICMP datagram is similar to a packet, which is an independent data entity. 

ICMP Packet Format

ICMP header comes after IPv4 and IPv6 packet header. 

ICMPv4 Packet Format

ICMPv4 Packet Format

In the ICMP packet format, the first 32 bits of the packet contain three fields:

Type (8-bit): The initial 8-bit of the packet is for message type, it provides a brief description of the message so that receiving network would know what kind of message it is receiving and how to respond to it. Some common message types are as follows:

  • Type 0 – Echo reply
  • Type 3 – Destination unreachable
  • Type 5 – Redirect Message
  • Type 8 – Echo Request
  • Type 11 – Time Exceeded
  • Type 12 – Parameter problem

Code (8-bit): Code is the next 8 bits of the ICMP packet format, this field carries some additional information about the error message and type.

Checksum (16-bit): Last 16 bits are for the checksum field in the ICMP packet header. The checksum is used to check the number of bits of the complete message and enable the ICMP tool to ensure that complete data is delivered.

The next 32 bits of the ICMP Header are Extended Header which has the work of pointing out the problem in IP Message. Byte locations are identified by the pointer which causes the problem message and receiving device looks here for pointing to the problem.

The last part of the ICMP packet is Data or Payload of variable length. The bytes included in IPv4 are 576 bytes and in IPv6, 1280 bytes.

ICMP in DDoS Attacks

In Distributed DOS (DDoS) attacks, attackers provide so much extra traffic to the target, so that it cannot provide service to users. There are so many ways through which an attacker executes these attacks, which are described below.

Ping of Death Attack

Whenever an attacker sends a ping, whose size is greater than the maximum allowable size, oversized packets are broken into smaller parts. When the sender re-assembles it, the size exceeds the limit which causes a buffer overflow and makes the machine freeze. This is simply called a Ping of Death Attack. Newer devices have protection from this attack, but older devices did not have protection from this attack.

ICMP Flood Attack

Whenever the sender sends so many pings that the device on whom the target is done is unable to handle the echo request. This type of attack is called an ICMP Flood Attack. This attack is also called a ping flood attack. It stops the target computer’s resources and causes a denial of service for the target computer.

Smurf Attack

Smurf Attack is a type of attack in which the attacker sends an ICMP packet with a spoofed source IP address. These type of attacks generally works on older devices like the ping of death attack.

Types of ICMP Messages

Type Code        Description
0 – Echo Reply 0 Echo reply
3 – Destination Unreachable 0 Destination network unreachable
1 Destination host unreachable
2 Destination protocol unreachable
3 Destination port unreachable
4 Fragmentation is needed and the DF flag set
5 Source route failed
5 – Redirect Message 0 Redirect the datagram for the network
1 Redirect datagram for the host
2 Redirect the datagram for the Type of Service and Network
3 Redirect datagram for the Service and Host
8 – Echo Request 0 Echo request
9 – Router Advertisement 0 Use to discover the addresses of operational routers
10 – Router Solicitation 0
11 – Time Exceeded 0 Time to live exceeded in transit
1 Fragment reassembly time exceeded.
12 – Parameter Problem 0 The pointer indicates an error.
1 Missing required option
2 Bad length
13 – Timestamp 0 Used for time synchronization
14 – Timestamp Reply 0 Reply to Timestamp message

Source Quench Message

A source quench message is a request to decrease the traffic rate for messages sent to the host destination) or we can say when receiving host detects that the rate of sending packets (traffic rate) to it is too fast it sends the source quench message to the source to slow the pace down so that no packet can be lost. 

Source Quench Message

Source Quench Message

ICMP will take the source IP from the discarded packet and inform the source by sending a source quench message. The source will reduce the speed of transmission so that router will be free from congestion.  

Source Quench Message with Reduced Speed

Source Quench Message with Reduced Speed

When the congestion router is far away from the source the ICMP will send a hop-by-hop source quench message so that every router will reduce the speed of transmission.

Parameter Problem

Whenever packets come to the router then the calculated header checksum should be equal to the received header checksum then only the packet is accepted by the router. 

Parameter Problem

Parameter Problem

If there is a mismatch packet will be dropped by the router. 

ICMP will take the source IP from the discarded packet and inform the source by sending a parameter problem message. 

Time Exceeded Message

Time Exceeded Message

Time Exceeded Message

When some fragments are lost in a network then the holding fragment by the router will be dropped then ICMP will take the source IP from the discarded packet and informs the source, of discarded datagram due to the time to live field reaching zero, by sending the time exceeded message.  

Destination Un-reachable

The destination is unreachable and is generated by the host or its inbound gateway to inform the client that the destination is unreachable for some reason. 

Destination Un-reachable

Destination Un-reachable

There is no necessary condition that only the router gives the ICMP error message time the destination host sends an ICMP error message when any type of failure (link failure, hardware failure, port failure, etc) happens in the network. 

Redirection Message

Redirect requests data packets are sent on an alternate route. The message informs a host to update its routing information (to send packets on an alternate route). 

Example: If the host tries to send data through a router R1 and R1 sends data on a router R2 and there is a direct way from the host to R2. Then R1 will send a redirect message to inform the host that there is the best way to the destination directly through R2 available. The host then sends data packets for the destination directly to R2. 
The router R2 will send the original datagram to the intended destination. 
But if the datagram contains routing information then this message will not be sent even if a better route is available as redirects should only be sent by gateways and should not be sent by Internet hosts. 

Redirection Message

Redirection Message

Whenever a packet is forwarded in the wrong direction later it is re-directed in a current direction then ICMP will send a re-directed message.

For more, you can refer to Types of ICMP (Internet Control Message Protocol) Messages.

FAQs

1. What is ICMP used for?

Internet Control Message Protocol (ICMP) is used for error reporting. Error Reporting by ICMP works by sending messages to the sender from the receiver in the case when data is not received.

2. Is ICMP the same as ping?

ICMP and ping are two different things, but they are somehow related. ICMP is a protocol that manages the messages between the devices and Ping is produced using ICMP.

3. How does ICMP ping work?

ICMP ping is a way to check whether there is a connection established between two devices on the internet. We can check packet loss or any delay that happens within the network with the help of ICMP ping.

Протокол ICMP (Internet Control Message Protocol) — протокол межсетевых управляющих сообщений. 

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

Информация о возникающих ошибках в сети передается по протоколу ICMP. А также протокол ICMP может использоваться для диагностики работы в сети даже, когда в ней не возникают ошибки. Так как IP предоставляет сервис без гарантии доставки, то сообщение об ошибках ICMP не обязаны обрабатываться ни протоколом ICMP ни протоколом IP.  

Формат заголовка ICMP

Рассмотрим формат пакета ICMP. Первое поле в заголовке тип сообщения. Оно говорит о том, что произошло в сети, какая ошибка или какое действие по диагностике пытаются выполнить.

Формат заголовка ICMP

Второе поле -код сообщения. В нем подробно описывается тип ошибки, её причина или диагностическое действие. Дальше идёт контрольная сумма, которая используется для проверки правильности доставки. Следующие 4 байта, служебная информация, которая зависит от типа и кода сообщения. В поле данных ICMP, как правило включается фрагмент пакета при передачи которого произошла ошибка. 

Типы ICMP — сообщений

Самое важно в пакете ICMP это тип сообщений. Именно тип, говорит о том, что произошло в сети. Есть 2 вида ICMP сообщений. Первый вид это запрос-ответ.

Типы ICMP - сообщений

  • Например, тип 0 и тип 8 это эхо-ответ и эхо-запрос, которые используются для проверки доступности компьютера в сети. 
  • Тип 13 и 14 запрос и ответ отметки времени. Эти запросы используются для проверки быстродействия сети. Другой вид это сообщение без запроса. 
  • Тип 3 это сообщение об ошибке узел назначения недостижим. 
  • Тип 5 сообщение о новом маршруте, который позволяет быстрее попасть к необходимой сети. 
  • Тип 9 сообщение о маршрутизаторе. Маршрутизаторы в сети периодически рассылают такие сообщения, чтобы компьютеры, которые находятся в сети могли узнать, какие есть маршрутизаторы. 
  • Тип 10 запрос сообщения о маршрутизаторе, если компьютер только что подключился к сети, он может не дожидаться периодического сообщения от маршрутизаторов, отправить такой запрос и маршрутизатор сразу отправит ответ о себе. 
  • Сообщение с типом 11 используется если маршрутизатор отбросил пакет время жизни которого истекло, как правило такая ситуация возникает, если в сети появилась петля.
  • Сообщение с типом 12 — проблемы с параметрами, говорит о том, что в заголовке IP какая-то ошибка и маршрутизатор не может отправить такой пакет. 

Коды ICMP — сообщений 

Следующее поле в заголовке ICMP это код сообщения. Ниже представлено несколько возможных кодов для типа сообщения 3 — узел назначения недостижим. Какие могут быть причины? Причины перечислены ниже на картинке. 

Коды ICMP - сообщений

Применение ICMP

Большая часть пакетов ICMP формируется и отправляется автоматически сетевым оборудованиям. Но некоторые типы сообщений формируются утилитами, которые применяются для диагностики сети. Рассмотрим утилиты ping и traceroute (в Windows tracert)

Утилита ping

Утилита ping используется, чтобы проверить доступность компьютера в сети. Возможно подключиться к этому компьютеру или нельзя. Ping использует это-протокол ICMP. Компьютер, который хочет проверить доступность другого, отправляет эхо-запрос (тип=8, код=0).

Утилита ping

Компьютер, который получил такой запрос, в ответ отправляет эхо-ответ ICMP с типом 0, если эхо-ответ не пришел, значит установить с компьютером соединение по сети невозможно.

Утилита ping

Пример использования утилиты ping для проверки возможности подключиться к сайту ВКонтакте. По умолчанию утилита ping запускает 4 эхо-запроса и для каждого эхо-запроса получен эхо-ответ. В ответе указывается некоторая диагностическая информация.

ping пример

Утилита traceroute

Утилита traceroute позволяет определить маршрут от отправителя к получателю. Под маршрутом имеется в виду перечень всех маршрутизаторов через которые проходит пакет. 

Пример работы утилиты traceroute ее windows вариант tracert для определения маршрута к сайту ВКонтакте. 

Пример Утилита traceroute

Работа утилиты traceroute 

Как утилита traceroute узнает маршрутизатор? Для этого утилита использует ICMP сообщения время жизни истекло. Чтобы этого достичь, сначала отправляется сообщение у которого время жизни установлено в единицу TTL=1.

Работа утилиты traceroute

Пакет доходит до первого маршрутизатора, маршрутизатор уменьшает время жизни TTL=0 и маршрутизатор отбрасывает пакет.

Работа утилиты traceroute

И генерирует сообщение об ошибке ICMP с типом 11, код 0 время жизни истекло. Утилита traceroute из заголовка IP пакета в которого вложен ICMP извлекает IP-адрес маршрутизатора.

Работа утилиты traceroute

На следующем этапе отправляется пакет с временем жизни равным двум TTL=2. 

Работа утилиты traceroute

На первом маршрутизаторе время жизни уменьшается до единицы и пакет переходит на второй маршрутизатор.

Работа утилиты traceroute

Второй маршрутизатор снова уменьшает время на 1, время жизни становится нулем. Пакет отбрасывается и уже второй маршрутизатор отправляет сообщение время жизни истекло. Утилита traceroute извлекает адрес второго маршрутизатора из IP заголовка этого сообщения. 

Работа утилиты traceroute

И так происходит до тех пор пока пакет не дойдет до узла назначения. 

Заключение

Рассмотрели протокол ICMP протокол межсетевых управляющих сообщений. Протокол ICMP используется для сообщения об ошибках, которые происходят в сети  и для тестирования работоспособности сети. 

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Протокол ошибок фсс 508
  • Протокол ошибок соно
  • Протестировать андроид на ошибки
  • Протокол об административном нарушении ошибки
  • Протестировать айфон на ошибки

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии