| 1 |
''' |
| 2 |
icmplib |
| 3 |
~~~~~~~ |
| 4 |
|
| 5 |
Easily forge ICMP packets and make your own ping and traceroute. |
| 6 |
|
| 7 |
https://github.com/ValentinBELYN/icmplib |
| 8 |
|
| 9 |
:copyright: Copyright 2017-2023 Valentin BELYN. |
| 10 |
:license: GNU LGPLv3, see the LICENSE for details. |
| 11 |
|
| 12 |
~~~~~~~ |
| 13 |
|
| 14 |
This program is free software: you can redistribute it and/or |
| 15 |
modify it under the terms of the GNU Lesser General Public License |
| 16 |
as published by the Free Software Foundation, either version 3 of |
| 17 |
the License, or (at your option) any later version. |
| 18 |
|
| 19 |
This program is distributed in the hope that it will be useful, |
| 20 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 21 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 22 |
GNU Lesser General Public License for more details. |
| 23 |
|
| 24 |
You should have received a copy of the GNU Lesser General Public |
| 25 |
License along with this program. If not, see |
| 26 |
<https://www.gnu.org/licenses/>. |
| 27 |
''' |
| 28 |
|
| 29 |
import socket, asyncio |
| 30 |
from struct import pack, unpack |
| 31 |
from time import time |
| 32 |
|
| 33 |
from .models import ICMPReply |
| 34 |
from .exceptions import * |
| 35 |
from .utils import PLATFORM_LINUX, PLATFORM_MACOS, PLATFORM_WINDOWS |
| 36 |
|
| 37 |
|
| 38 |
class ICMPSocket: |
| 39 |
''' |
| 40 |
Base class for ICMP sockets. |
| 41 |
|
| 42 |
:type address: str, optional |
| 43 |
:param address: The IP address from which you want to listen and |
| 44 |
send packets. By default, the socket listens on all interfaces. |
| 45 |
|
| 46 |
:type privileged: bool, optional |
| 47 |
:param privileged: When this option is enabled, the socket fully |
| 48 |
manages the exchanges and the structure of the ICMP packets. |
| 49 |
Disable this option if you want to instantiate and use the |
| 50 |
socket without root privileges and let the kernel handle ICMP |
| 51 |
headers. Default to True. |
| 52 |
Only available on Unix systems. Ignored on Windows. |
| 53 |
|
| 54 |
:raises SocketPermissionError: If the privileges are insufficient to |
| 55 |
create the socket. |
| 56 |
:raises SocketAddressError: If the requested address cannot be |
| 57 |
assigned to the socket. |
| 58 |
:raises ICMPSocketError: If another error occurs while creating the |
| 59 |
socket. |
| 60 |
|
| 61 |
''' |
| 62 |
__slots__ = '_sock', '_address', '_privileged' |
| 63 |
|
| 64 |
_IP_VERSION = -1 |
| 65 |
_ICMP_HEADER_OFFSET = -1 |
| 66 |
_ICMP_HEADER_REAL_OFFSET = -1 |
| 67 |
|
| 68 |
_ICMP_CODE_OFFSET = _ICMP_HEADER_OFFSET + 1 |
| 69 |
_ICMP_CHECKSUM_OFFSET = _ICMP_HEADER_OFFSET + 2 |
| 70 |
_ICMP_ID_OFFSET = _ICMP_HEADER_OFFSET + 4 |
| 71 |
_ICMP_SEQUENCE_OFFSET = _ICMP_HEADER_OFFSET + 6 |
| 72 |
_ICMP_PAYLOAD_OFFSET = _ICMP_HEADER_OFFSET + 8 |
| 73 |
|
| 74 |
_ICMP_ECHO_REQUEST = -1 |
| 75 |
_ICMP_ECHO_REPLY = -1 |
| 76 |
|
| 77 |
def __init__(self, address=None, privileged=True): |
| 78 |
self._sock = None |
| 79 |
self._address = address |
| 80 |
|
| 81 |
# The Linux kernel allows unprivileged users to use datagram |
| 82 |
# sockets (SOCK_DGRAM) to send ICMP requests. This feature is |
| 83 |
# now supported by the majority of Unix systems. |
| 84 |
# Windows is not compatible. |
| 85 |
self._privileged = privileged or PLATFORM_WINDOWS |
| 86 |
|
| 87 |
try: |
| 88 |
self._sock = self._create_socket( |
| 89 |
socket.SOCK_RAW if self._privileged else |
| 90 |
socket.SOCK_DGRAM) |
| 91 |
|
| 92 |
if address: |
| 93 |
self._sock.bind((address, 0)) |
| 94 |
|
| 95 |
except OSError as err: |
| 96 |
if err.errno in (1, 13, 10013): |
| 97 |
raise SocketPermissionError(privileged) |
| 98 |
|
| 99 |
if err.errno in (-9, 49, 99, 10049, 11001): |
| 100 |
raise SocketAddressError(address) |
| 101 |
|
| 102 |
raise ICMPSocketError(str(err)) |
| 103 |
|
| 104 |
def __enter__(self): |
| 105 |
''' |
| 106 |
Return this object. |
| 107 |
|
| 108 |
''' |
| 109 |
return self |
| 110 |
|
| 111 |
def __exit__(self, type, value, traceback): |
| 112 |
''' |
| 113 |
Call the `close` method. |
| 114 |
|
| 115 |
''' |
| 116 |
self.close() |
| 117 |
|
| 118 |
def __del__(self): |
| 119 |
''' |
| 120 |
Call the `close` method. |
| 121 |
|
| 122 |
''' |
| 123 |
self.close() |
| 124 |
|
| 125 |
def _create_socket(self, type): |
| 126 |
''' |
| 127 |
Create and return a new socket. Must be overridden. |
| 128 |
|
| 129 |
''' |
| 130 |
raise NotImplementedError |
| 131 |
|
| 132 |
def _set_ttl(self, ttl): |
| 133 |
''' |
| 134 |
Set the time to live of every IP packet originating from this |
| 135 |
socket. Must be overridden. |
| 136 |
|
| 137 |
''' |
| 138 |
raise NotImplementedError |
| 139 |
|
| 140 |
def _set_traffic_class(self, traffic_class): |
| 141 |
''' |
| 142 |
Set the DS Field (formerly TOS) or the Traffic Class field of |
| 143 |
every IP packet originating from this socket. Must be |
| 144 |
overridden. |
| 145 |
|
| 146 |
''' |
| 147 |
raise NotImplementedError |
| 148 |
|
| 149 |
def _checksum(self, data): |
| 150 |
''' |
| 151 |
Compute the checksum of an ICMP packet. Checksums are used to |
| 152 |
verify the integrity of packets. |
| 153 |
|
| 154 |
''' |
| 155 |
sum = 0 |
| 156 |
data += b'\x00' |
| 157 |
|
| 158 |
for i in range(0, len(data) - 1, 2): |
| 159 |
sum += (data[i] << 8) + data[i + 1] |
| 160 |
sum = (sum & 0xffff) + (sum >> 16) |
| 161 |
|
| 162 |
sum = ~sum & 0xffff |
| 163 |
|
| 164 |
return sum |
| 165 |
|
| 166 |
def _create_packet(self, id, sequence, payload): |
| 167 |
''' |
| 168 |
Build an ICMP packet from an identifier, a sequence number and |
| 169 |
a payload. |
| 170 |
|
| 171 |
This method returns the newly created ICMP header concatenated |
| 172 |
to the payload passed in parameters. |
| 173 |
|
| 174 |
''' |
| 175 |
checksum = 0 |
| 176 |
|
| 177 |
# Temporary ICMP header to compute the checksum |
| 178 |
header = pack('!2B3H', self._ICMP_ECHO_REQUEST, 0, checksum, |
| 179 |
id, sequence) |
| 180 |
|
| 181 |
checksum = self._checksum(header + payload) |
| 182 |
|
| 183 |
# Definitive ICMP header |
| 184 |
header = pack('!2B3H', self._ICMP_ECHO_REQUEST, 0, checksum, |
| 185 |
id, sequence) |
| 186 |
|
| 187 |
return header + payload |
| 188 |
|
| 189 |
def _parse_reply(self, packet, source, current_time): |
| 190 |
''' |
| 191 |
Parse an ICMP reply from bytes. |
| 192 |
|
| 193 |
This method returns an `ICMPReply` object or `None` if the reply |
| 194 |
cannot be parsed. |
| 195 |
|
| 196 |
''' |
| 197 |
# On Linux, the IP header is missing when a datagram socket is |
| 198 |
# used (SOCK_DGRAM). To keep the same behavior on all operating |
| 199 |
# systems including macOS which has this header, we add a |
| 200 |
# padding of the size of the missing IP header. |
| 201 |
if not self._privileged and PLATFORM_LINUX: |
| 202 |
packet = b'\x00' * self._ICMP_HEADER_OFFSET + packet |
| 203 |
|
| 204 |
bytes_received = len(packet) - self._ICMP_HEADER_OFFSET |
| 205 |
|
| 206 |
if len(packet) < self._ICMP_CHECKSUM_OFFSET: |
| 207 |
return None |
| 208 |
|
| 209 |
type, code = unpack('!2B', packet[ |
| 210 |
self._ICMP_HEADER_OFFSET: |
| 211 |
self._ICMP_CHECKSUM_OFFSET]) |
| 212 |
|
| 213 |
if type != self._ICMP_ECHO_REPLY: |
| 214 |
packet = packet[ |
| 215 |
self._ICMP_PAYLOAD_OFFSET |
| 216 |
- self._ICMP_HEADER_OFFSET |
| 217 |
+ self._ICMP_HEADER_REAL_OFFSET:] |
| 218 |
|
| 219 |
if len(packet) < self._ICMP_PAYLOAD_OFFSET: |
| 220 |
return None |
| 221 |
|
| 222 |
id, sequence = unpack('!2H', packet[ |
| 223 |
self._ICMP_ID_OFFSET: |
| 224 |
self._ICMP_PAYLOAD_OFFSET]) |
| 225 |
|
| 226 |
return ICMPReply( |
| 227 |
source=source, |
| 228 |
family=self._IP_VERSION, |
| 229 |
id=id, |
| 230 |
sequence=sequence, |
| 231 |
type=type, |
| 232 |
code=code, |
| 233 |
bytes_received=bytes_received, |
| 234 |
time=current_time) |
| 235 |
|
| 236 |
def send(self, request): |
| 237 |
''' |
| 238 |
Send an ICMP request message over the network to a remote host. |
| 239 |
|
| 240 |
This operation is non-blocking. Use the `receive` method to get |
| 241 |
the reply. |
| 242 |
|
| 243 |
:type request: ICMPRequest |
| 244 |
:param request: The ICMP request you have created. If the socket |
| 245 |
is used in non-privileged mode on a Linux system, the |
| 246 |
identifier defined in the request will be replaced by the |
| 247 |
kernel. |
| 248 |
|
| 249 |
:raises SocketBroadcastError: If a broadcast address is used and |
| 250 |
the corresponding option is not enabled on the socket |
| 251 |
(ICMPv4 only). |
| 252 |
:raises SocketUnavailableError: If the socket is closed. |
| 253 |
:raises ICMPSocketError: If another error occurs while sending. |
| 254 |
|
| 255 |
''' |
| 256 |
if not self._sock: |
| 257 |
raise SocketUnavailableError |
| 258 |
|
| 259 |
try: |
| 260 |
sock_destination = socket.getaddrinfo( |
| 261 |
host=request.destination, |
| 262 |
port=None, |
| 263 |
family=self._sock.family, |
| 264 |
type=self._sock.type)[0][4] |
| 265 |
|
| 266 |
packet = self._create_packet( |
| 267 |
id=request.id, |
| 268 |
sequence=request.sequence, |
| 269 |
payload=request.payload) |
| 270 |
|
| 271 |
self._set_ttl(request.ttl) |
| 272 |
self._set_traffic_class(request.traffic_class) |
| 273 |
|
| 274 |
request._time = time() |
| 275 |
self._sock.sendto(packet, sock_destination) |
| 276 |
|
| 277 |
# On Linux, the ICMP request identifier is replaced by the |
| 278 |
# kernel with a random port number when a datagram socket is |
| 279 |
# used (SOCK_DGRAM). So, we update the request created by |
| 280 |
# the user to take this new identifier into account. |
| 281 |
if not self._privileged and PLATFORM_LINUX: |
| 282 |
request._id = self._sock.getsockname()[1] |
| 283 |
|
| 284 |
except PermissionError: |
| 285 |
raise SocketBroadcastError |
| 286 |
|
| 287 |
except OSError as err: |
| 288 |
raise ICMPSocketError(str(err)) |
| 289 |
|
| 290 |
def receive(self, request=None, timeout=2): |
| 291 |
''' |
| 292 |
Receive an ICMP reply message from the socket. |
| 293 |
|
| 294 |
This method can be called multiple times if you expect several |
| 295 |
responses as with a broadcast address. |
| 296 |
|
| 297 |
:type request: ICMPRequest, optional |
| 298 |
:param request: The ICMP request to use to match the response. |
| 299 |
By default, all ICMP packets arriving on the socket are |
| 300 |
returned. |
| 301 |
|
| 302 |
:type timeout: int or float, optional |
| 303 |
:param timeout: The maximum waiting time for receiving the |
| 304 |
response in seconds. Default to 2. |
| 305 |
|
| 306 |
:rtype: ICMPReply |
| 307 |
:returns: An `ICMPReply` object representing the response of the |
| 308 |
desired destination or an upstream gateway. See the |
| 309 |
`ICMPReply` class for details. |
| 310 |
|
| 311 |
:raises TimeoutExceeded: If no response is received before the |
| 312 |
timeout specified in parameters. |
| 313 |
:raises SocketUnavailableError: If the socket is closed. |
| 314 |
:raises ICMPSocketError: If another error occurs while receiving. |
| 315 |
|
| 316 |
''' |
| 317 |
if not self._sock: |
| 318 |
raise SocketUnavailableError |
| 319 |
|
| 320 |
self._sock.settimeout(timeout) |
| 321 |
time_limit = time() + timeout |
| 322 |
|
| 323 |
try: |
| 324 |
while True: |
| 325 |
response = self._sock.recvfrom(1024) |
| 326 |
current_time = time() |
| 327 |
|
| 328 |
packet = response[0] |
| 329 |
source = response[1][0] |
| 330 |
|
| 331 |
if current_time > time_limit: |
| 332 |
raise socket.timeout |
| 333 |
|
| 334 |
reply = self._parse_reply( |
| 335 |
packet=packet, |
| 336 |
source=source, |
| 337 |
current_time=current_time) |
| 338 |
|
| 339 |
if (reply and not request or |
| 340 |
reply and request.id == reply.id and |
| 341 |
request.sequence == reply.sequence): |
| 342 |
return reply |
| 343 |
|
| 344 |
except socket.timeout: |
| 345 |
raise TimeoutExceeded(timeout) |
| 346 |
|
| 347 |
except OSError as err: |
| 348 |
raise ICMPSocketError(str(err)) |
| 349 |
|
| 350 |
def close(self): |
| 351 |
''' |
| 352 |
Close the socket. It cannot be used after this call. |
| 353 |
|
| 354 |
''' |
| 355 |
if self._sock: |
| 356 |
self._sock.close() |
| 357 |
self._sock = None |
| 358 |
|
| 359 |
@property |
| 360 |
def sock(self): |
| 361 |
''' |
| 362 |
Return the underlying socket (`socket.socket` object) or `None` |
| 363 |
if the socket is closed. |
| 364 |
|
| 365 |
This property should only be used if the feature you want is not |
| 366 |
yet implemented. Some changes made to this socket may cause |
| 367 |
unexpected behavior or be incompatible with later versions of |
| 368 |
the library. |
| 369 |
|
| 370 |
Prefer to use the other methods and properties defined within |
| 371 |
this class if possible. |
| 372 |
|
| 373 |
''' |
| 374 |
return self._sock |
| 375 |
|
| 376 |
@property |
| 377 |
def blocking(self): |
| 378 |
''' |
| 379 |
Indicate whether the socket is in blocking mode. |
| 380 |
Return a `boolean`. |
| 381 |
|
| 382 |
''' |
| 383 |
return self._sock.getblocking() |
| 384 |
|
| 385 |
@blocking.setter |
| 386 |
def blocking(self, enable): |
| 387 |
return self._sock.setblocking(enable) |
| 388 |
|
| 389 |
@property |
| 390 |
def address(self): |
| 391 |
''' |
| 392 |
The IP address from which the socket listens and sends packets. |
| 393 |
Return `None` if the socket listens on all interfaces. |
| 394 |
|
| 395 |
''' |
| 396 |
return self._address |
| 397 |
|
| 398 |
@property |
| 399 |
def is_privileged(self): |
| 400 |
''' |
| 401 |
Indicate whether the socket is running in privileged mode. |
| 402 |
Return a `boolean`. |
| 403 |
|
| 404 |
''' |
| 405 |
return self._privileged |
| 406 |
|
| 407 |
@property |
| 408 |
def is_closed(self): |
| 409 |
''' |
| 410 |
Indicate whether the socket is closed. |
| 411 |
Return a `boolean`. |
| 412 |
|
| 413 |
''' |
| 414 |
return self._sock is None |
| 415 |
|
| 416 |
|
| 417 |
# Echo Request and Echo Reply messages RFC 792 |
| 418 |
# |
| 419 |
# 0 1 2 3 |
| 420 |
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 |
| 421 |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| 422 |
# | Type | Code | Checksum | |
| 423 |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| 424 |
# | Identifier | Sequence Number | |
| 425 |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| 426 |
# | Data ... |
| 427 |
# +-+-+-+-+- |
| 428 |
# |
| 429 |
# ICMPv4 Error message RFC 792 |
| 430 |
# |
| 431 |
# 0 1 2 3 |
| 432 |
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 |
| 433 |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| 434 |
# | Type | Code | Checksum | |
| 435 |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| 436 |
# | Unused / Depends on the error | |
| 437 |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| 438 |
# | Internet Header + 64 bits of Original Data Datagram | |
| 439 |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| 440 |
|
| 441 |
|
| 442 |
class ICMPv4Socket(ICMPSocket): |
| 443 |
''' |
| 444 |
Class for sending and receiving ICMPv4 packets. |
| 445 |
|
| 446 |
:type address: str, optional |
| 447 |
:param address: The IP address from which you want to listen and |
| 448 |
send packets. By default, the socket listens on all interfaces. |
| 449 |
|
| 450 |
:type privileged: bool, optional |
| 451 |
:param privileged: When this option is enabled, the socket fully |
| 452 |
manages the exchanges and the structure of the ICMP packets. |
| 453 |
Disable this option if you want to instantiate and use the |
| 454 |
socket without root privileges and let the kernel handle ICMP |
| 455 |
headers. Default to True. |
| 456 |
Only available on Unix systems. Ignored on Windows. |
| 457 |
|
| 458 |
:raises SocketPermissionError: If the privileges are insufficient to |
| 459 |
create the socket. |
| 460 |
:raises SocketAddressError: If the requested address cannot be |
| 461 |
assigned to the socket. |
| 462 |
:raises ICMPSocketError: If another error occurs while creating the |
| 463 |
socket. |
| 464 |
|
| 465 |
''' |
| 466 |
__slots__ = '_sock', '_address', '_privileged' |
| 467 |
|
| 468 |
_IP_VERSION = 4 |
| 469 |
_ICMP_HEADER_OFFSET = 20 |
| 470 |
_ICMP_HEADER_REAL_OFFSET = 20 |
| 471 |
|
| 472 |
_ICMP_CODE_OFFSET = _ICMP_HEADER_OFFSET + 1 |
| 473 |
_ICMP_CHECKSUM_OFFSET = _ICMP_HEADER_OFFSET + 2 |
| 474 |
_ICMP_ID_OFFSET = _ICMP_HEADER_OFFSET + 4 |
| 475 |
_ICMP_SEQUENCE_OFFSET = _ICMP_HEADER_OFFSET + 6 |
| 476 |
_ICMP_PAYLOAD_OFFSET = _ICMP_HEADER_OFFSET + 8 |
| 477 |
|
| 478 |
_ICMP_ECHO_REQUEST = 8 |
| 479 |
_ICMP_ECHO_REPLY = 0 |
| 480 |
|
| 481 |
def _create_socket(self, type): |
| 482 |
''' |
| 483 |
Create and return a new socket. |
| 484 |
|
| 485 |
''' |
| 486 |
return socket.socket( |
| 487 |
family=socket.AF_INET, |
| 488 |
type=type, |
| 489 |
proto=socket.IPPROTO_ICMP) |
| 490 |
|
| 491 |
def _set_ttl(self, ttl): |
| 492 |
''' |
| 493 |
Set the time to live of every IP packet originating from this |
| 494 |
socket. |
| 495 |
|
| 496 |
''' |
| 497 |
self._sock.setsockopt( |
| 498 |
socket.IPPROTO_IP, |
| 499 |
socket.IP_TTL, |
| 500 |
ttl) |
| 501 |
|
| 502 |
def _set_traffic_class(self, traffic_class): |
| 503 |
''' |
| 504 |
Set the DS Field (formerly TOS) of every IP packet originating |
| 505 |
from this socket. |
| 506 |
|
| 507 |
Only available on Unix systems. Ignored on Windows. |
| 508 |
|
| 509 |
''' |
| 510 |
# Not available on Windows |
| 511 |
if PLATFORM_WINDOWS: |
| 512 |
return |
| 513 |
|
| 514 |
self._sock.setsockopt( |
| 515 |
socket.IPPROTO_IP, |
| 516 |
socket.IP_TOS, |
| 517 |
traffic_class) |
| 518 |
|
| 519 |
@property |
| 520 |
def broadcast(self): |
| 521 |
''' |
| 522 |
Indicate whether broadcast support is enabled on the socket. |
| 523 |
Return a `boolean`. |
| 524 |
|
| 525 |
.. note:: |
| 526 |
To enable broadcast support: |
| 527 |
icmp_socket.broadcast = True |
| 528 |
|
| 529 |
''' |
| 530 |
return self._sock.getsockopt( |
| 531 |
socket.SOL_SOCKET, |
| 532 |
socket.SO_BROADCAST) > 0 |
| 533 |
|
| 534 |
@broadcast.setter |
| 535 |
def broadcast(self, enable): |
| 536 |
self._sock.setsockopt( |
| 537 |
socket.SOL_SOCKET, |
| 538 |
socket.SO_BROADCAST, |
| 539 |
enable) |
| 540 |
|
| 541 |
|
| 542 |
# Echo Request and Echo Reply messages RFC 4443 |
| 543 |
# |
| 544 |
# 0 1 2 3 |
| 545 |
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 |
| 546 |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| 547 |
# | Type | Code | Checksum | |
| 548 |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| 549 |
# | Identifier | Sequence Number | |
| 550 |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| 551 |
# | Data ... |
| 552 |
# +-+-+-+-+- |
| 553 |
# |
| 554 |
# ICMPv6 Error message RFC 4443 |
| 555 |
# |
| 556 |
# 0 1 2 3 |
| 557 |
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 |
| 558 |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| 559 |
# | Type | Code | Checksum | |
| 560 |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| 561 |
# | Unused / Depends on the error | |
| 562 |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| 563 |
# | Original packet without exceed the minimum IPv6 MTU | |
| 564 |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| 565 |
|
| 566 |
# Windows IPv6 compatibility |
| 567 |
if PLATFORM_WINDOWS: |
| 568 |
socket.IPPROTO_IPV6 = 41 |
| 569 |
socket.IPPROTO_ICMPV6 = 58 |
| 570 |
|
| 571 |
|
| 572 |
class ICMPv6Socket(ICMPSocket): |
| 573 |
''' |
| 574 |
Class for sending and receiving ICMPv6 packets. |
| 575 |
|
| 576 |
:type address: str, optional |
| 577 |
:param address: The IP address from which you want to listen and |
| 578 |
send packets. By default, the socket listens on all interfaces. |
| 579 |
|
| 580 |
:type privileged: bool, optional |
| 581 |
:param privileged: When this option is enabled, the socket fully |
| 582 |
manages the exchanges and the structure of the ICMP packets. |
| 583 |
Disable this option if you want to instantiate and use the |
| 584 |
socket without root privileges and let the kernel handle ICMP |
| 585 |
headers. Default to True. |
| 586 |
Only available on Unix systems. Ignored on Windows. |
| 587 |
|
| 588 |
:raises SocketPermissionError: If the privileges are insufficient to |
| 589 |
create the socket. |
| 590 |
:raises SocketAddressError: If the requested address cannot be |
| 591 |
assigned to the socket. |
| 592 |
:raises ICMPSocketError: If another error occurs while creating the |
| 593 |
socket. |
| 594 |
|
| 595 |
''' |
| 596 |
__slots__ = '_sock', '_address', '_privileged' |
| 597 |
|
| 598 |
_IP_VERSION = 6 |
| 599 |
_ICMP_HEADER_OFFSET = 0 |
| 600 |
_ICMP_HEADER_REAL_OFFSET = 40 |
| 601 |
|
| 602 |
_ICMP_CODE_OFFSET = _ICMP_HEADER_OFFSET + 1 |
| 603 |
_ICMP_CHECKSUM_OFFSET = _ICMP_HEADER_OFFSET + 2 |
| 604 |
_ICMP_ID_OFFSET = _ICMP_HEADER_OFFSET + 4 |
| 605 |
_ICMP_SEQUENCE_OFFSET = _ICMP_HEADER_OFFSET + 6 |
| 606 |
_ICMP_PAYLOAD_OFFSET = _ICMP_HEADER_OFFSET + 8 |
| 607 |
|
| 608 |
_ICMP_ECHO_REQUEST = 128 |
| 609 |
_ICMP_ECHO_REPLY = 129 |
| 610 |
|
| 611 |
def _create_socket(self, type): |
| 612 |
''' |
| 613 |
Create and return a new socket. |
| 614 |
|
| 615 |
''' |
| 616 |
return socket.socket( |
| 617 |
family=socket.AF_INET6, |
| 618 |
type=type, |
| 619 |
proto=socket.IPPROTO_ICMPV6) |
| 620 |
|
| 621 |
def _set_ttl(self, ttl): |
| 622 |
''' |
| 623 |
Set the time to live of every IP packet originating from this |
| 624 |
socket. |
| 625 |
|
| 626 |
''' |
| 627 |
# Not available on macOS when the privileged param. is disabled |
| 628 |
if PLATFORM_MACOS and not self._privileged: |
| 629 |
return |
| 630 |
|
| 631 |
self._sock.setsockopt( |
| 632 |
socket.IPPROTO_IPV6, |
| 633 |
socket.IPV6_UNICAST_HOPS, |
| 634 |
ttl) |
| 635 |
|
| 636 |
def _set_traffic_class(self, traffic_class): |
| 637 |
''' |
| 638 |
Set the Traffic Class field of every IP packet originating from |
| 639 |
this socket. |
| 640 |
|
| 641 |
Only available on Unix systems. Ignored on Windows. |
| 642 |
|
| 643 |
''' |
| 644 |
# Not available on Windows |
| 645 |
if PLATFORM_WINDOWS: |
| 646 |
return |
| 647 |
|
| 648 |
# Not available on macOS when the privileged param. is disabled |
| 649 |
if PLATFORM_MACOS and not self._privileged: |
| 650 |
return |
| 651 |
|
| 652 |
self._sock.setsockopt( |
| 653 |
socket.IPPROTO_IPV6, |
| 654 |
socket.IPV6_TCLASS, |
| 655 |
traffic_class) |
| 656 |
|
| 657 |
|
| 658 |
class AsyncSocket: |
| 659 |
''' |
| 660 |
A wrapper for ICMP sockets which makes them asynchronous. |
| 661 |
|
| 662 |
:type icmp_sock: ICMPSocket |
| 663 |
:param icmp_sock: An ICMP socket. Once the wrapper is instantiated, |
| 664 |
this socket should no longer be used directly. |
| 665 |
|
| 666 |
''' |
| 667 |
__slots__ = '_icmp_sock' |
| 668 |
|
| 669 |
def __init__(self, icmp_sock): |
| 670 |
self._icmp_sock = icmp_sock |
| 671 |
self._icmp_sock.blocking = False |
| 672 |
|
| 673 |
def __getattr__(self, name): |
| 674 |
''' |
| 675 |
Return the specified attribute of the underlying ICMP socket. |
| 676 |
|
| 677 |
''' |
| 678 |
if not self._icmp_sock: |
| 679 |
raise SocketUnavailableError |
| 680 |
|
| 681 |
return getattr(self._icmp_sock, name) |
| 682 |
|
| 683 |
def __enter__(self): |
| 684 |
''' |
| 685 |
Return this object. |
| 686 |
|
| 687 |
''' |
| 688 |
return self |
| 689 |
|
| 690 |
def __exit__(self, type, value, traceback): |
| 691 |
''' |
| 692 |
Call the `close` method. |
| 693 |
|
| 694 |
''' |
| 695 |
self.close() |
| 696 |
|
| 697 |
def __del__(self): |
| 698 |
''' |
| 699 |
Call the `close` method. |
| 700 |
|
| 701 |
''' |
| 702 |
self.close() |
| 703 |
|
| 704 |
async def receive(self, request=None, timeout=2): |
| 705 |
''' |
| 706 |
Receive an ICMP reply message from the socket. |
| 707 |
|
| 708 |
This method can be called multiple times if you expect several |
| 709 |
responses as with a broadcast address. |
| 710 |
|
| 711 |
This method is non-blocking. |
| 712 |
|
| 713 |
:type request: ICMPRequest, optional |
| 714 |
:param request: The ICMP request to use to match the response. |
| 715 |
By default, all ICMP packets arriving on the socket are |
| 716 |
returned. |
| 717 |
|
| 718 |
:type timeout: int or float, optional |
| 719 |
:param timeout: The maximum waiting time for receiving the |
| 720 |
response in seconds. Default to 2. |
| 721 |
|
| 722 |
:rtype: ICMPReply |
| 723 |
:returns: An `ICMPReply` object representing the response of the |
| 724 |
desired destination or an upstream gateway. See the |
| 725 |
`ICMPReply` class for details. |
| 726 |
Unlike the `reveive` method of synchronous ICMP sockets, the |
| 727 |
returned `ICMPReply` object does not specify the IP address |
| 728 |
of the host that replied to the request message. |
| 729 |
|
| 730 |
:raises TimeoutExceeded: If no response is received before the |
| 731 |
timeout specified in parameters. |
| 732 |
:raises SocketUnavailableError: If the socket is closed. |
| 733 |
:raises ICMPSocketError: If another error occurs while receiving. |
| 734 |
|
| 735 |
''' |
| 736 |
if not self._icmp_sock or not self._icmp_sock._sock: |
| 737 |
raise SocketUnavailableError |
| 738 |
|
| 739 |
loop = asyncio.get_running_loop() |
| 740 |
time_limit = time() + timeout |
| 741 |
remaining_time = timeout |
| 742 |
|
| 743 |
try: |
| 744 |
while True: |
| 745 |
packet = await asyncio.wait_for( |
| 746 |
loop.sock_recv(self._icmp_sock._sock, 1024), |
| 747 |
remaining_time) |
| 748 |
|
| 749 |
current_time = time() |
| 750 |
|
| 751 |
if current_time > time_limit: |
| 752 |
raise asyncio.TimeoutError |
| 753 |
|
| 754 |
reply = self._parse_reply( |
| 755 |
packet=packet, |
| 756 |
source=None, |
| 757 |
current_time=current_time) |
| 758 |
|
| 759 |
if (reply and not request or |
| 760 |
reply and request.id == reply.id and |
| 761 |
request.sequence == reply.sequence): |
| 762 |
return reply |
| 763 |
|
| 764 |
remaining_time = time_limit - current_time |
| 765 |
|
| 766 |
except asyncio.TimeoutError: |
| 767 |
raise TimeoutExceeded(timeout) |
| 768 |
|
| 769 |
except OSError as err: |
| 770 |
raise ICMPSocketError(str(err)) |
| 771 |
|
| 772 |
finally: |
| 773 |
if isinstance(loop, asyncio.SelectorEventLoop): |
| 774 |
loop.remove_reader(self._icmp_sock._sock) |
| 775 |
|
| 776 |
def detach(self): |
| 777 |
''' |
| 778 |
Detach the socket from the wrapper and return it. The wrapper |
| 779 |
cannot be used after this call but the socket can be reused for |
| 780 |
other purposes. |
| 781 |
|
| 782 |
''' |
| 783 |
icmp_sock = self._icmp_sock |
| 784 |
|
| 785 |
if self._icmp_sock: |
| 786 |
self._icmp_sock = None |
| 787 |
|
| 788 |
return icmp_sock |
| 789 |
|
| 790 |
def close(self): |
| 791 |
''' |
| 792 |
Detach the underlying socket from the wrapper and close it. Both |
| 793 |
cannot be used after this call. |
| 794 |
|
| 795 |
''' |
| 796 |
if self._icmp_sock: |
| 797 |
self.detach().close() |
| 798 |
|
| 799 |
@property |
| 800 |
def is_closed(self): |
| 801 |
''' |
| 802 |
Indicate whether the underlying socket is closed or detached |
| 803 |
from this wrapper. Return a `boolean`. |
| 804 |
|
| 805 |
''' |
| 806 |
return self._icmp_sock is None |