Skip to content

Missing pkt.underlayer causes MQTT to fail #5071

Description

@nrathaus

Brief description

MQTTPublish will trigger a crash if it has no underlayer, because it expects one and tries to read from it:

Patch:

diff --git a/scapy/contrib/mqtt.py b/scapy/contrib/mqtt.py
index afd75e78..c6b9c729 100644
--- a/scapy/contrib/mqtt.py
+++ b/scapy/contrib/mqtt.py
@@ -198,12 +198,16 @@ class MQTTPublish(Packet):
         StrLenField("topic", "",
                     length_from=lambda pkt: pkt.length),
         ConditionalField(ShortField("msgid", None),
-                         lambda pkt: (pkt.underlayer.QOS == 1 or
+                         lambda pkt: pkt.underlayer is not None and
+                                     (pkt.underlayer.QOS == 1 or
                                       pkt.underlayer.QOS == 2)),
         StrLenField("value", "",
-                    length_from=lambda pkt: pkt.underlayer.len - pkt.length - 2
-                    if pkt.underlayer.QOS == 0 else
-                    pkt.underlayer.len - pkt.length - 4)
+                    length_from=lambda pkt: (
+                        0 if pkt.underlayer is None else
+                        pkt.underlayer.len - pkt.length - 2
+                        if pkt.underlayer.QOS == 0 else
+                        pkt.underlayer.len - pkt.length - 4
+                    ))
     ]

I asked Claude to see if it finds other similar patterns of such issues (access to underlayer without checking if underlayer exists) and it reported:

That pattern shows up in 9 files, 18 places (bluetooth.py, smb2.py, dot15d4.py, several bluetooth_vsc_* contrib files, ospf.py, rsvp.py, scada/pcom.py).

If you want me to open an issue for each, or a PR for all of them, just let me know

Scapy version

5e13d41

Python version

3.11

Operating system

Linux

Additional environment information

No response

How to reproduce

load_contrib('mqtt')
p = MQTTPublish()
p.show()

A crash shows on p.show()

Actual result

No response

Expected result

No response

Related resources

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions