summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authoralex <alex@pdp7.net>2024-10-08 21:53:44 +0200
committeralexpdp7 <alex@corcoles.net>2024-10-08 21:55:04 +0200
commit4ceb8f9152a56b3cf5d742b8850d5b963d76764b (patch)
treedf721b4be2d648e4e1bec0666868f097537e3ff0
parentbc5b8c8e968121d7588a11a49714446587403fbc (diff)
Store reroute.py
-rwxr-xr-xlinux/reroute.py59
1 files changed, 59 insertions, 0 deletions
diff --git a/linux/reroute.py b/linux/reroute.py
new file mode 100755
index 00000000..db1a16ab
--- /dev/null
+++ b/linux/reroute.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python3
+
+DESCRIPTION = """
+This script runs a command with a different network configuration using firejail.
+
+THIS MIGHT BE UNSAFE. USE AT YOUR OWN CAUTION:
+
+* Input might not be correctly validated.
+* Use of firejail might not be correct.
+"""
+
+import argparse
+import pathlib
+import shlex
+import subprocess
+import tempfile
+import textwrap
+
+
+def main():
+ parser = argparse.ArgumentParser(description=DESCRIPTION)
+
+ parser.add_argument("network_interface")
+ parser.add_argument("dns")
+ parser.add_argument("gateway")
+ parser.add_argument("ip")
+ parser.add_argument("command", nargs="+")
+
+ parser.add_argument("--route", nargs="*", help="destination,gateway")
+
+ args = parser.parse_args()
+
+ routes = "".join([_make_route(r) for r in args.route])
+
+ command = shlex.join(args.command)
+
+ with tempfile.TemporaryDirectory() as tempdir:
+ script = pathlib.Path(tempdir) / "script"
+
+ script.write_text(textwrap.dedent(
+ f"""
+ #!/bin/sh
+
+ {routes}
+ {command}
+ """
+ ).lstrip())
+ script.chmod(0o555)
+ command = ["sudo", "firejail", f"--net={args.network_interface}", f"--dns={args.dns}", f"--defaultgw={args.gateway}", f"--ip={args.ip}", f"--whitelist={script}", "--", script]
+
+ subprocess.run(command, check=True)
+
+
+def _make_route(argument):
+ destination, gateway = argument.split(",")
+ return shlex.join(["ip", "route", "add", destination, "via", gateway, "dev", "eth0"])
+
+if __name__ == "__main__":
+ main()