// real GnuPG HKP/WKD endpoints, confined to private user/network/mount namespaces. module main import nspkg.tests.archivefixtures import nspkg.tests.httpfixtures import nspkg.tests.signaturefixtures import json2 import net import net.openssl import net.urllib import os import sync import time fn C.SSL_get_servername(voidptr, i32) &char @[heap] struct Fixture { mut: mutex &sync.Mutex = sync.new_mutex() fingerprint string key string armor string listing string short_only bool wkd_key ?string requests [][]string tls_names []string } fn (mut fixture Fixture) reply(scheme string, path string) httpfixtures.Response { fixture.mutex.@lock() defer { fixture.mutex.unlock() } fixture.requests << [scheme, path] url := urllib.parse(path) or { return httpfixtures.Response{ status: 400 } } if scheme == 'https' { if key := fixture.wkd_key { if url.path.contains('/hu/') { return httpfixtures.Response{ body: key headers: { 'Content-Type': 'application/octet-stream' } } } } return httpfixtures.Response{ status: 404 body: 'missing' headers: { 'Content-Type': 'text/plain' } } } params := url.query() operation := params.get('op') or { '' } search := params.get('search') or { '' } match operation { 'index' { if (fixture.short_only && search.len > 10) || fixture.listing == '' { return httpfixtures.Response{ body: 'info:1:0\n' headers: { 'Content-Type': 'text/plain' } } } return httpfixtures.Response{ body: 'info:1:1\npub:${fixture.listing}:22:255:1700000000::\nuid:Fixture%20%3Calpm%40fixture.test%3E:::\n' headers: { 'Content-Type': 'text/plain' } } } 'get' { return httpfixtures.Response{ body: fixture.armor headers: { 'Content-Type': 'application/pgp-keys' } } } else { return httpfixtures.Response{ status: 404 body: 'missing' headers: { 'Content-Type': 'text/plain' } } } } } fn plain_reply(context voidptr, request httpfixtures.Request) httpfixtures.Response { mut fixture := unsafe { &Fixture(context) } return fixture.reply('http', request.path) } @[heap] struct SecureFixture { mut: listener &openssl.SSLListener fixture &Fixture mutex &sync.Mutex = sync.new_mutex() stopped bool worker thread } fn secure_start(fixture &Fixture, cert string, key string) !&SecureFixture { mut server := &SecureFixture{ listener: openssl.new_ssl_listener('127.0.0.1:443', openssl.SSLConnectConfig{ cert: cert, cert_key: key }, openssl.SSLListenerOptions{})! fixture: unsafe { fixture } } server.worker = spawn server.run() return server } fn (mut server SecureFixture) stopping() bool { server.mutex.@lock() defer { server.mutex.unlock() } return server.stopped } fn (mut server SecureFixture) close() ! { server.mutex.@lock() server.stopped = true server.mutex.unlock() // wake the blocking accept; the worker checks stopped before starting TLS. mut wake := net.dial_tcp('127.0.0.1:443')! wake.close()! server.worker.wait() server.listener.shutdown()! } fn (mut server SecureFixture) run() { for !server.stopping() { mut connection := server.listener.accept_without_handshake() or { eprintln(err) return } if server.stopping() { connection.shutdown() or { eprintln(err) } break } server.serve(mut connection) } } fn (mut server SecureFixture) capture_name(connection &openssl.SSLConn) { name := C.SSL_get_servername(connection.ssl, 0) if name == unsafe { nil } { return } server.fixture.mutex.@lock() defer { server.fixture.mutex.unlock() } server.fixture.tls_names << unsafe { cstring_to_vstring(name) } } fn (mut server SecureFixture) serve(mut connection openssl.SSLConn) { defer { connection.shutdown() or { eprintln(err) } } connection.set_read_timeout(5 * time.second) connection.accept_handshake() or { server.capture_name(connection) return } server.capture_name(connection) mut data := []u8{} mut block := []u8{len: 1024} for data.len < 16384 { n := connection.read(mut block) or { return } if n == 0 { return } data << block[..n] if data.bytestr().contains('\r\n\r\n') { break } } parts := data.bytestr().all_before('\r\n').split(' ') if parts.len < 2 { return } response := server.fixture.reply('https', parts[1]) mut text := 'HTTP/1.1 ${response.status} Fixture\r\nConnection: close\r\nContent-Length: ${response.body.len}\r\n' for key, value in response.headers { text += '${key}: ${value}\r\n' } text += '\r\n' + response.body mut position := 0 for position < text.len { n := connection.write_string(text[position..]) or { return } if n <= 0 { return } position += n } } struct Observation { mut: success bool known bool questions []string detail string code int scenario string backend string requests [][]string tls_names []string log string actions []string } fn configure(path string, server string, cert string) !signaturefixtures.Keyring { os.mkdir(path, mode: 0o700)! os.write_file(os.join_path(path, 'gpg.conf'), 'no-auto-key-retrieve\nauto-key-locate clear,wkd\ntrust-model direct\nkeyserver ${server}\n')! os.write_file(os.join_path(path, 'dirmngr.conf'), 'standard-resolver\nno-use-tor\nconnect-timeout 2\nconnect-quick-timeout 2\nresolver-timeout 2\nhkp-cacert ${cert}\nlog-file ${path}/dirmngr.log\ndebug-level advanced\n')! return signaturefixtures.Keyring{ path: path } } fn certificate(base string, name string) !(string, string) { cert := os.join_path(base, name + '.pem') key := os.join_path(base, name + '-key.pem') signaturefixtures.command('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1', '-subj', '/CN=fixture.test', '-addext', 'subjectAltName=DNS:fixture.test,DNS:openpgpkey.fixture.test', '-keyout', key, '-out', cert])! return cert, key } fn isolate(base string, cert string, parent_mount string, parent_net string) ! { if os.getuid() != 0 || os.readlink('/proc/self/ns/mnt')! == parent_mount || os.readlink('/proc/self/ns/net')! == parent_net { return error('key transport fixture requires private user/network/mount namespaces') } signaturefixtures.command('mount', ['--make-rprivate', '/'])! signaturefixtures.command('ip', ['link', 'set', 'lo', 'up'])! hosts := os.join_path(base, 'hosts') os.write_file(hosts, '127.0.0.1 localhost fixture.test openpgpkey.fixture.test\n::1 localhost\n')! signaturefixtures.command('mount', ['--bind', hosts, '/etc/hosts'])! mut targets := map[string]bool{} for path in ['/etc/ssl/certs/ca-certificates.crt', '/etc/ssl/cert.pem', '/etc/pki/tls/certs/ca-bundle.crt'] { if os.exists(path) { targets[os.real_path(path)] = true } } for target, _ in targets { signaturefixtures.command('mount', ['--bind', cert, target])! } anchors := os.join_path(base, 'anchors') os.mkdir(anchors)! os.cp(cert, os.join_path(anchors, 'fixture.pem'))! for target in ['/etc/ca-certificates/trust-source/anchors', '/etc/pki/ca-trust/source/anchors'] { if os.is_dir(target) { signaturefixtures.command('mount', ['--bind', anchors, target])! } } } fn (mut fixture Fixture) scenario(name string, correct_armor string, wrong_armor string, wrong_key string, wrong_fingerprint string) { fixture.mutex.@lock() defer { fixture.mutex.unlock() } fixture.requests = [][]string{} fixture.tls_names = []string{} fixture.listing = if name in ['missing', 'wkd', 'wkd-untrusted', 'load-missing'] { '' } else { fixture.fingerprint } if name in ['hkp-id', 'body-mismatch', 'load-id'] { fixture.listing = fixture.fingerprint[fixture.fingerprint.len - 16..] } if name == 'index-mismatch' { fixture.listing = wrong_fingerprint } fixture.armor = if name in ['body-mismatch', 'load-mismatch'] { wrong_armor } else { correct_armor } fixture.short_only = name in ['hkp-short', 'load-short'] fixture.wkd_key = if name == 'wkd' { ?string(fixture.key) } else if name == 'wkd-wrong' { ?string(wrong_key) } else { none } } fn (mut fixture Fixture) observe(probe string, home string, name string, base string, backend string, action string) !Observation { uid := if name.starts_with('wkd') { 'Fixture ' } else { '' } text := signaturefixtures.command('timeout', ['20s', probe, home, fixture.fingerprint, uid, if name in ['declined', 'load-declined', 'db-declined'] { 'no' } else { 'yes' }, base, backend, action])! signaturefixtures.command('gpgconf', ['--homedir', home, '--kill', 'all'])! mut result := json2.decode[Observation](text)! result.scenario = name if action != 'import' { result.backend = backend } fixture.mutex.@lock() result.requests = fixture.requests.clone() result.tls_names = fixture.tls_names.clone() fixture.mutex.unlock() logfile := os.join_path(home, 'dirmngr.log') if os.exists(logfile) { result.log = os.read_file(logfile)! } return result } fn main() { run() or { eprintln(err) exit(1) } } fn run() ! { if os.args.len != 7 || os.args[3] != '--parent-mount' || os.args[5] != '--parent-net' { return error('expected probe, base, --parent-mount ID and --parent-net ID') } probe := os.args[1] base := os.args[2] cert, key := certificate(base, 'trusted')! bad_cert, bad_key := certificate(base, 'untrusted')! isolate(base, cert, os.args[4], os.args[6])! mut fixture := &Fixture{} mut plain := httpfixtures.start(plain_reply, fixture)! defer { plain.close() or { eprintln(err) } } server := plain.url.replace('http://', 'hkp://') mut homes := []string{} defer { for home in homes { signaturefixtures.command('gpgconf', ['--homedir', home, '--kill', 'all']) or { eprintln(err) } } } signer := configure(os.join_path(base, 'signer'), server, cert)! homes << signer.path fixture.fingerprint = signer.generate('Fixture ')! fixture.key = signer.gpg(['--export'])! correct_armor := signer.gpg(['--armor', '--export'])! wrong := configure(os.join_path(base, 'wrong'), server, cert)! homes << wrong.path wrong_fingerprint := wrong.generate('Fixture ')! wrong_key := wrong.gpg(['--export'])! wrong_armor := wrong.gpg(['--armor', '--export'])! package := os.join_path(base, 'fixture.pkg.tar') archivefixtures.write(package, [archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = fixture\npkgver = 1-1\narch = any\n' }], false)! signer.sign(package, [fixture.fingerprint], false)! mut results := []Observation{} for scenario in ['hkp-full', 'hkp-id', 'hkp-short', 'missing', 'declined', 'wkd', 'wkd-fallback', 'wkd-wrong', 'wkd-untrusted', 'index-mismatch', 'body-mismatch'] { home := os.join_path(base, scenario) configure(home, server, cert)! homes << home fixture.scenario(scenario, correct_armor, wrong_armor, wrong_key, wrong_fingerprint) mut secure := secure_start(fixture, if scenario == 'wkd-untrusted' { bad_cert } else { cert }, if scenario == 'wkd-untrusted' { bad_key } else { key })! // this scope closes TLS even if the probe or JSON decoder fails. result := fixture.observe(probe, home, scenario, base, 'native', 'import') or { secure.close() or { eprintln(err) } return err } secure.close()! results << result } for scenario in ['load-full', 'load-id', 'load-short', 'load-missing', 'load-declined', 'load-mismatch'] { for backend in ['reference', 'native', 'public'] { home := os.join_path(base, scenario + '-' + backend) configure(home, server, cert)! homes << home // signing.c checks the legacy keyring before trying its import prepass. os.write_file(os.join_path(home, 'pubring.gpg'), '')! fixture.scenario(scenario, correct_armor, wrong_armor, wrong_key, wrong_fingerprint) results << fixture.observe(probe, home, scenario, base, backend, package)! } } // refresh an expired key through WKD; a new self-signature makes the retry converge. refresh := configure(os.join_path(base, 'refresh-signer'), server, cert)! homes << refresh.path past := time.now().unix() - 10 * 86400 refresh_fpr := refresh.generate_at('Fixture ', past, '1d')! expired := os.join_path(base, 'expired-public') refresh.gpg(['--output', expired, '--export', refresh_fpr])! os.mkdir_all(os.join_path(base, 'sync'))! database := os.join_path(base, 'sync', 'refresh.db') archivefixtures.write(database, [archivefixtures.Entry{ name: 'fixture-1-1/desc', text: '%NAME%\nfixture\n\n%VERSION%\n1-1\n\n' }], false)! refresh.sign_at(database, refresh_fpr, past + 3600, '0')! refresh.gpg(['--pinentry-mode', 'loopback', '--passphrase', '', '--quick-set-expire', refresh_fpr, '0'])! fixture.fingerprint = refresh_fpr fixture.key = refresh.gpg(['--export', refresh_fpr])! updated_armor := refresh.gpg(['--armor', '--export', refresh_fpr])! for scenario in ['wkd', 'wkd-fallback', 'wkd-wrong', 'wkd-untrusted', 'declined'] { for backend in ['reference', 'native', 'public'] { home := os.join_path(base, 'db-' + scenario + '-' + backend) ring := configure(home, server, cert)! homes << home ring.gpg(['--import', expired])! ring.trust(refresh_fpr, 6)! ring.gpg(['--output', os.join_path(home, 'pubring.gpg'), '--export'])! fixture.scenario(scenario, updated_armor, wrong_armor, wrong_key, wrong_fingerprint) mut secure := secure_start(fixture, if scenario == 'wkd-untrusted' { bad_cert } else { cert }, if scenario == 'wkd-untrusted' { bad_key } else { key })! mut result := fixture.observe(probe, home, 'db-' + scenario, base, backend, 'db:refresh') or { secure.close() or { eprintln(err) } return err } secure.close()! results << result } } println(json2.encode(results)) }