diff --git a/moscow.mk b/moscow.mk index 42d5bc6..4b3371e 100644 --- a/moscow.mk +++ b/moscow.mk @@ -23,7 +23,7 @@ # nasm, ussr, C toolchain the runtime and its native xHCI driver # clang, ld.lld /lib/ctest.so, gui.so and tls.so (BearSSL, # fetched once); CLANG= and LLD= override -# Linux, gcc, flex, bison, /bin/ussr, /bin/ural and /bin/moscow_native: +# Linux, gcc, flex, bison, /bin/ussr, /bin/ural, /bin/moscow_native and /bin/kal-ssh: # perl, curl static PIE against musl, with zlib, OpenSSL, # curl and SQLite, all fetched once # clang, lld-link BOOTX64.EFI, the UEFI loader (efi/loader.c), @@ -88,6 +88,8 @@ ZLIB := zlib-1.3.2 ZLIB_SHA256 := bb329a0a2cd0274d05519d61c667c062e06990d72e125ee2dfa8de64f0119d16 OPENSSL := openssl-3.5.9 OPENSSL_SHA256 := 603f5602e2eef00d77fbd429d34dcd5822bb301757a1bc9cdb24c670f1eb859a +LIBSSH2 := libssh2-1.11.1 +LIBSSH2_SHA256 := d9ec76cbe34db98eec3539fe2c899d26b0c837cb3eb466a56b0f109cabf658f7 CURL := curl-8.23.0 CURL_SHA256 := e3de77cfa6367083c776a26647fc9f633b538c06c3baa73d931a252ac8f72b49 SQLITE := sqlite-autoconf-3540100 @@ -123,6 +125,9 @@ $(DL)/$(ZLIB).tar.gz: $(call fetch,https://zlib.net/fossils/$(ZLIB).tar.gz https://github.com/madler/zlib/releases/download/v$(ZLIB:zlib-%=%)/$(ZLIB).tar.gz,$(ZLIB_SHA256)) $(DL)/$(OPENSSL).tar.gz: $(call fetch,https://github.com/openssl/openssl/releases/download/$(OPENSSL)/$(OPENSSL).tar.gz https://www.openssl.org/source/$(OPENSSL).tar.gz,$(OPENSSL_SHA256)) +$(DL)/$(LIBSSH2).tar.gz: + $(call fetch,https://libssh2.org/download/$(LIBSSH2).tar.gz,$(LIBSSH2_SHA256)) + $(DL)/$(CURL).tar.gz: $(call fetch,https://curl.se/download/$(CURL).tar.gz https://github.com/curl/curl/releases/download/curl-$(subst .,_,$(CURL:curl-%=%))/$(CURL).tar.gz,$(CURL_SHA256)) $(DL)/$(SQLITE).tar.gz: @@ -148,7 +153,7 @@ $(OUT)/xhci.bin: $(OUT)/xhci.o $(ARCH)/xhci.ld CHINA := $(ROOT)/src/china SU_SRC := $(filter-out $(CHINA)/%,$(wildcard $(ROOT)/src/*.su $(ROOT)/src/*/*.su $(ROOT)/src/*/*/*.su)) BOOT_FILES := ussr_rt.bin moscow.ru russia.ru rush.ru -NATIVE_RU := install stalin belarus +NATIVE_RU := install stalin belarus kal RUSSIA_RU := Mbl Mbltishi kremlin CHINA_RU := china $(basename $(notdir $(wildcard $(CHINA)/*/*.su))) BIN_RU := $(NATIVE_RU) $(RUSSIA_RU) $(CHINA_RU) @@ -168,6 +173,10 @@ $(OUT)/russia.ru $(OUT)/stalin.ru $(OUT)/belarus.ru: $(OUT)/%.ru: $(SU_SRC) $(US mkdir -p $(OUT) cd $(ROOT)/src/$* && $(RUN_USSR) -c $*.su $@ +$(OUT)/kal.ru: $(ROOT)/src/kaliningrad/kal.su $(USSR) + mkdir -p $(OUT) + cd $(ROOT)/src/kaliningrad && $(RUN_USSR) -c kal.su $@ + $(OUT)/rush.ru: $(SU_SRC) $(USSR) mkdir -p $(OUT) cd $(ROOT)/src/russia && $(RUN_USSR) -c rush.su $@ @@ -271,7 +280,7 @@ NATIVE_TOOLS := gcc make flex bison perl curl NATIVE_OK := $(if $(filter Linux,$(shell uname -s)),$(if $(strip $(foreach t,$(NATIVE_TOOLS),$(if $(call have,$(t)),,$(t)))),,yes)) ifeq ($(NATIVE_OK),yes) -PROGS := $(NATIVE)/ussr $(NATIVE)/ural $(NATIVE)/moscow_native +PROGS := $(NATIVE)/ussr $(NATIVE)/ural $(NATIVE)/moscow_native $(NATIVE)/kal-ssh PREFIX := $(NATIVE)/musl MUSL_GCC := $(PREFIX)/bin/musl-gcc MLIB := $(PREFIX)/lib @@ -318,6 +327,20 @@ $(DEPS)/lib/libcurl.a: $(DL)/$(CURL).tar.gz $(DEPS)/lib/libssl.a $(DEPS)/lib/lib $(MAKE) -j$(JOBS) -C lib >/dev/null 2>&1 && $(MAKE) -C lib install >/dev/null 2>&1 && \ $(MAKE) -C include install >/dev/null 2>&1 +$(DEPS)/lib/libssh2.a: $(DL)/$(LIBSSH2).tar.gz $(DEPS)/lib/libssl.a + tar -xzf $< -C $(NATIVE) + cd $(NATIVE)/$(LIBSSH2) && CC=$(MUSL_GCC) CFLAGS="$(PICFLAGS)" \ + CPPFLAGS="-I$(DEPS)/include" LDFLAGS="-L$(DEPS)/lib -static" LIBS= \ + ./configure --prefix=$(DEPS) --with-crypto=openssl --with-libssl-prefix=$(DEPS) \ + --disable-shared --enable-static --without-libz >/dev/null && \ + $(MAKE) -C src -j$(JOBS) >/dev/null && $(MAKE) -C src install >/dev/null && \ + cp include/libssh2.h $(DEPS)/include/ + +$(NATIVE)/kal-ssh: $(ROOT)/src/kaliningrad/kal_ssh.c $(DEPS)/lib/libssh2.a + $(MUSL_GCC) -fPIE -O2 -Wall -Wextra -I$(DEPS)/include $(PIE) -o $@ $< \ + -L$(DEPS)/lib -lssh2 -lcrypto $(MLIB)/crtn.o + strip $@ 2>/dev/null || true + $(NATIVE)/$(SQLITE)/sqlite3.c: $(DL)/$(SQLITE).tar.gz mkdir -p $(NATIVE) tar -xzf $< -C $(NATIVE) @@ -351,7 +374,7 @@ $(NATIVE)/ussr: $(USSR_SRC) $(DEPS)/lib/libssl.a | $(MUSL_GCC) $(NATIVE)/moscow_native: $(ROOT)/tests/moscow_native.c | $(MUSL_GCC) $(MUSL_GCC) -fPIE -O1 -w $(PIE) -o $@ $< $(MLIB)/crtn.o else -$(call missing,Linux programs need Linux and $(NATIVE_TOOLS): no new /bin/ussr /bin/ural /bin/moscow_native) +$(call missing,Linux programs need Linux and $(NATIVE_TOOLS): no new /bin/ussr /bin/ural /bin/moscow_native /bin/kal-ssh) PROGS := endif @@ -416,7 +439,7 @@ $(IMG): $(OUT)/moscow.img $(addprefix $(OUT)/,$(addsuffix .ru,$(BIN_RU))) $(LIBS [ -f "$$so" ] || { echo "moscow.mk: no /lib/*.so" >&2; break; }; \ $(BELARUS) put $@ $$so /lib/$$(basename $$so); \ done - for f in ussr ural moscow_native; do \ + for f in ussr ural moscow_native kal-ssh; do \ if [ -f $(NATIVE)/$$f ]; then $(BELARUS) put $@ $(NATIVE)/$$f /bin/$$f; \ else echo "moscow.mk: no /bin/$$f" >&2; fi; \ done @@ -446,7 +469,7 @@ $(ISO): $(IMG) $(ISO_EFI) FORCE mkdir -p $(STAGE)/boot $(STAGE)/bin $(STAGE)/etc/ssl $(STAGE)/src/ussr for f in $(BOOT_FILES); do cp $(OUT)/$$f $(STAGE)/boot/$$f; done for f in $(BIN_RU); do cp $(OUT)/$$f.ru $(STAGE)/bin/$$f.ru; done - for f in ussr ural moscow_native; do \ + for f in ussr ural moscow_native kal-ssh; do \ if [ -f $(NATIVE)/$$f ]; then cp $(NATIVE)/$$f $(STAGE)/bin/$$f; fi; \ done printf '%s' "moscow-install" >$(STAGE)/etc/hostname @@ -481,7 +504,7 @@ endif clean: rm -rf $(OUT)/*.bin $(OUT)/*.ru $(OUT)/*.img $(OUT)/*.iso $(OUT)/iso $(OUT)/lib \ $(OUT)/files.txt $(OUT)/murmansk.rules \ - $(NATIVE)/ussr $(NATIVE)/ural $(NATIVE)/moscow_native $(NATIVE)/src + $(NATIVE)/ussr $(NATIVE)/ural $(NATIVE)/moscow_native $(NATIVE)/kal-ssh $(NATIVE)/src FORCE: .PHONY: all boot img iso clean certs FORCE diff --git a/src/kaliningrad/README.md b/src/kaliningrad/README.md new file mode 100644 index 0000000..b1423e4 --- /dev/null +++ b/src/kaliningrad/README.md @@ -0,0 +1,39 @@ +# Kaliningrad + +Kaliningrad opens a remote SSH shell from the current console. + +## Linux and Windows + +Install OpenSSH Client and make sure `ssh` is on `PATH`. From the +repository root: + + ussr src/kaliningrad/kal.su server.example alice + ussr src/kaliningrad/kal.su server.example alice 2222 + +Kaliningrad passes the arguments directly to OpenSSH and returns its exit +status. OpenSSH handles host verification, authentication, configuration, +and terminal I/O. + +## Moscow + +A Linux build of the Moscow ISO includes `/bin/kal.ru` and the static +libssh2 backend. At the Rush prompt in a master-admin session: + + kal(): "192.0.2.10" "alice" 22 "HOST_KEY_SHA256_HEX" + +Use the server's IPv4 address and replace the final argument with the +64-character SHA-256 hex digest of its SSH host public key. Obtain it +from the server's trusted console or administrator. On a Linux server, +for an Ed25519 host key: + + awk '{print $2}' /etc/ssh/ssh_host_ed25519_key.pub | base64 -d | sha256sum + +Use the digest of the host key the server and client negotiate. A mismatch +ends the connection before password entry. Moscow supports password +authentication and an interactive remote terminal. Press Ctrl-] to +disconnect locally. Its backend requires a CPU with working RDRAND. + +With Paramiko installed for Python, run the SSH integration test after +building the ISO: + + python src/moscow/tools/kal_test.py --qemu qemu-system-x86_64 --uefi diff --git a/src/kaliningrad/box.uno b/src/kaliningrad/box.uno new file mode 100644 index 0000000..7cd723e --- /dev/null +++ b/src/kaliningrad/box.uno @@ -0,0 +1 @@ +'Package{name=`kaliningrad`,version=`0.1.0`,description=`Console SSH client for Linux, Windows, and Moscow`,entry=`kal.su`,dependencies=[],files=[`kal.su`,`kal_ssh.c`,`README.md`],license=`UNSPECIFIED`,minimum_ussr=`0.5.0`,source=``}' diff --git a/src/kaliningrad/kal.su b/src/kaliningrad/kal.su new file mode 100644 index 0000000..27b2e86 --- /dev/null +++ b/src/kaliningrad/kal.su @@ -0,0 +1,29 @@ +# Hosted systems use their installed OpenSSH. Moscow ships kal-ssh. +init(r): argc argv [ + getenv(os): "OS" + if(_): {argc < 2 || argc > 4} [ + print(_): "Usage: kal HOST USER [PORT] (Moscow also requires a host key fingerprint)" + return(r): 2 + ] + at(host): argv 0 + at(user): argv 1 + set(port): "22" + if(_): {argc >= 3} [ at(port): argv 2 ] + typeof(port_type): port + if(_): {port_type = "integer"} [ encode(port): port ] + elif(_): {port_type != "string"} [ return(r): 2 ] + if(_): {os = "Moscow"} [ + if(_): {argc != 4} [ + print(_): "Usage: kal HOST USER PORT SHA256_HEX" + return(r): 2 + ] + at(fingerprint): argv 3 + run(r): "/bin/kal-ssh" host user port fingerprint + return(r): r + ] + if(_): {argc > 3} [ + print(_): "Usage: kal HOST USER [PORT]" + return(r): 2 + ] + ssh(r): "-l" user "-p" port "--" host +] diff --git a/src/kaliningrad/kal_ssh.c b/src/kaliningrad/kal_ssh.c new file mode 100644 index 0000000..dd8b903 --- /dev/null +++ b/src/kaliningrad/kal_ssh.c @@ -0,0 +1,229 @@ +/* Moscow's native SSH backend. The protocol and cryptography live in libssh2. */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MOSCOW_CONSOLE_RAW 0x4b00 + +static bool seed_random(void) +{ + unsigned int eax, ebx, ecx, edx; + unsigned long seed[8]; + if (!__get_cpuid(1, &eax, &ebx, &ecx, &edx) || !(ecx & bit_RDRND)) + return false; + for (size_t i = 0; i < sizeof(seed) / sizeof(seed[0]); ++i) { + unsigned char ready = 0; + for (int attempt = 0; attempt < 10 && !ready; ++attempt) + __asm__ volatile("rdrand %0; setc %1" : "=r"(seed[i]), "=qm"(ready)); + if (!ready) { + OPENSSL_cleanse(seed, sizeof(seed)); + return false; + } + } + RAND_seed(seed, sizeof(seed)); + OPENSSL_cleanse(seed, sizeof(seed)); + return RAND_status() == 1; +} + +static int hex_digit(char c) +{ + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + if (c >= 'A' && c <= 'F') + return c - 'A' + 10; + return -1; +} + +static bool parse_fingerprint(const char *text, unsigned char digest[32]) +{ + if (strlen(text) != 64) + return false; + for (size_t i = 0; i < 32; ++i) { + int high = hex_digit(text[i * 2]); + int low = hex_digit(text[i * 2 + 1]); + if (high < 0 || low < 0) + return false; + digest[i] = (unsigned char)(16 * high + low); + } + return true; +} + +static int write_all(int fd, const char *data, size_t size) +{ + while (size) { + ssize_t n = write(fd, data, size); + if (n <= 0) + return -1; + data += n; + size -= (size_t)n; + } + return 0; +} + +static int read_password(char *password, size_t capacity) +{ + size_t length = 0; + size_t excess = 0; + fputs("Password: ", stderr); + fflush(stderr); + for (;;) { + char ch; + if (read(STDIN_FILENO, &ch, 1) != 1 || ch == 3 || ch == 4) + return -1; + if (ch == '\r' || ch == '\n') + break; + if (ch == '\b' || ch == 127) { + if (excess) + --excess; + else if (length) + --length; + } else if ((unsigned char)ch >= 32) { + if (length == capacity) + ++excess; + else + password[length++] = ch; + } + } + fputc('\n', stderr); + return excess ? -1 : (int)length; +} + +static int interactive(LIBSSH2_SESSION *session, LIBSSH2_CHANNEL *channel, int fd) +{ + char output[4096]; + char input[1024]; + size_t offset = 0, length = 0; + libssh2_session_set_blocking(session, 0); + while (!libssh2_channel_eof(channel)) { + bool progress = false; + for (int stream = 0; stream <= 1; ++stream) { + ssize_t n = libssh2_channel_read_ex(channel, stream, output, sizeof(output)); + if (n > 0) { + if (write_all(stream ? STDERR_FILENO : STDOUT_FILENO, output, (size_t)n)) + return 1; + progress = true; + } else if (n < 0 && n != LIBSSH2_ERROR_EAGAIN) { + return 1; + } + } + if (offset < length) { + ssize_t n = libssh2_channel_write(channel, input + offset, length - offset); + if (n > 0) { + offset += (size_t)n; + progress = true; + } else if (n < 0 && n != LIBSSH2_ERROR_EAGAIN) { + return 1; + } + } + int directions = libssh2_session_block_directions(session); + struct pollfd events[] = { + {fd, POLLIN | ((directions & LIBSSH2_SESSION_BLOCK_OUTBOUND) ? POLLOUT : 0), 0}, + {STDIN_FILENO, offset == length ? POLLIN : 0, 0}, + }; + if (poll(events, 2, progress ? 0 : 50) < 0) + return 1; + if (events[1].revents & POLLIN) { + ssize_t n = read(STDIN_FILENO, input, sizeof(input)); + if (n < 0 && errno == EAGAIN) + continue; + if (n <= 0 || memchr(input, 29, (size_t)n)) + return 0; + offset = 0; + length = (size_t)n; + } + } + return libssh2_channel_get_exit_status(channel); +} + +int main(int argc, char **argv) +{ + unsigned char expected[32]; + struct sockaddr_in addr = {.sin_family = AF_INET}; + char *end = NULL; + long port = argc == 5 ? strtol(argv[3], &end, 10) : 0; + if (argc != 5 || port < 1 || port > 65535 || *end || !argv[2][0] || + inet_pton(AF_INET, argv[1], &addr.sin_addr) != 1 || + !parse_fingerprint(argv[4], expected)) { + fputs("Usage: kal-ssh IPV4 USER PORT SHA256_HEX\n", stderr); + return 2; + } + addr.sin_port = htons((unsigned short)port); + if (!seed_random()) { + fputs("kal: Moscow SSH requires a working CPU RDRAND source\n", stderr); + return 1; + } + if (libssh2_init(0)) { + fputs("kal: could not initialize libssh2\n", stderr); + return 1; + } + int result = 1; + int fd = socket(AF_INET, SOCK_STREAM, 0); + LIBSSH2_SESSION *session = NULL; + LIBSSH2_CHANNEL *channel = NULL; + bool raw = false; + char password[256] = {0}; + if (fd < 0 || connect(fd, (struct sockaddr *)&addr, sizeof(addr))) { + perror("kal: connect"); + goto done; + } + session = libssh2_session_init(); + if (!session) + goto done; + libssh2_session_set_timeout(session, 15000); + if (libssh2_session_handshake(session, fd)) { + fputs("kal: SSH handshake failed\n", stderr); + goto done; + } + const char *actual = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA256); + if (!actual || CRYPTO_memcmp(expected, actual, sizeof(expected))) { + fputs("kal: SSH host key fingerprint does not match\n", stderr); + goto done; + } + if (ioctl(STDIN_FILENO, MOSCOW_CONSOLE_RAW, 1)) { + fputs("kal: could not enable unechoed terminal input\n", stderr); + goto done; + } + raw = true; + int length = read_password(password, sizeof(password)); + if (length < 0 || libssh2_userauth_password_ex(session, argv[2], + (unsigned int)strlen(argv[2]), password, (unsigned int)length, NULL)) { + fputs("kal: password authentication failed\n", stderr); + goto done; + } + OPENSSL_cleanse(password, sizeof(password)); + channel = libssh2_channel_open_session(session); + if (!channel || libssh2_channel_request_pty(channel, "xterm") || + libssh2_channel_shell(channel)) { + fputs("kal: could not start a remote terminal\n", stderr); + goto done; + } + fputs("kal: press Ctrl-] to disconnect\n", stderr); + result = interactive(session, channel, fd); +done: + OPENSSL_cleanse(password, sizeof(password)); + if (raw) + ioctl(STDIN_FILENO, MOSCOW_CONSOLE_RAW, 0); + if (session) + libssh2_session_set_blocking(session, 0); + if (channel) + libssh2_channel_free(channel); + if (fd >= 0) + close(fd); + if (session) + libssh2_session_free(session); + libssh2_exit(); + return result; +} diff --git a/src/moscow/README.md b/src/moscow/README.md index 96d6725..572de22 100644 --- a/src/moscow/README.md +++ b/src/moscow/README.md @@ -52,6 +52,9 @@ The [China package](../china/README.md) supplies precompiled command-line programs on the live ISO and installed system. Use `run(_): "china"` in Rush to list them. +[Kaliningrad](../kaliningrad/README.md) opens a remote SSH shell from the +Moscow console. Linux-built images include its native SSH backend. + ## Console accounts The stock live media start a single master-admin session named `ted`. diff --git a/src/moscow/arch/amd64/native.inc b/src/moscow/arch/amd64/native.inc index 261e09f..f68b8ab 100644 --- a/src/moscow/arch/amd64/native.inc +++ b/src/moscow/arch/amd64/native.inc @@ -1033,10 +1033,6 @@ n_sys_zero: xor eax, eax ret -n_sys_notty: - mov rax, -E_NOTTY - ret - n_sys_nomem: mov rax, -E_NOMEM ret @@ -1340,7 +1336,6 @@ n_table: dq 104, n_sys_zero ; getgid dq 107, n_sys_zero ; geteuid dq 108, n_sys_zero ; getegid - dq 16, n_sys_notty ; ioctl: the console is lines dq 73, n_sys_zero ; flock: one program at a file dq 280, n_sys_zero ; utimensat dq 95, n_sys_umask diff --git a/src/moscow/linux.su b/src/moscow/linux.su index c586725..9382c58 100644 --- a/src/moscow/linux.su +++ b/src/moscow/linux.su @@ -500,6 +500,17 @@ lx_read(r): t fd buf n [ btget(f): t fd btget(kind): f "kind" if(_): {kind = "con"} [ + btget(raw): f "raw" false + if(_): raw [ + if(_): {n = 0} [ return(r): 0 ] + terminal_raw(_): + terminal_getch(key): + terminal_sane(_): + if(_): {key < 0} [ return(r): 0 ] + k_upoke(w): buf key 1 + if(_): {w < 0} [ return(r): w ] + return(r): 1 + ] btget(line): f "buf" len(ln): line if(_): {ln = 0} [ @@ -1561,6 +1572,18 @@ lx_fcntl(r): t fd cmd arg [ elif(_): {cmd = 5} [ k_upoke(_): arg 2 2 ] ] +# 0x4b00 toggles unechoed reads on this console descriptor. +lx_ioctl(r): t fd req value [ + set(r): -25 + if(_): {req != 19200} [ return(r): r ] + btget(file): t fd + if(_): {file = null} [ return(r): -9 ] + btget(kind): file "kind" + if(_): {kind != "con"} [ return(r): r ] + btput(_): file "raw" {value != 0} + set(r): 0 +] + # __linux: [number, six arguments] sys_linux(r): v [ at(n): v 0 @@ -1578,6 +1601,7 @@ sys_linux(r): v [ elif(_): {n = 2} [ lx_open(r): t a b ] elif(_): {n = 257} [ lx_open(r): t b c ] elif(_): {n = 3} [ lx_close(r): t a ] + elif(_): {n = 16} [ lx_ioctl(r): t a b c ] elif(_): {n = 8} [ lx_seek(r): t a b c ] elif(_): {n = 4 || n = 6} [ lx_stat(r): t a b ] elif(_): {n = 5} [ lx_fstat(r): t a b ] diff --git a/src/moscow/tools/kal_test.py b/src/moscow/tools/kal_test.py new file mode 100644 index 0000000..1acdd5a --- /dev/null +++ b/src/moscow/tools/kal_test.py @@ -0,0 +1,115 @@ +"""Test the Moscow SSH console client against a local Paramiko server.""" +import argparse +import hashlib +import os +import socket +import threading +import tempfile +import paramiko +from qemu_test import ISO, Machine, clean, find_ovmf, find_qemu, uefi_drives + +class ShellServer(paramiko.ServerInterface): + def __init__(self): + self.ready = threading.Event() + def get_allowed_auths(self, username): + return "password" + def check_auth_password(self, username, password): + if (username, password) == ("alice", "kal-test-secret"): + return paramiko.AUTH_SUCCESSFUL + return paramiko.AUTH_FAILED + def check_channel_request(self, kind, chid): + return (paramiko.OPEN_SUCCEEDED if kind == "session" + else paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED) + def check_channel_pty_request(self, channel, term, width, height, pixelwidth, pixelheight, modes): + return True + def check_channel_shell_request(self, channel): + self.ready.set() + return True + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--qemu") + parser.add_argument("--port", type=int, default=6860) + parser.add_argument("--uefi", action="store_true") + args = parser.parse_args() + qemu = find_qemu(args.qemu) + if qemu is None: + parser.error("QEMU is required") + with tempfile.TemporaryDirectory() as work: + extra = ["-cpu", "max"] + if args.uefi: + firmware = find_ovmf(qemu) + if firmware is None: + parser.error("OVMF is required for --uefi") + extra += uefi_drives(firmware, os.path.join(work, "vars.fd")) + exercise(qemu, args.port, extra) + + +def exercise(qemu, serial_port, extra): + key = paramiko.RSAKey.generate(2048) + fingerprint = hashlib.sha256(key.asbytes()).hexdigest() + listener = socket.socket() + listener.bind(("127.0.0.1", 0)) + listener.listen() + port = listener.getsockname()[1] + errors = [] + + def serve(): + for expected_session in (False, True): + sock, _ = listener.accept() + transport = paramiko.Transport(sock) + transport.add_server_key(key) + server = ShellServer() + try: + transport.start_server(server=server) + channel = transport.accept(20) + if not expected_session: + assert channel is None + continue + assert channel is not None and server.ready.wait(10) + channel.send(b"kal remote ready\r\n") + channel.settimeout(15) + message = bytearray() + while not message.endswith(b"\r"): + part = channel.recv(128) + if not part: + raise AssertionError("connection closed before terminal input") + message.extend(part) + assert message == b"hello from Moscow\r", message + channel.send(b"kal input received\r\n") + channel.send_exit_status(7) + channel.shutdown_write() + channel.close() + except Exception as error: + errors.append(error) + finally: + transport.close() + + threading.Thread(target=serve, daemon=True).start() + machine = Machine(qemu, [], serial_port, [], cdrom=ISO, extra=extra) + s = machine.serial + try: + s.output_to_prompt(timeout=90) + command = f'kal(status): "10.0.2.2" "alice" {port}' + s.command(f'{command} "{64 * "0"}"') + failed = clean(s.output_to_prompt(timeout=35)) + assert "fingerprint does not match" in failed and "Password:" not in failed, failed + s.command(f'{command} "{fingerprint}"') + s.read_until(b"Password: ", timeout=35) + s.sock.sendall(b"kal-test-secret\r") + ready = s.read_until(b"kal remote ready", timeout=35) + assert b"kal-test-secret" not in ready, "password was echoed" + s.sock.sendall(b"hello from Moscow\r") + output = clean(s.output_to_prompt(timeout=35)) + assert "kal input received" in output, output + s.command("print(_): status") + assert clean(s.output_to_prompt()) == "7" + assert not errors, errors + print("PASS SSH fingerprint rejection, password auth, PTY data and exit status", flush=True) + finally: + machine.close() + listener.close() + + +if __name__ == "__main__": + main()