Skip to content

Commit 0de8699

Browse files
committed
Restore TCP kill behavior on upstream 12.2.2
1 parent 437fb75 commit 0de8699

2 files changed

Lines changed: 46 additions & 1 deletion

File tree

mitmproxy/proxy/layers/tcp.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,10 @@ def relay_messages(self, event: events.Event) -> layer.CommandGenerator[None]:
115115
tcp_message = tcp.TCPMessage(from_client, event.data)
116116
self.flow.messages.append(tcp_message)
117117
yield TcpMessageHook(self.flow)
118-
yield commands.SendData(send_to, tcp_message.content)
118+
if self.flow.live:
119+
yield commands.SendData(send_to, tcp_message.content)
120+
else:
121+
yield commands.CloseTcpConnection(send_to, half_close=True)
119122
else:
120123
yield commands.SendData(send_to, event.data)
121124

test/mitmproxy/proxy/layers/test_tcp.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
from ..tutils import Placeholder
44
from ..tutils import Playbook
55
from ..tutils import reply
6+
from mitmproxy import connection
7+
from mitmproxy import options
68
from mitmproxy.proxy.commands import CloseConnection
79
from mitmproxy.proxy.commands import CloseTcpConnection
810
from mitmproxy.proxy.commands import OpenConnection
@@ -11,6 +13,7 @@
1113
from mitmproxy.proxy.events import DataReceived
1214
from mitmproxy.proxy.layers import tcp
1315
from mitmproxy.proxy.layers.tcp import TcpMessageInjected
16+
from mitmproxy.proxy import context as proxy_context
1417
from mitmproxy.tcp import TCPFlow
1518
from mitmproxy.tcp import TCPMessage
1619

@@ -149,3 +152,42 @@ def test_inject(tctx):
149152
<< None
150153
)
151154
assert len(f().messages) == 2
155+
156+
157+
def _build_tctx() -> proxy_context.Context:
158+
opts = options.Options()
159+
client = connection.Client(
160+
peername=("client", 1234),
161+
sockname=("127.0.0.1", 8080),
162+
state=connection.ConnectionState.OPEN,
163+
timestamp_start=1605699329,
164+
)
165+
return proxy_context.Context(client, opts)
166+
167+
168+
def test_kill_closes_connection_when_flow_not_live():
169+
"""If a TCP flow is marked not live, the layer should close rather than relay data."""
170+
171+
def mark_flow_dead(flow: TCPFlow) -> None:
172+
flow.live = False
173+
174+
f = Placeholder(TCPFlow)
175+
tctx = _build_tctx()
176+
177+
assert (
178+
Playbook(tcp.TCPLayer(tctx))
179+
<< tcp.TcpStartHook(f)
180+
>> reply()
181+
<< OpenConnection(tctx.server)
182+
>> reply(None)
183+
>> DataReceived(tctx.client, b"terminate")
184+
<< tcp.TcpMessageHook(f)
185+
>> reply(side_effect=mark_flow_dead)
186+
<< CloseTcpConnection(tctx.server, half_close=True)
187+
<< None
188+
)
189+
190+
flow = f()
191+
assert flow is not None
192+
assert flow.live is False
193+
assert flow.messages[-1].content == b"terminate"

0 commit comments

Comments
 (0)