pypacker Package

checksum Module

pypacker.checksum.crc32_add(crc, buf)
pypacker.checksum.crc32_cksum(buf)

Return computed CRC-32c checksum.

pypacker.checksum.crc32_done(crc)
pypacker.checksum.in_cksum(buf)

Return computed Internet Protocol checksum.

pypacker.checksum.in_cksum_add(s, buf)

Add checksum value to the given value s.

pypacker.checksum.in_cksum_done(s)

Complete checksum building.

gzip Module

GNU zip

class pypacker.gzip.Gzip(*args, **kwargs)

Bases: pypacker.pypacker.Packet

__hdr__ = (('magic', '2s', '\x1f\x8b'), ('method', 'B', 8), ('flags', 'B', 0), ('mtime', 'I', 0), ('xflags', 'B', 0), ('os', 'B', 3), ('extra', '0s', b''), ('filename', '0s', b''), ('comment', '0s', b''))
comment = b''
compress()

Compress self.data.

decompress()

Return decompressed payload.

extra = b''
filename = b''
flags = 0
magic = '\x1f\x8b'
method = 8
mtime = 0
os = 3
pack_hdr()
unpack(buf)
xflags = 0
class pypacker.gzip.GzipExtra(*args, **kwargs)

Bases: pypacker.pypacker.Packet

__hdr__ = (('id', '2s', ''), ('len', 'H', 0))
id = ''
len = 0

ppcap Module

Packet read and write routines for pcap format. See http://wiki.wireshark.org/Development/LibpcapFileFormat

class pypacker.ppcap.FileHdr(*args, **kwargs)

Bases: pypacker.pypacker.Packet

pcap file header.

__hdr__ = (('magic', 'I', 2712847316), ('v_major', 'H', 2), ('v_minor', 'H', 4), ('thiszone', 'I', 0), ('sigfigs', 'I', 0), ('snaplen', 'I', 1500), ('linktype', 'I', 1))
linktype = 1
magic = 2712847316
sigfigs = 0
snaplen = 1500
thiszone = 0
v_major = 2
v_minor = 4
class pypacker.ppcap.LEFileHdr(*args, **kwargs)

Bases: pypacker.pypacker.Packet

pcap file header.

__hdr__ = (('magic', 'I', 2712847316), ('v_major', 'H', 2), ('v_minor', 'H', 4), ('thiszone', 'I', 0), ('sigfigs', 'I', 0), ('snaplen', 'I', 1500), ('linktype', 'I', 1))
linktype = 1
magic = 2712847316
sigfigs = 0
snaplen = 1500
thiszone = 0
v_major = 2
v_minor = 4
class pypacker.ppcap.LEPktHdr(*args, **kwargs)

Bases: pypacker.pypacker.Packet

pcap packet header.

__hdr__ = (('tv_sec', 'I', 0), ('tv_usec', 'I', 0), ('caplen', 'I', 0), ('len', 'I', 0))
caplen = 0
len = 0
tv_sec = 0
tv_usec = 0
class pypacker.ppcap.PktHdr(*args, **kwargs)

Bases: pypacker.pypacker.Packet

pcap packet header.

__hdr__ = (('tv_sec', 'I', 0), ('tv_usec', 'I', 0), ('caplen', 'I', 0), ('len', 'I', 0))
caplen = 0
len = 0
tv_sec = 0
tv_usec = 0
class pypacker.ppcap.Reader(fileobj=None, filename=None, lowest_layer=None, filter=None, ts_conversion=True)

Bases: builtins.object

Simple pcap file reader supporting pcap format. Using iterators this will return (timestamp, bytes) on standard mode and (timestamp, packet) on packet mode. Default timestamp resolution ist nanoseconds.

close()
is_resolution_nano()
class pypacker.ppcap.Writer(fileobj=None, filename=None, snaplen=1500, linktype=1)

Bases: builtins.object

Simple pcap writer supporting pcap format. Note: this will use nanosecond timestamp resolution.

close()
write(bts, ts=None)

Write the given packet’s bytes to file.

bts – bytes to be written ts – timestamp in Nanoseconds

pypacker.ppcap._filter_dummy(pkt)

producer_consumer Module

psocket Module

Packet read and write routines using network sockets.

class pypacker.psocket.SocketHndl(iface_name='lo', mode=0, timeout=3)

Bases: builtins.object

Simple socket reader/writer.

ETH_P_ALL = 3
MODE_LAYER_2 = 0
MODE_LAYER_3 = 1
close()
recv()

return – bytes received from network

recvp(filter_match_recv=None, lowest_layer=<class 'pypacker.layer12.ethernet.Ethernet'>, max_amount=1)

Receive packets from network. This does the same as calling recv() but using a receive filter and received bytes will be converted to packets using class given by lowest_layer.

filter_match_recv – filter as callback function to match packets to be retrieved. The only
parameter is the created packet itself. Return True to accept a specific packet. Raise StopIteration to stop receiving packets

