Skip to content

Commit c21f06f

Browse files
committed
BPF filter: fix memory leak
1 parent ef72e1d commit c21f06f

File tree

3 files changed

+16
-6
lines changed

3 files changed

+16
-6
lines changed

scapy/arch/bpf/core.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import struct
1515

1616
from scapy.arch.bpf.consts import BIOCSETF, BIOCSETIF
17-
from scapy.arch.common import compile_filter
17+
from scapy.arch.common import compile_filter, free_filter
1818
from scapy.config import conf
1919
from scapy.consts import LINUX
2020
from scapy.error import Scapy_Exception
@@ -76,6 +76,8 @@ def attach_filter(fd, bpf_filter, iface):
7676
ret = fcntl.ioctl(fd, BIOCSETF, bp)
7777
if ret < 0:
7878
raise Scapy_Exception("Can't attach the BPF filter !")
79+
# Free
80+
free_filter(bp)
7981

8082

8183
def in6_getifaddr():

scapy/arch/common.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,14 @@ def compile_filter(filter_exp, # type: str
132132
return bpf
133133

134134

135+
def free_filter(bp: bpf_program) -> None:
136+
"""
137+
Free a bpf_program created with compile_filter
138+
"""
139+
from scapy.libs.winpcapy import pcap_freecode
140+
pcap_freecode(ctypes.byref(bp))
141+
142+
135143
#######
136144
# DNS #
137145
#######

scapy/arch/linux/__init__.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
from scapy.compat import raw
2323
from scapy.consts import LINUX
24-
from scapy.arch.common import compile_filter
24+
from scapy.arch.common import compile_filter, free_filter
2525
from scapy.config import conf
2626
from scapy.data import MTU, ETH_P_ALL, SOL_PACKET, SO_ATTACH_FILTER, \
2727
SO_TIMESTAMPNS
@@ -130,14 +130,14 @@ def attach_filter(sock, bpf_filter, iface):
130130
if conf.use_pypy and sys.pypy_version_info <= (7, 3, 2): # type: ignore
131131
# PyPy < 7.3.2 has a broken behavior
132132
# https://foss.heptapod.net/pypy/pypy/-/issues/3298
133-
bp = struct.pack( # type: ignore
133+
fp = struct.pack( # type: ignore
134134
'HL',
135135
bp.bf_len, ctypes.addressof(bp.bf_insns.contents)
136136
)
137137
else:
138-
bp = sock_fprog(bp.bf_len, bp.bf_insns) # type: ignore
139-
sock.setsockopt(socket.SOL_SOCKET, SO_ATTACH_FILTER, bp)
140-
138+
fp = sock_fprog(bp.bf_len, bp.bf_insns) # type: ignore
139+
sock.setsockopt(socket.SOL_SOCKET, SO_ATTACH_FILTER, fp)
140+
free_filter(bp)
141141

142142
def set_promisc(s, iff, val=1):
143143
# type: (socket.socket, _GlobInterfaceType, int) -> None

0 commit comments

Comments
 (0)