Skip to main content

Overview

Impacket’s Structure class (impacket/structure.py) provides a powerful framework for defining and manipulating binary data structures. It’s the foundation for all protocol implementations in Impacket.

The Structure Class

Basic Concept

The Structure class allows you to define data structures declaratively using format specifiers similar to Python’s struct module, with additional features for complex protocols.

Format Specifiers

Standard struct Format

From Python’s struct module:

Extended Impacket Specifiers

Dynamic Specifiers

Creating Structures

Simple Packet

Variable-Length Fields

Length-Prefixed Data

Arrays

Nested Structures

Parsing Packets

From Binary Data

Conditional Fields

Real-World Examples

SMB Packet Construction

NTLM Authentication Packet

Custom Protocol

Advanced Techniques

Evaluated Fields

Common Header Pattern

Alignment

Debugging

Best Practices

  1. Use type hints in field names: ('length', '<H') is clearer than ('len', '<H')
  2. Specify default values: ('type', 'B=1') prevents uninitialized fields
  3. Use length prefixes: ('<H-Data') auto-calculates lengths
  4. Document complex formats: Add comments for protocol-specific fields
  5. Test with real data: Parse actual packets to validate structure definitions
  6. Handle endianness: Explicitly specify < (little) or > (big) endian

Common Pitfalls

  1. String encoding: Use b'' for byte strings, not regular strings
  2. Array lengths: Ensure count field is set before packing arrays
  3. Field order: Structure fields are packed in definition order
  4. Alignment: Be aware of padding in binary protocols
  5. Nested structures: Use : format specifier, not direct structure assignment

References

  • Python struct module documentation
  • Impacket source: impacket/structure.py
  • Protocol RFCs and Microsoft specifications for real-world examples