lowest_layer – packet class to be used to create new packets max_amount – maximum amount of packets to be fetched return – packets received from network as list

send(bts, dst=None)

Send the given bytes to network.

bts – the bytes to be sent dst – destination for Layer 3 if mode is MODE_LAYER_3

sr(packet_send, max_packets_recv=1, filter=None, lowest_layer=<class 'pypacker.layer12.ethernet.Ethernet'>)

Send a packet and receive answer packets. This will use information retrieved from direction() to retrieve answer packets.

packet_send – pypacker packet to be sent max_packets_recv – max packets to be received filter – filter as lambda function to match packets to be retrieved,

return True to accept a specific packet

lowest_layer – packet class to be used to create new packets

return – packets receives

pypacker Module

Simple packet creation and parsing logic.

exception pypacker.pypacker.DissectError

Bases: builtins.Exception

class pypacker.pypacker.MetaPacket

Bases: builtins.type

This Metaclass is a more efficient way of setting attributes than using __init__. This is done by reading name / format / default out of __hdr__ in every subclass. This configuration is set one time when loading the module (not at instatiation). Actual values are retrieved using “obj.field” notation.

CAUTION: - list et al are _SHARED_ among all classes! A copy is needed on changes to them. General note: __new__ is called before __init__ - new protocols: don’t use header fields having same names as methods in Packet class

exception pypacker.pypacker.NeedData

Bases: builtins.Exception

class pypacker.pypacker.Packet(*args, **kwargs)

Bases: builtins.object

Base packet class, with metaclass magic to generate members from self.__hdr__. This class can be instatiated via:

Packet(byte_array) Packet(key1=val1, key2=val2, ...)

Every packet got an optional header and an optional body. Body-data can be raw byte string OR a packet itself (the body handler). which stores the data. The following schema illustrates the Packet-structure:

[Packet: [headerfield1] [headerfield2] ... [headerfieldN] [Body: Handler (Packet):

[headerfield1] ... [Body: Handler (Packet):

... [Body: Raw data]

]]]

A header definition like __hdr__ = ((“name”, “12s”, b”defaultvalue”),) will define a header field having the name “name”, format “12s” and defaultvalue “defaultvalue” as bytestring. Fields will be added in order of definition. __byte_order__ can be set to override the default value ‘>’. Extending classes should overwrite the “_dissect”-method in order to dissect given data.

  • Auto-decoding of headers via given format-patterns (defined via __hdr__)

  • Auto-decoding of body-handlers (like IP -> parse IP-data -> add TCP-handler to IP -> parse TCP-data..)

  • Access of fields via “layer1.key” notation

  • Convenient access for standard types (MAC, IP address) using string-represenations

    This is done by appending “_s” to the attributename: ip.src_s = “127.0.0.1” ip_src_bytes = ip.src

    Implementation info: Convenient access should be set via varname_s = pypacker.Packet._get_property_XXX(“varname”)

  • Access of higher layers via layer1.layer2.layerX or “layer1[layerX]” notation

  • Concatination via “layer1 + layer2 + layerX”

  • There are two types of headers:
    1. Static (same order, pre-defined header-names, constant format)

      Format for __hdr__: (“name”, “format”, value)

    2. Dynamic (Packet based or textual protocol-headers, changes in format, length and order)

      Format for __hdr__: (“name”, None, TriggerList) Allowed contents (mutual exclusive): raw bytes, tuples like (key, value), Packets

      For raw bytes or tuple-based TriggerLists, _pack() can be overwritten to reassemble the whole header (see ip.py and tcp.py). For changes on other fields resulting from TriggerList-changes, _handle_mod(value) can be overwritten (see ip.py)

  • Header-values with length < 1 Byte should be set by using properties

  • Header formats can not be updated directly

  • Static fields can be deactivated via setting None “obj.field = None”, re-activate by setting a value

  • Ability to check direction to other Packets via “direction()”

  • Generic callback to lower layers for rare cases eg where upper layer needs

    to know about lower ones (like TCP (higher layer) ->IP (lower layer) for checksum calculation)

  • No correction of given raw packet-data eg checksums when creating a packet from it

    (exception: if the packet can’t be build without correct data -> raise exception). The internal state will only be updated on changes to headers or data.

  • Checksums are auto-recalculated until set manualy

  • General rule: less changes to headers/body-data = more performance

pypacker(__init__) -auto called->
-> _dissect(): has to be overwritten, get to know/verify the real header-structure
-> (optional): call _parse_handler() setting a handler representing an upper-layer

-auto called-> _unpack(): set all header values and data using the given format.

Examples:

