pypacker Package

asn1 Module

Abstract Syntax Notation #1.

crc32c Module

pypacker.crc32c.add(crc, buf)
pypacker.crc32c.cksum(buf)

Return computed CRC-32c checksum.

pypacker.crc32c.done(crc)

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()
skip_upperlayer = False
unpack(buf)
xflags = 0
class pypacker.gzip.GzipExtra(*args, **kwargs)

Bases: pypacker.pypacker.Packet

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

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
skip_upperlayer = False
snaplen = 1500
thiszone = 0
v_major = 2
v_minor = 4
class pypacker.ppcap.LEFileHdr(*args, **kwargs)

Bases: pypacker.ppcap.FileHdr

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

Bases: pypacker.ppcap.PktHdr

caplen = 0
len = 0
skip_upperlayer = False
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
skip_upperlayer = False
tv_sec = 0
tv_usec = 0
class pypacker.ppcap.Reader(fileobj=None, filename=None)

Bases: builtins.object

Simple pcap file reader supporting pcap and pcapng format. Using iterators this will return “timestamp, byte string”. Default timestamp resolution ist nanoseconds.

close()
dispatch(cnt, callback, *args)
loop(callback, *args)
class pypacker.ppcap.Writer(fileobj=None, snaplen=1500, linktype=1)

Bases: builtins.object

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

close()
write(pkt, ts=None)

Write the given packet’s bytes to file.

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'>)

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 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 received from network

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.

exception pypacker.pypacker.Error

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__

exception pypacker.pypacker.NeedData

Bases: pypacker.pypacker.UnpackError

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.

  • 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

  • Some members can be set/retrieved using convenient string-represenations beneath the

    byte-represenation (see Ethernet or IP). This is done by appending “_s” to the attributename: obj.key_s = “stringval” string_var = obj.key_s 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,

      can be extended by inserting new ones at arbitrary positions)

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

      These header got format “None” (auto-set when adding new header fields)

      Usage with Packet: - Define an TriggerList as part of the value in __hdr__ (or add via _XXX_headerfield()) - Packets in this list can be added/set/removed afterwards NOTE: deep-layer packets will be omitted in Packets, adding new headers to sub-packets after adding to a TriggerList is not permitted

      Usage for text-based protocols (eg when headername is given by protocol itself like “Host: xyz.org” in HTTP, usage): - define an TriggerList as part of the value in __hdr__ (or add via _XXX_headerfield()) - define _pack() in your TriggerList to reassemble packets (see HTTP). Single values in this list can be represented as tuples like [(key, value), (key, value), ...] - Values in this list can be added/set/removed afterwards

      Examples can be found at the ip and tcp-implementations.

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

  • Header formats can not be updated directly

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

  • Generic callback for rare cases eg where upper layer needs

    to know about lower ones (like TCP->IP 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.

  • no plausability-checks when changing headers/date manually (type-infos have to be set manually)

  • checksums are auto-recalculated until set manualy

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

New Protocols are added by subclassing Packet and defining fields via “__hdr__” as a list of (name, format, default value) tuples. __byte_order__ can be set to override the default (‘>’). Extending classes should overwrite the “_dissect”-method for diessction the given data.

pypacker(__init__) -auto called->
-> _dissect(): has to be overwritten, get to know/verify the real header-structure
-> (optional): call _add/remove_headerfield() to change 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.

Exceptionally a callback can be used for downward leyer signaling like eg TCP -> IP for checksum calculation.

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, data="ld!")
DIR_REV = 2

Direction unknown

DIR_SAME = 1

Reversed direction

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.

create_reverse()

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

TODO: to be implemented

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

data

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.

direction(next)

Every layer can check the direction to the given layer (of the “next” packet). This continues on the next upper layer if a direction was found. This stops if body data is not a Packet. Both packets need net to be of the same typ. The extending class should overwrite _direction() to implement an individual check.

next – Packet to be compared with this Packet return – [DIR_SAME | DIR_REV | DIR_UNKNOWN]

handler

Return handler object or None if not present.

hdr_fmtstr
hdr_len
classmethod load_handler(clz, clz_add, handler)

Load Packet handler using a shared dictionary.

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

pack_hdr()

Return header as byte string.

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: pypacker.pypacker.Error

pypacker.pypacker.byte2hex(buf)

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

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

Return a hexdump output string of the given buffer.

pypacker.pypacker.in_cksum(buf)

Return computed Internet Protocol checksum.

pypacker.pypacker.in_cksum_add(s, buf)

Add checksum value to the given value s.

pypacker.pypacker.in_cksum_done(s)

Complete checksum building.

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)

Bases: builtins.list

List with trigger-capabilities representing dynamic header. This list can contain raw bytes, tuples or packets representing individual header fields. Format changes to packets in this list aren’t allowed after adding. _tuples_to_packets() can be overwritten for auto-creating packets using tuples. Using bytes or tuples “_pack()” must 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, closure) which gets the buffer to be dissected. The closure has to return a simple list itself. Dissecting dynamic fields will only take place on access to TriggerList.

append(v)
bin()

Output the TriggerLists elements as concatenated bytestring.

extend(v)
find_by_id(id)

Advanced list search for tuple-lists: Return all tuples in list having t[0]==id

init_lazy_dissect(buf, closure)

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

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

insert(pos, v)

Table Of Contents

This Page