Merge pull request #5593 from mhils/wg-polish

WireGuard: Polish
This commit is contained in:
Maximilian Hils 2022-09-19 17:51:54 +02:00 committed by GitHub
commit 64c3f32276
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 51 additions and 36 deletions

View File

@ -139,7 +139,13 @@ async def resolve_message(
class DnsResolver:
async def dns_request(self, flow: dns.DNSFlow) -> None:
should_resolve = (
isinstance(flow.client_conn.proxy_mode, mode_specs.DnsMode)
(
isinstance(flow.client_conn.proxy_mode, mode_specs.DnsMode)
or (
isinstance(flow.client_conn.proxy_mode, mode_specs.WireGuardMode)
and flow.server_conn.address == ("10.0.0.53", 53)
)
)
and flow.live
and not flow.response
and not flow.error

View File

@ -270,7 +270,7 @@ class Proxyserver(ServerManager):
def inject_event(self, event: events.MessageInjected):
connection_id = (
"tcp",
event.flow.client_conn.transport_protocol,
event.flow.client_conn.peername,
event.flow.client_conn.sockname,
)

View File

@ -1,11 +0,0 @@
import time
import threading
class BaseThread(threading.Thread):
def __init__(self, name, *args, **kwargs):
super().__init__(name=name, *args, **kwargs)
self._thread_started = time.time()
def _threadinfo(self):
return "%s - age: %is" % (self.name, int(time.time() - self._thread_started))

View File

@ -51,7 +51,7 @@ class MitmFormatter(logging.Formatter):
message = miniclick.style(
message,
fg=LOG_COLORS.get(record.levelno),
dim=(record.levelno <= logging.DEBUG)
# dim=(record.levelno <= logging.DEBUG)
)
if client := getattr(record, "client", None):
client = human.format_address(client)

View File

@ -70,8 +70,8 @@ class Http2Connection(HttpConnection):
super().__init__(context, conn)
if self.debug:
self.h2_conf.logger = H2ConnectionLogger(
f"{human.format_address(self.context.client.peername)}: "
f"{self.__class__.__name__}"
self.context.client.peername,
self.__class__.__name__
)
self.h2_conf.validate_inbound_headers = (
self.context.options.validate_inbound_headers

View File

@ -1,4 +1,5 @@
import collections
import logging
from typing import Dict, List, NamedTuple, Tuple
import h2.config
@ -9,16 +10,29 @@ import h2.settings
import h2.stream
logger = logging.getLogger(__name__)
class H2ConnectionLogger(h2.config.DummyLogger):
def __init__(self, name: str):
def __init__(self, peername: tuple, conn_type: str):
super().__init__()
self.name = name
self.peername = peername
self.conn_type = conn_type
def debug(self, fmtstr, *args):
print(f"{self.name} h2 (debug): {fmtstr % args}")
logger.debug(
f"{self.conn_type} {fmtstr}",
*args,
extra={"client": self.peername}
)
def trace(self, fmtstr, *args):
print(f"{self.name} h2 (trace): {fmtstr % args}")
logger.log(
logging.DEBUG - 1,
f"{self.conn_type} {fmtstr}",
*args,
extra={"client": self.peername}
)
class SendH2Data(NamedTuple):

View File

@ -37,6 +37,7 @@ class DestinationKnown(layer.Layer, metaclass=ABCMeta):
if (
self.context.options.connection_strategy == "eager"
and self.context.server.address
and self.context.server.transport_protocol == "tcp"
):
err = yield commands.OpenConnection(self.context.server)
if err:

View File

@ -139,11 +139,6 @@ class ServerInstance(Generic[M], metaclass=ABCMeta):
reader: asyncio.StreamReader | wg.TcpStream,
writer: asyncio.StreamWriter | wg.TcpStream,
) -> None:
connection_id = (
"tcp",
writer.get_extra_info("peername"),
writer.get_extra_info("sockname"),
)
handler = ProxyConnectionHandler(
ctx.master, reader, writer, ctx.options, self.mode
)
@ -152,12 +147,23 @@ class ServerInstance(Generic[M], metaclass=ABCMeta):
socket = writer.get_extra_info("socket")
try:
assert platform.original_addr
handler.layer.context.server.address = platform.original_addr(socket)
original_dst = platform.original_addr(socket)
except Exception as e:
logger.error(f"Transparent mode failure: {e!r}")
return
else:
handler.layer.context.client.sockname = original_dst
handler.layer.context.server.address = original_dst
elif isinstance(self.mode, mode_specs.WireGuardMode):
handler.layer.context.server.address = writer.get_extra_info("original_dst")
original_dst = writer.get_extra_info("original_dst")
handler.layer.context.client.sockname = original_dst
handler.layer.context.server.address = original_dst
connection_id = (
handler.layer.context.client.transport_protocol,
handler.layer.context.client.peername,
handler.layer.context.client.sockname,
)
with self.manager.register_connection(connection_id, handler):
await handler.handle_client()
@ -352,6 +358,7 @@ class WireGuardServerInstance(ServerInstance[mode_specs.WireGuardMode]):
[Interface]
PrivateKey = {self.client_key}
Address = 10.0.0.1/32
DNS = 10.0.0.53
[Peer]
PublicKey = {wg.pubkey(self.server_key)}

View File

@ -53,6 +53,7 @@ def run(
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger("tornado").setLevel(logging.WARNING)
logging.getLogger("asyncio").setLevel(logging.WARNING)
logging.getLogger("hpack").setLevel(logging.WARNING)
debug.register_info_dumpers()
opts = options.Options()

View File

@ -290,7 +290,8 @@ class WebSocketEventBroadcaster(tornado.websocket.WebSocketHandler):
for conn in cls.connections:
try:
conn.write_message(message)
if not conn.ws_connection.is_closing():
conn.write_message(message)
except Exception: # pragma: no cover
logging.error("Error sending message", exc_info=True)

View File

@ -53,5 +53,5 @@ async def test_styling(monkeypatch) -> None:
tctx.configure(t)
logging.warning("hello")
assert "\x1b[33m\x1b[22mhello\x1b[0m" in f.getvalue()
assert "\x1b[33mhello\x1b[0m" in f.getvalue()
t.done()

View File

@ -1,7 +0,0 @@
import re
from mitmproxy.coretypes import basethread
def test_basethread():
t = basethread.BaseThread("foobar")
assert re.match(r"foobar - age: \d+s", t._threadinfo())

View File

@ -1,4 +1,7 @@
.wireguard-config {
> * {
margin: 0;
}
margin: 1rem 0;
display: flex;
flex-wrap: wrap;