>>> class Foo(Packet):
...       __hdr__ = (("foo", "I", 1), ("bar", "H", 2), ("baz", "4s", "quux"))
...
>>> foo = Foo(bar=3)
>>> foo
Foo(bar=3)
>>> foo.bin()
b"quux"
>>> foo.bar
3
>>> foo.baz
b"quux"
>>> foo.foo = 7
>>> foo.baz = "whee"
>>> foo
Foo(baz="whee", foo=7, bar=3)
>>> Foo(b"hello, world!")
Foo(baz=" wor", foo=1751477356L, bar=28460, body_bytes="ld!")
DIR_REV = 2
DIR_SAME = 1
DIR_UNKNOWN = 3
add_change_listener(listener_cb)

Add a new callback to be called on changes to header or body. The only argument is this packet itself.

listener_cb – the change listener to be added as callback-function

bin()

Return this header and body (including all upper layers) as byte string and reset changed-status.

body_bytes

Return raw data bytes or handler bytes (including all upper layers) if present. This is the same as calling bin() but excluding this header and without resetting changed-status.

body_handler

Return handler object or None if not present.

create_reverse()

Creata a packet having reverse direction. This is defined for: Ethernet, IP, TCP, UDP. Note: This will only set static headers fields which are responsible for direction. Unknown layers will be created using the standard constructor.

return – Packet having reverse direction of layers starting from this layer

direction(packet2)

Every layer can check the direction to the given “packet2” layer. This continues until no body handler can be found anymore. The extending class should overwrite _direction() to implement an individual check.

packet2 – Packet to be compared with this Packet return – Possible Bitwise OR-concatination of [DIR_SAME | DIR_REV | DIR_UNKNOWN], check using “&” operator

dissect_full()

Recursive unpack ALL data inlcuding lazy header etc up to highest layer inlcuding danymic fields.

hdr_len
header_bytes

Return header as byte string.

header_len
is_direction(packet2, direction)

Same as “direction()” but using explicit direction to be checked. As direction can be DIR_SAME and DIR_REV at the same time, this call is more clearly.

packet2 – packet to be compared to this packet direction – check for this direction return – True if direction dirextion is found in this packet, False otherwise.

classmethod load_handler(clz, clz_add, handler)

Load Packet handler using a shared dictionary.

clz_add – class for which handler has to be added handler – dict of handlers to be set like { id : class }, id can be a tuple of values

parsefail
remove_change_listener(listener_cb, remove_all=False)

Remove callback from the list of listeners.

listener_cb – the change listener to be removed remove_all – remove all listener at once

exception pypacker.pypacker.UnpackError

Bases: builtins.Exception

pypacker.pypacker.byte2hex(buf)

Convert a bytestring to a hex-represenation: b‘1234’ -> ‘1234’

pypacker.pypacker.get_rnd_ipv4()

Create random ipv4 adress as bytestring

pypacker.pypacker.get_rnd_mac()

Create random mac address as bytestring

pypacker.pypacker.hexdump(buf, length=16)

Return a hexdump output string for the given bytestring.

pypacker.pypacker.ip4_bytes_to_str(ip_bytes)

Convert ip address from byte representation to 127.0.0.1.

pypacker.pypacker.ip4_str_to_bytes(ip_str)

Convert ip address 127.0.0.1 to byte representation.

pypacker.pypacker.mac_bytes_to_str(mac_bytes)

Convert mac address from byte representation to AA:BB:CC:DD:EE:FF.

pypacker.pypacker.mac_str_to_bytes(mac_str)

Convert mac address AA:BB:CC:DD:EE:FF to byte representation.

triggerlist Module

TriggerList for handling dynamic headers.

class pypacker.triggerlist.TriggerList(lst=[], clz=None, packet=None)

Bases: builtins.list

List with trigger-capabilities representing dynamic header. This list can contain raw bytes, tuples or packets representing individual header fields. Using bytes or tuples “_pack()” should be overwritten to reassemble bytes. A TriggerList must be initiated using the no-parameter constructor and modified by using append/extend/del etc. Performance hint: for lazy dissecting, call init_lazy_dissect(buf, callback) which gets the buffer to be dissected. The callback has to return a simple list itself. Dissecting dynamic fields will only take place on access to TriggerList. TODO: add mode for simple/list based access

append(v)
bin()

Output the TriggerLists elements as concatenated bytestring.

extend(v)
find_pos(needle, extract_cb=None, offset=0, preformat_cb=<function TriggerList.<lambda> at 0xb5fe038c>)

Find an item-position giving needle as search criteria.

needle – value to search for extract_cb – lambda expression to extract values from packets: needle == extract_cb(packet) offset – start at index “offset” to search preformat_cb – lambda expression to preformat key before comparing: needle == preformat_cb(key),

eg lowercase for HTTP-header names

return – index of first element found or None

find_value(needle, extract_cb=None, offset=0, preformat_cb=<function TriggerList.<lambda> at 0xb5fe041c>)

Same as find_pos() but directly returning found value or None.

init_lazy_dissect(buf, callback)

Initialize lazy dissecting for performance reasons. A packet has to be assigned first to ‘packet’.

buf – the buffer to be dissected callback – method to be used to dissect the buffer. Gets this buffer as only parameter.

insert(pos, v)

Table Of Contents

This Page