Coverage for /private/tmp/im/impacket/impacket/ImpactPacket.py : 55%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved. # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # Description: # Network packet codecs basic building blocks. # Low-level packet codecs for various Internet protocols. # # Author: # Javier Burroni (javier) # Bruce Leidl (brl) # Javier Kohen (jkohen)
"""Classes to build network packets programmatically.
Each protocol layer is represented by an object, and these objects are hierarchically structured to form a packet. This list is traversable in both directions: from parent to child and vice versa.
All objects can be turned back into a raw buffer ready to be sent over the wire (see method get_packet). """
self.value = value return repr(self.value)
"""Implement the basic operations utilized to operate on a packet's raw buffer. All the packet classes derive from this one.
The byte, word, long and ip_address getters and setters accept negative indexes, having these the a similar effect as in a regular Python sequence slice. """
"If 'length' is specified the buffer is created with an initial size" else:
"Sets the value of the packet buffer from the string 'data'"
"Returns the packet buffer as a string object"
"Returns the packet buffer as an array"
"Set the packet buffer from an array" # Make a copy to be safe
"Set byte at 'index' to 'value'"
"Return byte at 'index'"
"Set 2-byte word at 'index' to 'value'. See struct module's documentation to understand the meaning of 'order'." self.__bytes[index:] = ary else:
"Return 2-byte word at 'index'. See struct module's documentation to understand the meaning of 'order'." bytes = self.__bytes[index:] else:
"Set 4-byte 'value' at 'index'. See struct module's documentation to understand the meaning of 'order'." else:
"Return 4-byte value at 'index'. See struct module's documentation to understand the meaning of 'order'." else:
"Set 8-byte 'value' at 'index'. See struct module's documentation to understand the meaning of 'order'." self.__bytes[index:] = ary else:
"Return 8-byte value at 'index'. See struct module's documentation to understand the meaning of 'order'." bytes = self.__bytes[index:] else:
"Return 4-byte value at 'index' as an IP string" bytes = self.__bytes[index:] else:
"Set 4-byte value at 'index' from 'ip_string'"
"Set 16-bit checksum at 'index' by calculating checksum of 'data'" self.set_word(index, self.compute_checksum(data))
"Return the one's complement of the one's complement sum of all the 16-bit words in 'anArray'"
"""This method performs two tasks: to allocate enough space to fit the elements at positions index through index+size, and to adjust negative indexes to their absolute equivalent. """
orig_index -= diff
"Protocol Layer Manager for insertion and removal of protocol layers."
"Set 'aHeader' as the child of this protocol layer"
"Set the header 'my_parent' as the parent of this protocol layer"
"Return the child of this protocol layer"
"Return the parent of this protocol layer"
"Break the hierarchy parent/child child/parent"
# Update child raw packet in my body
"Return frame header size"
"Return frame tail size"
"Return frame body size"
"Return frame total size"
"Load the packet body from string. "\ "WARNING: Using this function will break the hierarchy of preceding protocol layer"
self.__TAIL_SIZE=len(aBuffer) self.__tail.set_bytes_from_string(aBuffer)
else:
# leave the array empty else:
"Load the whole packet from a string" \ "WARNING: Using this function will break the hierarchy of preceding protocol layer"
"This is the base class from which all protocol definitions extend."
"Returns all data from children of this header as string"
else:
"""Returns the raw representation of this packet and its children as a string. The output from this method is a packet ready to be transmitted over the wire. """
else:
"Return the size of this header and all of it's children"
"Calculate and set the checksum for this header"
"Pseudo headers can be used to limit over what content will the checksums be calculated." # default implementation returns empty array return array.array('B')
"Properly set the state of this instance to reflect that of the raw packet passed as argument." diff = hdr_len - len(aBuffer) for i in range(0, diff): aBuffer += '\x00'
"Return the size of this header, that is, not counting neither the size of the children nor of the parents." raise RuntimeError("Method %s.get_header_size must be overridden." % self.__class__)
if len(aList): ltmp = [] line = [] count = 0 for byte in aList: if not (count % 2): if (count % 16): ltmp.append(' ') else: ltmp.append(' '*4) ltmp.append(''.join(line)) ltmp.append('\n') line = [] if chr(byte) in Header.packet_printable: line.append(chr(byte)) else: line.append('.') ltmp.append('%.2x' % byte) count += 1 if (count%16): left = 16 - (count%16) ltmp.append(' ' * (4+(left // 2) + (left*2))) ltmp.append(''.join(line)) ltmp.append('\n') return ltmp else: return []
ltmp = self.list_as_hex(self.get_bytes().tolist())
if self.child(): ltmp.append(['\n', str(self.child())])
if len(ltmp)>0: return ''.join(ltmp) else: return ''
"""This packet type can hold raw data. It's normally employed to hold a packet's innermost layer's contents in those cases for which the protocol details are unknown, and there's a copy of a valid packet available.
For instance, if all that's known about a certain protocol is that a UDP packet with its contents set to "HELLO" initiate a new session, creating such packet is as simple as in the following code fragment: packet = UDP() packet.contains('HELLO') """
"""Represents a VLAN header specified in IEEE 802.1Q and 802.1ad. Provides methods for convenient manipulation with header fields."""
"""Returns Tag Protocol Identifier"""
"""Sets Tag Protocol Identifier"""
"""Returns Priority Code Point"""
"""Sets Priority Code Point"""
"""Returns Drop Eligible Indicator"""
"""Sets Drop Eligible Indicator"""
"""Returns VLAN Identifier"""
"""Sets VLAN Identifier"""
priorities = ( 'Best Effort', 'Background', 'Excellent Effort', 'Critical Applications', 'Video, < 100 ms latency and jitter', 'Voice, < 10 ms latency and jitter', 'Internetwork Control', 'Network Control')
pcp = self.get_pcp() return '\n'.join(( '802.1Q header: 0x{0:08X}'.format(self.get_long(0)), 'Priority Code Point: {0} ({1})'.format(pcp, priorities[pcp]), 'Drop Eligible Indicator: {0}'.format(self.get_dei()), 'VLAN Identifier: {0}'.format(self.get_vid())))
"Set ethernet data type field to 'aValue'"
"Return ethernet data type field"
"""Returns an EthernetTag initialized from index-th VLAN tag. The tags are numbered from 0 to self.tag_cnt-1 as they appear in the frame. It is possible to use negative indexes as well."""
"""Sets the index-th VLAN tag to contents of an EthernetTag object. The tags are numbered from 0 to self.tag_cnt-1 as they appear in the frame. It is possible to use negative indexes as well."""
"""Inserts contents of an EthernetTag object before the index-th VLAN tag. Index defaults to 0 (the top of the stack).""" index += self.tag_cnt
"""Removes the index-th VLAN tag and returns it as an EthernetTag object. Index defaults to 0 (the top of the stack)."""
aBuffer += b'\x00'*diff
"Return size of Ethernet header"
try: self.set_ether_type(self.child().ethertype) except: " an Ethernet packet may have a Data() " pass
"Return 48 bit destination ethernet address as a 6 byte array"
"Set destination ethernet address from 6 byte array 'aValue'"
"Return 48 bit source ethernet address as a 6 byte array"
"Set source ethernet address from 6 byte array 'aValue'"
def as_eth_addr(anArray): tmp_list = [x > 15 and '%x'%x or '0%x'%x for x in anArray] return '' + reduce(lambda x, y: x+':'+y, tmp_list)
tmp_str = 'Ether: ' + self.as_eth_addr(self.get_ether_shost()) + ' -> ' tmp_str += self.as_eth_addr(self.get_ether_dhost()) if self.child(): tmp_str += '\n' + str( self.child()) return tmp_str
"""Adjusts negative indices to their absolute equivalents. Raises IndexError when out of range <0, self.tag_cnt-1>."""
# Linux "cooked" capture encapsulation. # Used, for instance, for packets returned by the "any" interface. "sent to us by somebody else", "broadcast by somebody else", "multicast by somebody else", "sent to somebody else to somebody else", "sent by us", ]
Header.__init__(self, 16) if (aBuffer): self.load_header(aBuffer)
"Sets the packet type field to type" self.set_word(0, type)
"Returns the packet type field" return self.get_word(0)
"Sets the ARPHDR value for the link layer device type" self.set_word(2, type)
"Returns the ARPHDR value for the link layer device type" return self.get_word(2)
"Sets the length of the sender's address field to len" self.set_word(4, len)
"Returns the length of the sender's address field" return self.get_word(4)
"Sets the sender's address field to addr. Addr must be at most 8-byte long." if (len(addr) < 8): addr += b'\0' * (8 - len(addr)) self.get_bytes()[6:14] = addr
"Returns the sender's address field" return self.get_bytes()[6:14].tostring()
"Set ethernet data type field to 'aValue'" self.set_word(14, aValue)
"Return ethernet data type field" return self.get_word(14)
"Return size of packet header" return 16
if self.child(): self.set_ether_type(self.child().ethertype) return Header.get_packet(self)
type = self.get_type() if type < len(LinuxSLL.type_descriptions): return LinuxSLL.type_descriptions[type] else: return "Unknown"
ss = [] alen = self.get_addr_len() addr = hexlify(self.get_addr()[0:alen]) ss.append("Linux SLL: addr=%s type=`%s'" % (addr, self.get_type_desc())) if self.child(): ss.append(str(self.child()))
return '\n'.join(ss)
# When decoding, checksum shouldn't be modified
self.is_BSD = True else:
# set protocol self.set_ip_p(self.child().protocol)
# set total length
my_bytes.extend(op.get_bytes())
# Pad to a multiple of 4 bytes my_bytes.fromstring(b"\0"* num_pad)
# only change ip_hl value if options are present self.set_ip_hl(len(my_bytes) // 4)
# set the checksum if the user hasn't modified it
return my_bytes.tostring() else:
# def calculate_checksum(self, buffer = None): # tmp_value = self.get_ip_sum() # if self.auto_checksum and (not tmp_value): # if buffer: # tmp_bytes = buffer # else: # tmp_bytes = self.bytes[0:self.get_header_size()] # # self.set_ip_sum(self.compute_checksum(tmp_bytes))
pseudo_buf = array.array("B") pseudo_buf.extend(self.get_bytes()[12:20]) pseudo_buf.fromlist([0]) pseudo_buf.extend(self.get_bytes()[9:10]) tmp_size = self.child().get_size()
size_str = struct.pack("!H", tmp_size)
pseudo_buf.fromstring(size_str) return pseudo_buf
self.__option_list.append(option) sum = 0 for op in self.__option_list: sum += op.get_len() if sum > 40: raise ImpactPacketException("Options overflowed in IP packet with length: %d" % sum)
n = self.get_byte(0) return (n >> 4)
return self.get_byte(1)
return self.get_word(2, order = '=') else:
self.set_word(2, value, order = '=') else:
return self.get_word(4)
return self.get_word(6, order = '=') else:
self.set_word(6, aValue, order = '=') else:
return self.get_ip_off() & 0x1FFF
tmp_value = self.get_ip_off() & 0xD000 tmp_value |= aValue self.set_ip_off(tmp_value)
return self.get_ip_off() & 0x8000
tmp_value |= 0x8000 else:
return self.get_ip_off() & 0x4000
tmp_value |= 0x4000 else:
return self.get_ip_off() & 0x2000
tmp_value |= 0x2000 else:
if self.child(): proto = self.child().protocol else: proto = 0
child_data = self.get_data_as_string() if not child_data: return [self]
ip_header_bytes = self.get_bytes() current_offset = 0 fragment_list = []
for frag_size in aList: ip = IP() ip.set_bytes(ip_header_bytes) # copy of original header ip.set_ip_p(proto)
if frag_size % 8: # round this fragment size up to next multiple of 8 frag_size += 8 - (frag_size % 8)
ip.set_ip_offmask(current_offset // 8) current_offset += frag_size
data = Data(child_data[:frag_size]) child_data = child_data[frag_size:]
ip.set_ip_len(20 + data.get_size()) ip.contains(data)
if child_data:
ip.set_ip_mf(1)
fragment_list.append(ip) else: # no more data bytes left to add to fragments
ip.set_ip_mf(0)
fragment_list.append(ip) return fragment_list
if child_data: # any remaining data? # create a fragment containing all of the remaining child_data ip = IP() ip.set_bytes(ip_header_bytes) ip.set_ip_offmask(current_offset) ip.set_ip_len(20 + len(child_data)) data = Data(child_data) ip.contains(data) fragment_list.append(ip)
return fragment_list
data_len = len(self.get_data_as_string()) num_frags = data_len // aSize
if data_len % aSize: num_frags += 1
size_list = [] for i in range(0, num_frags): size_list.append(aSize) return self.fragment_by_list(size_list)
return self.get_byte(8)
return self.get_word(10)
op_len += op.get_len()
raise ImpactPacketException("Cannot load options from truncated packet")
op_type = opt_bytes[0] if op_type == IPOption.IPOPT_EOL or op_type == IPOption.IPOPT_NOP: new_option = IPOption(op_type) op_len = 1 else: op_len = opt_bytes[1] if op_len > len(opt_bytes): raise ImpactPacketException("IP Option length is too high")
new_option = IPOption(op_type, op_len) new_option.set_bytes(opt_bytes[:op_len])
opt_bytes = opt_bytes[op_len:] opt_left -= op_len self.add_option(new_option) if op_type == IPOption.IPOPT_EOL: break
flags = ' ' if self.get_ip_df(): flags += 'DF ' if self.get_ip_mf(): flags += 'MF ' if self.get_ip_rf(): flags += 'RF ' tmp_str = 'IP%s%s -> %s ' % (flags, self.get_ip_src(),self.get_ip_dst()) for op in self.__option_list: tmp_str += '\n' + str(op) if self.child(): tmp_str += '\n' + str(self.child()) return tmp_str
if size and (size < 3 or size > 40): raise ImpactPacketException("IP Options must have a size between 3 and 40 bytes")
if(opcode == IPOption.IPOPT_EOL): PacketBuffer.__init__(self, 1) self.set_code(IPOption.IPOPT_EOL) elif(opcode == IPOption.IPOPT_NOP): PacketBuffer.__init__(self, 1) self.set_code(IPOption.IPOPT_NOP) elif(opcode == IPOption.IPOPT_RR): if not size: size = 39 PacketBuffer.__init__(self, size) self.set_code(IPOption.IPOPT_RR) self.set_len(size) self.set_ptr(4)
elif(opcode == IPOption.IPOPT_LSRR): if not size: size = 39 PacketBuffer.__init__(self, size) self.set_code(IPOption.IPOPT_LSRR) self.set_len(size) self.set_ptr(4)
elif(opcode == IPOption.IPOPT_SSRR): if not size: size = 39 PacketBuffer.__init__(self, size) self.set_code(IPOption.IPOPT_SSRR) self.set_len(size) self.set_ptr(4)
elif(opcode == IPOption.IPOPT_TS): if not size: size = 40 PacketBuffer.__init__(self, size) self.set_code(IPOption.IPOPT_TS) self.set_len(size) self.set_ptr(5) self.set_flags(0) else: if not size: raise ImpactPacketException("Size required for this type") PacketBuffer.__init__(self,size) self.set_code(opcode) self.set_len(size)
op = self.get_code() if not (op == IPOption.IPOPT_RR or op == IPOption.IPOPT_LSRR or op == IPOption.IPOPT_SSRR or op == IPOption.IPOPT_TS): raise ImpactPacketException("append_ip() not support for option type %d" % self.opt_type)
p = self.get_ptr() if not p: raise ImpactPacketException("append_ip() failed, option ptr uninitialized")
if (p + 4) > self.get_len(): raise ImpactPacketException("append_ip() would overflow option")
self.set_ip_address(p - 1, ip) p += 4 self.set_ptr(p)
self.set_byte(0, value)
return self.get_byte(0)
if not (self.get_code() == IPOption.IPOPT_TS): raise ImpactPacketException("Operation only supported on Timestamp option") self.set_byte(3, flags)
if not (self.get_code() == IPOption.IPOPT_TS): raise ImpactPacketException("Operation only supported on Timestamp option") return self.get_byte(3)
self.set_byte(1, len)
self.set_byte(2, ptr)
return self.get_byte(2)
return len(self.get_bytes())
map = {IPOption.IPOPT_EOL : "End of List ", IPOption.IPOPT_NOP : "No Operation ", IPOption.IPOPT_RR : "Record Route ", IPOption.IPOPT_TS : "Timestamp ", IPOption.IPOPT_LSRR : "Loose Source Route ", IPOption.IPOPT_SSRR : "Strict Source Route "}
tmp_str = "\tIP Option: " op = self.get_code() if op in map: tmp_str += map[op] else: tmp_str += "Code: %d " % op
if op == IPOption.IPOPT_RR or op == IPOption.IPOPT_LSRR or op ==IPOption.IPOPT_SSRR: tmp_str += self.print_addresses()
return tmp_str
p = 3 tmp_str = "[" if self.get_len() >= 7: # at least one complete IP address while 1: if p + 1 == self.get_ptr(): tmp_str += "#" tmp_str += self.get_ip_address(p) p += 4 if p >= self.get_len(): break else: tmp_str += ", " tmp_str += "] " if self.get_ptr() % 4: # ptr field should be a multiple of 4 tmp_str += "nonsense ptr field: %d " % self.get_ptr() return tmp_str
self.load_header(aBuffer)
return self.get_word(0) self.set_word(0, value)
return self.get_word(2) self.set_word(2, value)
return self.get_word(4)
self.set_word(4, value)
return self.get_word(6)
self.set_word(6, value) self.auto_checksum = 0
if self.auto_checksum and (not self.get_uh_sum()): # if there isn't a parent to grab a pseudo-header from we'll assume the user knows what they're doing # and won't meddle with the checksum or throw an exception if not self.parent(): return
buffer = self.parent().get_pseudo_header()
buffer += self.get_bytes() data = self.get_data_as_string() if(data): buffer.fromstring(data) self.set_uh_sum(self.compute_checksum(buffer))
tmp_str = 'UDP %d -> %d' % (self.get_uh_sport(), self.get_uh_dport()) if self.child(): tmp_str += '\n' + str(self.child()) return tmp_str
# set total length if(self.get_uh_ulen() == 0): self.set_uh_ulen(self.get_size()) return Header.get_packet(self)
raise ImpactPacketException("Cannot add TCP option, would overflow option space")
return self.__option_list
oldSource = self.get_th_sport() self.set_th_sport(self.get_th_dport()) self.set_th_dport(oldSource)
# # Header field accessors #
return self.get_long(4)
self.set_long(4, aValue)
return self.get_long(8)
self.set_long(8, aValue)
return self.get_word(18)
return self.set_word(18, aValue)
# Flag accessors
tmp_value = self.get_byte(12) & 0x0f return tmp_value
return self.set_flags(128) return self.reset_flags(128)
return self.set_flags(64) return self.reset_flags(64)
return self.set_flags(32) return self.reset_flags(32)
return self.reset_flags(16)
return self.set_flags(8) return self.reset_flags(8)
return self.set_flags(4) return self.reset_flags(4)
return self.set_flags(2) return self.reset_flags(2)
return self.set_flags(1) return self.reset_flags(1)
# Overridden Methods
self.set_th_sum(0) buffer = self.parent().get_pseudo_header() buffer += self.get_bytes() buffer += self.get_padded_options()
data = self.get_data_as_string() if(data): buffer.fromstring(data)
res = self.compute_checksum(buffer)
self.set_th_sum(self.compute_checksum(buffer))
"Returns entire packet including child data as a string. This is the function used to extract the final packet"
# only change th_off value if options are present
return bytes.tostring() + data else:
raise ImpactPacketException("Cannot load options from truncated packet")
else: raise ImpactPacketException("TCP Option length is too high") raise ImpactPacketException("TCP Option length is too low")
break
# # Private #
else:
"Return an array containing all options padded to a 4 byte boundary" op_buf.fromstring("\0" * num_pad)
tmp_str = 'TCP ' if self.get_ECE(): tmp_str += 'ece ' if self.get_CWR(): tmp_str += 'cwr ' if self.get_ACK(): tmp_str += 'ack ' if self.get_FIN(): tmp_str += 'fin ' if self.get_PSH(): tmp_str += 'push ' if self.get_RST(): tmp_str += 'rst ' if self.get_SYN(): tmp_str += 'syn ' if self.get_URG(): tmp_str += 'urg ' tmp_str += '%d -> %d' % (self.get_th_sport(), self.get_th_dport()) for op in self.__option_list: tmp_str += '\n' + str(op)
if self.child(): tmp_str += '\n' + str(self.child()) return tmp_str
PacketBuffer.__init__(self, 1) self.set_kind(TCPOption.TCPOPT_EOL) self.set_mss(data) else: self.set_shift_cnt(data) else: self.set_ts(data) else:
elif kind == TCPOption.TCPOPT_SACK: PacketBuffer.__init__(self, 2) self.set_kind(TCPOption.TCPOPT_SACK)
self.set_long (2, aValue)
self.set_long (6, aValue)
raise ImpactPacketException("Cannot set length field on an option having a size smaller than 2 bytes")
if self.get_size() < 2: raise ImpactPacketException("Cannot retrieve length field from an option having a size smaller than 2 bytes") return self.get_byte(1)
raise ImpactPacketException("Can only set MSS on TCPOPT_MAXSEG option")
if self.get_kind() != TCPOption.TCPOPT_MAXSEG: raise ImpactPacketException("Can only retrieve MSS from TCPOPT_MAXSEG option") return self.get_word(2)
raise ImpactPacketException("Can only set Shift Count on TCPOPT_WINDOW option")
if self.get_kind() != TCPOption.TCPOPT_WINDOW: raise ImpactPacketException("Can only retrieve Shift Count from TCPOPT_WINDOW option") return self.get_byte(2)
if self.get_kind() != TCPOption.TCPOPT_TIMESTAMP: raise ImpactPacketException("Can only retrieve timestamp from TCPOPT_TIMESTAMP option") return self.get_long(2)
raise ImpactPacketException("Can only set timestamp on TCPOPT_TIMESTAMP option")
if self.get_kind() != TCPOption.TCPOPT_TIMESTAMP: raise ImpactPacketException("Can only retrieve timestamp from TCPOPT_TIMESTAMP option") return self.get_long(6)
if self.get_kind() != TCPOption.TCPOPT_TIMESTAMP: raise ImpactPacketException("Can only set timestamp on TCPOPT_TIMESTAMP option") self.set_long(6, ts)
map = { TCPOption.TCPOPT_EOL : "End of List ", TCPOption.TCPOPT_NOP : "No Operation ", TCPOption.TCPOPT_MAXSEG : "Maximum Segment Size ", TCPOption.TCPOPT_WINDOW : "Window Scale ", TCPOption.TCPOPT_TIMESTAMP : "Timestamp " }
tmp_str = "\tTCP Option: " op = self.get_kind() if op in map: tmp_str += map[op] else: tmp_str += " kind: %d " % op if op == TCPOption.TCPOPT_MAXSEG: tmp_str += " MSS : %d " % self.get_mss() elif op == TCPOption.TCPOPT_WINDOW: tmp_str += " Shift Count: %d " % self.get_shift_cnt() elif op == TCPOption.TCPOPT_TIMESTAMP: pass # TODO return tmp_str
return anamolies[self.get_icmp_type()] else:
return self.get_byte(1)
return self.get_ip_address(4)
self.set_ip_address(4, ip)
return self.get_word(6)
return self.get_long(4)
self.set_long(4, aValue)
return self.get_word(6)
self.set_word(6, aValue)
return self.get_byte(4)
self.set_byte(4, aValue)
return self.get_byte(5)
self.set_byte(5, aValue)
return self.get_word(6)
self.set_word(6, aValue)
return self.get_long(8)
self.set_long(8, aValue)
return self.get_long(12)
self.set_long(12, aValue)
return self.get_long(16)
self.set_long(16, aValue)
return self.get_ip_address(8)
self.set_ip_address(8, mask)
tmp_type = {0:'ECHOREPLY', 3:'UNREACH', 4:'SOURCEQUENCH',5:'REDIRECT', 6:'ALTHOSTADDR', 8:'ECHO', 9:'ROUTERADVERT', 10:'ROUTERSOLICIT', 11:'TIMXCEED', 12:'PARAMPROB', 13:'TSTAMP', 14:'TSTAMPREPLY', 15:'IREQ', 16:'IREQREPLY', 17:'MASKREQ', 18:'MASKREPLY', 30:'TRACEROUTE', 31:'DATACONVERR', 32:'MOBILE REDIRECT', 33:'IPV6 WHEREAREYOU', 34:'IPV6 IAMHERE', 35:'MOBILE REGREQUEST', 36:'MOBILE REGREPLY', 39:'SKIP', 40:'PHOTURIS'} answer = tmp_type.get(aType, 'UNKNOWN') return answer
tmp_code = {3:['UNREACH NET', 'UNREACH HOST', 'UNREACH PROTOCOL', 'UNREACH PORT', 'UNREACH NEEDFRAG', 'UNREACH SRCFAIL', 'UNREACH NET UNKNOWN', 'UNREACH HOST UNKNOWN', 'UNREACH ISOLATED', 'UNREACH NET PROHIB', 'UNREACH HOST PROHIB', 'UNREACH TOSNET', 'UNREACH TOSHOST', 'UNREACH FILTER PROHIB', 'UNREACH HOST PRECEDENCE', 'UNREACH PRECEDENCE CUTOFF', 'UNKNOWN ICMP UNREACH']} tmp_code[5] = ['REDIRECT NET', 'REDIRECT HOST', 'REDIRECT TOSNET', 'REDIRECT TOSHOST'] tmp_code[9] = ['ROUTERADVERT NORMAL', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None,'ROUTERADVERT NOROUTE COMMON'] tmp_code[11] = ['TIMXCEED INTRANS ', 'TIMXCEED REASS'] tmp_code[12] = ['PARAMPROB ERRATPTR ', 'PARAMPROB OPTABSENT', 'PARAMPROB LENGTH'] tmp_code[40] = [None, 'PHOTURIS UNKNOWN INDEX', 'PHOTURIS AUTH FAILED', 'PHOTURIS DECRYPT FAILED'] if aType in tmp_code: tmp_list = tmp_code[aType] if ((aCode + 1) > len(tmp_list)) or (not tmp_list[aCode]): return 'UNKNOWN' else: return tmp_list[aCode] else: return 'UNKNOWN'
tmp_type = self.get_icmp_type() tmp_code = self.get_icmp_code() tmp_str = 'ICMP type: ' + self.get_type_name(tmp_type) tmp_str+= ' code: ' + self.get_code_name(tmp_type, tmp_code) if self.child(): tmp_str += '\n' + str( self.child() ) return tmp_str
return self.get_icmp_type() == 3
return not self.isQuery()
return self.isDestinationUnreachable() and (self.get_icmp_code() == 1)
return self.isDestinationUnreachable() and (self.get_icmp_code() == 0)
return self.isDestinationUnreachable() and (self.get_icmp_code() == 3)
return self.isDestinationUnreachable() and (self.get_icmp_code() == 2)
tmp_dict = {8:'', 9:'', 10:'', 13:'', 14:'', 15:'', 16:'', 17:'', 18:''} return self.get_icmp_type() in tmp_dict
Header.__init__(self, 8) if aBuffer: self.load_header(aBuffer)
return self.get_byte(0)
self.set_byte(0, aValue)
return self.get_byte(1)
self.set_byte(1, aValue)
return self.get_word(2)
self.set_word(2, aValue)
return self.get_long(4)
self.set_long(4, aValue)
return 8
tmp_dict = {0x11:'HOST MEMBERSHIP QUERY ', 0x12:'v1 HOST MEMBERSHIP REPORT ', 0x13:'IGMP DVMRP ', 0x14:' PIM ', 0x16:'v2 HOST MEMBERSHIP REPORT ', 0x17:'HOST LEAVE MESSAGE ', 0x1e:'MTRACE REPLY ', 0X1f:'MTRACE QUERY '} answer = tmp_dict.get(aType, 'UNKNOWN TYPE OR VERSION ') return answer
if self.auto_checksum and (not self.get_igmp_cksum()): self.set_igmp_cksum(self.compute_checksum(self.get_bytes()))
tmp_str = 'IGMP: ' + self.get_type_name(self.get_igmp_type()) tmp_str += 'Group: ' + socket.inet_ntoa(struct.pack('!L',self.get_igmp_group())) if self.child(): tmp_str += '\n' + str(self.child()) return tmp_str
return self.get_word(0)
self.set_word(0, aValue)
return self.get_word(2)
self.set_word(2, aValue)
self.set_byte(4, aValue)
self.set_byte(5, aValue)
return self.get_word(6)
self.set_word(6, aValue)
tmp_size = self.get_ar_hln() return self.get_bytes().tolist()[8: 8 + tmp_size]
for i in range(0, self.get_ar_hln()): self.set_byte(i + 8, aValue[i])
tmp_size = self.get_ar_pln() return self.get_bytes().tolist()[8 + self.get_ar_hln(): 8 + self.get_ar_hln() + tmp_size]
for i in range(0, self.get_ar_pln()): self.set_byte(i + 8 + self.get_ar_hln(), aValue[i])
tmp_size = self.get_ar_hln() tmp_from = 8 + self.get_ar_hln() + self.get_ar_pln() return self.get_bytes().tolist()[tmp_from: tmp_from + tmp_size]
tmp_from = 8 + self.get_ar_hln() + self.get_ar_pln() for i in range(0, self.get_ar_hln()): self.set_byte(i + tmp_from, aValue[i])
tmp_size = self.get_ar_pln() tmp_from = 8 + ( 2 * self.get_ar_hln()) + self.get_ar_pln() return self.get_bytes().tolist()[tmp_from: tmp_from + tmp_size]
tmp_from = 8 + (2 * self.get_ar_hln()) + self.get_ar_pln() for i in range(0, self.get_ar_pln()): self.set_byte(i + tmp_from, aValue[i])
tmp_dict = {1:'REQUEST', 2:'REPLY', 3:'REVREQUEST', 4:'REVREPLY', 8:'INVREQUEST', 9:'INVREPLY'} answer = tmp_dict.get(ar_op, 'UNKNOWN') return answer
tmp_dict = { 1:'ARPHRD ETHER', 6:'ARPHRD IEEE802', 15:'ARPHRD FRELAY'} answer = tmp_dict.get(ar_hrd, 'UNKNOWN') return answer
if not anArray: return '' tmp_str = '%x' % anArray[0] for i in range(1, len(anArray)): tmp_str += ':%x' % anArray[i] return tmp_str
if not anArray: return '' tmp_str = '%d' % anArray[0] for i in range(1, len(anArray)): tmp_str += '.%d' % anArray[i] return tmp_str
tmp_op = self.get_ar_op() tmp_str = 'ARP format: ' + self.get_hrd_name(self.get_ar_hrd()) + ' ' tmp_str += 'opcode: ' + self.get_op_name(tmp_op) tmp_str += '\n' + self.as_hrd(self.get_ar_sha()) + ' -> ' tmp_str += self.as_hrd(self.get_ar_tha()) tmp_str += '\n' + self.as_pro(self.get_ar_spa()) + ' -> ' tmp_str += self.as_pro(self.get_ar_tpa()) if self.child(): tmp_str += '\n' + str(self.child()) return tmp_str
a = Ethernet() b = ARP() c = Data('Hola loco!!!') b.set_ar_hln(6) b.set_ar_pln(4) #a.set_ip_dst('192.168.22.6') #a.set_ip_src('1.1.1.2') a.contains(b) b.contains(c) b.set_ar_op(2) b.set_ar_hrd(1) b.set_ar_spa((192, 168, 22, 6)) b.set_ar_tpa((192, 168, 66, 171)) a.set_ether_shost((0x0, 0xe0, 0x7d, 0x8a, 0xef, 0x3d)) a.set_ether_dhost((0x0, 0xc0, 0xdf, 0x6, 0x5, 0xe)) print("beto %s" % a) |