2021-03-13 23:48:39 +00:00
|
|
|
"""
|
|
|
|
Inject a WebSocket message into a running connection.
|
|
|
|
|
|
|
|
This example shows how to inject a WebSocket message into a running connection.
|
|
|
|
"""
|
|
|
|
import asyncio
|
|
|
|
|
2022-11-29 13:28:41 +00:00
|
|
|
from mitmproxy import ctx
|
|
|
|
from mitmproxy import http
|
2021-03-13 23:48:39 +00:00
|
|
|
|
|
|
|
|
|
|
|
# Simple example: Inject a message as a response to an event
|
|
|
|
|
2022-04-26 11:53:35 +00:00
|
|
|
|
2021-07-15 12:46:45 +00:00
|
|
|
def websocket_message(flow: http.HTTPFlow):
|
|
|
|
assert flow.websocket is not None # make type checker happy
|
2021-03-13 23:48:39 +00:00
|
|
|
last_message = flow.websocket.messages[-1]
|
2021-08-18 11:37:28 +00:00
|
|
|
if last_message.is_text and "secret" in last_message.text:
|
2021-07-15 12:46:45 +00:00
|
|
|
last_message.drop()
|
2022-04-26 11:53:35 +00:00
|
|
|
ctx.master.commands.call(
|
|
|
|
"inject.websocket", flow, last_message.from_client, b"ssssssh"
|
|
|
|
)
|
2021-03-13 23:48:39 +00:00
|
|
|
|
|
|
|
|
|
|
|
# Complex example: Schedule a periodic timer
|
|
|
|
|
2022-04-26 11:53:35 +00:00
|
|
|
|
2021-03-13 23:48:39 +00:00
|
|
|
async def inject_async(flow: http.HTTPFlow):
|
|
|
|
msg = "hello from mitmproxy! "
|
2021-07-15 12:46:45 +00:00
|
|
|
assert flow.websocket is not None # make type checker happy
|
2021-03-16 13:52:01 +00:00
|
|
|
while flow.websocket.timestamp_end is None:
|
2021-08-18 11:37:28 +00:00
|
|
|
ctx.master.commands.call("inject.websocket", flow, True, msg.encode())
|
2021-03-13 23:48:39 +00:00
|
|
|
await asyncio.sleep(1)
|
|
|
|
msg = msg[1:] + msg[:1]
|
|
|
|
|
|
|
|
|
2023-02-13 21:45:02 +00:00
|
|
|
# Python 3.11: replace with TaskGroup
|
|
|
|
tasks = set()
|
|
|
|
|
|
|
|
|
2021-03-13 23:48:39 +00:00
|
|
|
def websocket_start(flow: http.HTTPFlow):
|
2023-02-13 21:45:02 +00:00
|
|
|
# we need to hold a reference to the task, otherwise it will be garbage collected.
|
|
|
|
t = asyncio.create_task(inject_async(flow))
|
|
|
|
tasks.add(t)
|
|
|
|
t.add_done_callback(tasks.remove)
|