| 1 |
#!/usr/bin/env python3 |
| 2 |
"""A stand-in for the `ssh` binary, for tests that must not need an SSH server. |
| 3 |
|
| 4 |
It understands the four things Harlequin passes it -- `-G`, `-V`, `-L` and a |
| 5 |
destination -- and answers `-G` in the format OpenSSH's own config dumper uses. |
| 6 |
Without `-G` it binds the local end of each forward and sleeps, which is every |
| 7 |
observable thing a real forward does to the machine Harlequin is running on. |
| 8 |
|
| 9 |
Environment variables shape what it does, so one script covers the cases: |
| 10 |
|
| 11 |
FAKE_SSH_ARGV append each invocation's argv, as a JSON line, to this path |
| 12 |
FAKE_SSH_FORWARD a `LocalForward` the destination's Host block supplies |
| 13 |
FAKE_SSH_STDERR write this to stderr, as ssh writes its diagnostics |
| 14 |
FAKE_SSH_STDERR_PARTIAL write this to stderr with no trailing newline |
| 15 |
FAKE_SSH_STDOUT write this to stdout, as a ProxyCommand helper may |
| 16 |
FAKE_SSH_EXIT exit with this code instead of binding anything |
| 17 |
FAKE_SSH_HANG bind nothing and sleep, as ssh does waiting on a passphrase |
| 18 |
FAKE_SSH_DELAY seconds to wait before binding |
| 19 |
FAKE_SSH_DROP_WHEN hold the forwards until this path exists, then drop them |
| 20 |
FAKE_SSH_PROBE_EXIT exit `-G` with this code |
| 21 |
FAKE_SSH_PROBE_TEXT print this from `-G` instead of a resolved config |
| 22 |
FAKE_SSH_ALIVE_INTERVAL what `-G` reports for serveraliveinterval (default 0, |
| 23 |
so every tunnel built here is given a keepalive) |
| 24 |
""" |
| 25 |
|
| 26 |
from __future__ import annotations |
| 27 |
|
| 28 |
import json |
| 29 |
import os |
| 30 |
import socket |
| 31 |
import sys |
| 32 |
import time |
| 33 |
|
| 34 |
TAKES_A_VALUE = {"-L", "-R", "-D", "-o", "-i", "-p", "-l", "-F", "-b", "-c", "-W"} |
| 35 |
|
| 36 |
|
| 37 |
def parse_argv(argv: list[str]) -> tuple[list[str], str, bool]: |
| 38 |
"""The `-L` specs, the destination, and whether `-G` was asked for.""" |
| 39 |
forwards: list[str] = [] |
| 40 |
destination = "" |
| 41 |
dump_config = False |
| 42 |
index = 0 |
| 43 |
while index < len(argv): |
| 44 |
arg = argv[index] |
| 45 |
if arg in TAKES_A_VALUE: |
| 46 |
value = argv[index + 1] if index + 1 < len(argv) else "" |
| 47 |
if arg == "-L": |
| 48 |
forwards.append(value) |
| 49 |
index += 2 |
| 50 |
elif arg.startswith("-"): |
| 51 |
dump_config = dump_config or "G" in arg |
| 52 |
index += 1 |
| 53 |
else: |
| 54 |
if not destination: |
| 55 |
destination = arg |
| 56 |
index += 1 |
| 57 |
return forwards, destination, dump_config |
| 58 |
|
| 59 |
|
| 60 |
def format_forward(spec: str) -> tuple[str, str]: |
| 61 |
"""One `-L` spec as the two fields `ssh -G` prints for it.""" |
| 62 |
parts = spec.split(":") |
| 63 |
if len(parts) == 4: |
| 64 |
bind, listen_port, host, port = parts |
| 65 |
listen = f"[{bind}]:{listen_port}" |
| 66 |
else: |
| 67 |
listen_port, host, port = parts |
| 68 |
listen = listen_port |
| 69 |
return listen, f"[{host}]:{port}" |
| 70 |
|
| 71 |
|
| 72 |
def endpoint(listen: str) -> tuple[str, int]: |
| 73 |
"""Where the local end of a forward listens.""" |
| 74 |
if listen.startswith("["): |
| 75 |
host, _, port = listen[1:].partition("]:") |
| 76 |
return host, int(port) |
| 77 |
return "127.0.0.1", int(listen) |
| 78 |
|
| 79 |
|
| 80 |
def main() -> int: |
| 81 |
argv = sys.argv[1:] |
| 82 |
record = os.environ.get("FAKE_SSH_ARGV") |
| 83 |
if record: |
| 84 |
with open(record, "a", encoding="utf-8") as f: |
| 85 |
f.write(json.dumps(argv) + "\n") |
| 86 |
|
| 87 |
if "-V" in argv: |
| 88 |
print("FakeSSH_1.0, a stand-in", file=sys.stderr) |
| 89 |
return 0 |
| 90 |
|
| 91 |
forwards, destination, dump_config = parse_argv(argv) |
| 92 |
from_config = os.environ.get("FAKE_SSH_FORWARD") |
| 93 |
if from_config: |
| 94 |
forwards.append(from_config) |
| 95 |
|
| 96 |
if dump_config: |
| 97 |
probe_exit = int(os.environ.get("FAKE_SSH_PROBE_EXIT", "0")) |
| 98 |
if probe_exit: |
| 99 |
# a real client says why it would not take the argv |
| 100 |
message = os.environ.get("FAKE_SSH_STDERR") |
| 101 |
if message: |
| 102 |
print(message, file=sys.stderr, flush=True) |
| 103 |
return probe_exit |
| 104 |
text = os.environ.get("FAKE_SSH_PROBE_TEXT") |
| 105 |
if text is not None: |
| 106 |
sys.stdout.write(text) |
| 107 |
return 0 |
| 108 |
print(f"host {destination}") |
| 109 |
print(f"hostname {destination}") |
| 110 |
print("port 22") |
| 111 |
print(f"serveraliveinterval {os.environ.get('FAKE_SSH_ALIVE_INTERVAL', '0')}") |
| 112 |
for spec in forwards: |
| 113 |
listen, connect = format_forward(spec) |
| 114 |
print(f"localforward {listen} {connect}") |
| 115 |
return 0 |
| 116 |
|
| 117 |
message = os.environ.get("FAKE_SSH_STDERR") |
| 118 |
if message: |
| 119 |
print(message, file=sys.stderr, flush=True) |
| 120 |
on_stdout = os.environ.get("FAKE_SSH_STDOUT") |
| 121 |
if on_stdout: |
| 122 |
print(on_stdout, flush=True) |
| 123 |
partial = os.environ.get("FAKE_SSH_STDERR_PARTIAL") |
| 124 |
if partial: |
| 125 |
# no trailing newline, as a prompt has none |
| 126 |
sys.stderr.write(partial) |
| 127 |
sys.stderr.flush() |
| 128 |
code = os.environ.get("FAKE_SSH_EXIT") |
| 129 |
if code: |
| 130 |
return int(code) |
| 131 |
|
| 132 |
time.sleep(float(os.environ.get("FAKE_SSH_DELAY", "0"))) |
| 133 |
listeners = [] |
| 134 |
if not os.environ.get("FAKE_SSH_HANG"): |
| 135 |
for spec in forwards: |
| 136 |
listen, _ = format_forward(spec) |
| 137 |
host, port = endpoint(listen) |
| 138 |
sock = socket.socket() |
| 139 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 140 |
try: |
| 141 |
sock.bind((host, port)) |
| 142 |
except OSError as e: |
| 143 |
print(f"bind [{host}]:{port}: {e.strerror}", file=sys.stderr) |
| 144 |
return 255 |
| 145 |
sock.listen(8) |
| 146 |
listeners.append(sock) |
| 147 |
drop_when = os.environ.get("FAKE_SSH_DROP_WHEN") |
| 148 |
if drop_when: |
| 149 |
# the test controls when the forward drops, so nothing races the |
| 150 |
# readiness poll on a loaded machine |
| 151 |
while not os.path.exists(drop_when): |
| 152 |
time.sleep(0.02) |
| 153 |
for sock in listeners: |
| 154 |
sock.close() |
| 155 |
print("Timeout, server web-1 not responding.", file=sys.stderr) |
| 156 |
return 255 |
| 157 |
while True: |
| 158 |
time.sleep(3600) |
| 159 |
|
| 160 |
|
| 161 |
if __name__ == "__main__": |
| 162 |
sys.exit(main()) |