forked from alessandromaggio/pythonping
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathicmp.py
More file actions
217 lines (179 loc) · 7.22 KB
/
Copy pathicmp.py
File metadata and controls
217 lines (179 loc) · 7.22 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import os
import socket
import struct
import select
import time
def checksum(data):
"""Creates the ICMP checksum as in RFC 1071
:param data: Data to calculate the checksum ofs
:type data: bytes
:return: Calculated checksum
:rtype: int
Divides the data in 16-bits chunks, then make their 1's complement sum"""
subtotal = 0
for i in range(0, len(data)-1, 2):
subtotal += ((data[i] << 8) + data[i+1]) # Sum 16 bits chunks together
if len(data) % 2: # If length is odd
subtotal += (data[len(data)-1] << 8) # Sum the last byte plus one empty byte of padding
while subtotal >> 16: # Add carry on the right until fits in 16 bits
subtotal = (subtotal & 0xFFFF) + (subtotal >> 16)
check = ~subtotal # Performs the one complement
return ((check << 8) & 0xFF00) | ((check >> 8) & 0x00FF) # Swap bytes
class ICMPType:
"""Represents an ICMP type, as combination of type and code
ICMP Types should inherit from this class so that the code can identify them easily.
This is a static class, not meant to be instantiated"""
def __init__(self):
raise TypeError('ICMPType may not be instantiated')
class Types(ICMPType):
class EchoReply(ICMPType):
type_id = 0
ECHO_REPLY = (type_id, 0,)
class DestinationUnreachable(ICMPType):
type_id = 3
NETWORK_UNREACHABLE = (type_id, 0,)
HOST_UNREACHABLE = (type_id, 1,)
PROTOCOL_UNREACHABLE = (type_id, 2,)
PORT_UNREACHABLE = (type_id, 3,)
FRAGMENTATION_REQUIRED = (type_id, 4,)
SOURCE_ROUTE_FAILED = (type_id, 5,)
NETWORK_UNKNOWN = (type_id, 6,)
HOST_UNKNOWN = (type_id, 7,)
SOURCE_HOST_ISOLATED = (type_id, 8,)
NETWORK_ADMINISTRATIVELY_PROHIBITED = (type_id, 9,)
HOST_ADMINISTRATIVELY_PROHIBITED = (type_id, 10,)
NETWORK_UNREACHABLE_TOS = (type_id, 11,)
HOST_UNREACHABLE_TOS = (type_id, 12,)
COMMUNICATION_ADMINISTRATIVELY_PROHIBITED = (type_id, 13,)
HOST_PRECEDENCE_VIOLATION = (type_id, 14,)
PRECEDENCE_CUTOFF = (type_id, 15,)
class SourceQuench(ICMPType):
type_id = 4
SOURCE_QUENCH = (type_id, 0,)
class Redirect(ICMPType):
type_id = 5
FOR_NETWORK = (type_id, 0,)
FOR_HOST = (type_id, 1,)
FOR_TOS_AND_NETWORK = (type_id, 2,)
FOR_TOS_AND_HOST = (type_id, 3,)
class EchoRequest(ICMPType):
type_id = 8
ECHO_REQUEST = (type_id, 0,)
class RouterAdvertisement(ICMPType):
type_id = 9
ROUTER_ADVERTISEMENT = (type_id, 0,)
class RouterSolicitation(ICMPType):
type_id = 10
ROUTER_SOLICITATION = (type_id, 0)
# Aliases
ROUTER_DISCOVERY = ROUTER_SOLICITATION
ROUTER_SELECTION = ROUTER_SOLICITATION
class TimeExceeded(ICMPType):
type_id = 11
TTL_EXPIRED_IN_TRANSIT = (type_id, 0)
FRAGMENT_REASSEMBLY_TIME_EXCEEDED = (type_id, 1)
class BadIPHeader(ICMPType):
type_id = 12
POINTER_INDICATES_ERROR = (type_id, 0)
MISSING_REQUIRED_OPTION = (type_id, 1)
BAD_LENGTH = (type_id, 2)
class Timestamp(ICMPType):
type_id = 13
TIMESTAMP = (type_id, 0)
class TimestampReply(ICMPType):
type_id = 14
TIMESTAMP_REPLY = (type_id, 0)
class InformationRequest(ICMPType):
type_id = 15
INFORMATION_REQUEST = (type_id, 0)
class InformationReply(ICMPType):
type_id = 16
INFORMATION_REPLY = (type_id, 0)
class AddressMaskRequest(ICMPType):
type_id = 17
ADDRESS_MASK_REQUEST = (type_id, 0)
class AddressMaskReply(ICMPType):
type_id = 18
ADDRESS_MASK_REPLY = (type_id, 0)
class Traceroute(ICMPType):
type_id = 30
INFORMATION_REQUEST = (type_id, 30)
class ICMP:
LEN_TO_PAYLOAD = 41 # Ethernet, IP and ICMP header lengths combined
def __init__(self, message_type=Types.EchoReply, payload=None, identifier=None, sequence_number=1):
"""Creates an ICMP packet
:param message_type: Type of ICMP message to send
:type message_type: Union[ICMPType, (int, int), int]
:param payload: utf8 string or bytes payload
:type payload: Union[str, bytes]
:param identifier: ID of this ICMP packet
:type identifier: int"""
self.message_code = 0
if issubclass(message_type, ICMPType):
self.message_type = message_type.type_id
elif isinstance(message_type, tuple):
self.message_type = message_type[0]
self.message_code = message_type[1]
elif isinstance(message_type, int):
self.message_type = message_type
if payload is None:
payload = bytes('1', 'utf8')
elif isinstance(payload, str):
payload = bytes(payload, 'utf8')
self.payload = payload
if identifier is None:
identifier = os.getpid()
self.id = identifier & 0xFFFF # Prevent identifiers bigger than 16 bits
self.sequence_number = sequence_number
self.received_checksum = None
@property
def packet(self):
"""The raw packet with header, ready to be sent from a socket"""
return self._header(check=self.expected_checksum) + self.payload
def _header(self, check=0):
"""The raw ICMP header
:param check: Checksum value
:type check: int
:return: The packed header
:rtype: bytes"""
# TODO implement sequence number
return struct.pack("bbHHh",
self.message_type,
self.message_code,
check,
self.id,
self.sequence_number)
@property
def is_valid(self):
"""True if the received checksum is valid, otherwise False"""
if self.received_checksum is None:
return True
return self.expected_checksum == self.received_checksum
@property
def expected_checksum(self):
"""The checksum expected for this packet, calculated with checksum field set to 0"""
return checksum(self._header() + self.payload)
@property
def header_length(self):
"""Length of the ICMP header"""
return len(self._header())
@staticmethod
def generate_from_raw(raw):
"""Creates a new ICMP representation from the raw bytes
:param raw: The raw packet including payload
:type raw: bytes
:return: An ICMP instance representing the packet
:rtype: ICMP"""
packet = ICMP()
packet.unpack(raw)
return packet
def unpack(self, raw):
"""Unpacks a raw packet and stores it in this object
:param raw: The raw packet, including payload
:type raw: bytes"""
self.message_type, \
self.message_code, \
self.received_checksum, \
self.id, \
sequence = struct.unpack("bbHHh", raw[20:28])
self.payload = raw[28:]