Alx Mx
Alx Mx

Reputation: 179

How to define a packet with variable amount of fields using Scapy?

I am trying to define a certain type packet in Scapy. All fields of the packet are of the same type, except the first field which is ByteField, and the the number of the fields will be determined by the value of the that ByteField field. For example, if the value is 8, then there will be 9 fields in the packet totally.

I've looked at Scapy documentation but couldn't find anything relevant there. The problem is that I have to do it inside the definition of the packet itself and I don't think loops and variables are accepted in "fields_desc" structure.

It obviously starts as something:

fields_desc = [
    ByteField("NumOfFields", 0),

]

But then I'm stuck as I need to use the actual value of that field and generate other fields probably in loop.

How this could be done?

Upvotes: 0

Views: 1229

Answers (2)

Cukic0d
Cukic0d

Reputation: 5411

You have several options:

  • If the fields are of the same type: FieldListField with a length_from attribute.
  • Create your own custom field: using i2m...
  • Use a PacketListField with 1-sized packets. It has more options that FielfListField.

In any case, have a look at https://scapy.readthedocs.io/en/latest/build_dissect.html#fields and help(...) when required :-)

Upvotes: 2

Shir
Shir

Reputation: 1207

I think you can use ConditionalField.

From Scapy documentation:

ConditionalField(fld, cond)
        # Wrapper to make field 'fld' only appear if
        # function 'cond' evals to True, e.g.
        # ConditionalField(XShortField("chksum",None),lambda pkt:pkt.chksumpresent==1)

So you can do something like-

ConditionalField(IntField('Field_1', 0), lambda pkt: pkt.NumOfFields >= 1)

I used it myself in a pretty similar context in the code of this question, maybe it will be useful for you.

Upvotes: 0

Related Questions