nspkg / tests / key_transport_fixture.v
400 lines · 380 sloc · 13.36 KB · c01b0795d1db56c7bce2539b2c46b110637fdc1a
Raw
1// real GnuPG HKP/WKD endpoints, confined to private user/network/mount namespaces.
2module main
3
4import nspkg.tests.archivefixtures
5import nspkg.tests.httpfixtures
6import nspkg.tests.signaturefixtures
7import json2
8import net
9import net.openssl
10import net.urllib
11import os
12import sync
13import time
14
15fn C.SSL_get_servername(voidptr, i32) &char
16
17@[heap]
18struct Fixture {
19mut:
20 mutex &sync.Mutex = sync.new_mutex()
21 fingerprint string
22 key string
23 armor string
24 listing string
25 short_only bool
26 wkd_key ?string
27 requests [][]string
28 tls_names []string
29}
30
31fn (mut fixture Fixture) reply(scheme string, path string) httpfixtures.Response {
32 fixture.mutex.@lock()
33 defer { fixture.mutex.unlock() }
34 fixture.requests << [scheme, path]
35 url := urllib.parse(path) or { return httpfixtures.Response{ status: 400 } }
36 if scheme == 'https' {
37 if key := fixture.wkd_key {
38 if url.path.contains('/hu/') {
39 return httpfixtures.Response{
40 body: key
41 headers: {
42 'Content-Type': 'application/octet-stream'
43 }
44 }
45 }
46 }
47 return httpfixtures.Response{
48 status: 404
49 body: 'missing'
50 headers: {
51 'Content-Type': 'text/plain'
52 }
53 }
54 }
55 params := url.query()
56 operation := params.get('op') or { '' }
57 search := params.get('search') or { '' }
58 match operation {
59 'index' {
60 if (fixture.short_only && search.len > 10) || fixture.listing == '' {
61 return httpfixtures.Response{
62 body: 'info:1:0\n'
63 headers: {
64 'Content-Type': 'text/plain'
65 }
66 }
67 }
68 return httpfixtures.Response{
69 body: 'info:1:1\npub:${fixture.listing}:22:255:1700000000::\nuid:Fixture%20%3Calpm%40fixture.test%3E:::\n'
70 headers: {
71 'Content-Type': 'text/plain'
72 }
73 }
74 }
75 'get' {
76 return httpfixtures.Response{
77 body: fixture.armor
78 headers: {
79 'Content-Type': 'application/pgp-keys'
80 }
81 }
82 }
83 else {
84 return httpfixtures.Response{
85 status: 404
86 body: 'missing'
87 headers: {
88 'Content-Type': 'text/plain'
89 }
90 }
91 }
92 }
93}
94
95fn plain_reply(context voidptr, request httpfixtures.Request) httpfixtures.Response {
96 mut fixture := unsafe { &Fixture(context) }
97 return fixture.reply('http', request.path)
98}
99
100@[heap]
101struct SecureFixture {
102mut:
103 listener &openssl.SSLListener
104 fixture &Fixture
105 mutex &sync.Mutex = sync.new_mutex()
106 stopped bool
107 worker thread
108}
109
110fn secure_start(fixture &Fixture, cert string, key string) !&SecureFixture {
111 mut server := &SecureFixture{
112 listener: openssl.new_ssl_listener('127.0.0.1:443', openssl.SSLConnectConfig{ cert: cert, cert_key: key }, openssl.SSLListenerOptions{})!
113 fixture: unsafe { fixture }
114 }
115 server.worker = spawn server.run()
116 return server
117}
118
119fn (mut server SecureFixture) stopping() bool {
120 server.mutex.@lock()
121 defer { server.mutex.unlock() }
122 return server.stopped
123}
124
125fn (mut server SecureFixture) close() ! {
126 server.mutex.@lock()
127 server.stopped = true
128 server.mutex.unlock()
129 // wake the blocking accept; the worker checks stopped before starting TLS.
130 mut wake := net.dial_tcp('127.0.0.1:443')!
131 wake.close()!
132 server.worker.wait()
133 server.listener.shutdown()!
134}
135
136fn (mut server SecureFixture) run() {
137 for !server.stopping() {
138 mut connection := server.listener.accept_without_handshake() or {
139 eprintln(err)
140 return
141 }
142 if server.stopping() {
143 connection.shutdown() or { eprintln(err) }
144 break
145 }
146 server.serve(mut connection)
147 }
148}
149
150fn (mut server SecureFixture) capture_name(connection &openssl.SSLConn) {
151 name := C.SSL_get_servername(connection.ssl, 0)
152 if name == unsafe { nil } { return }
153 server.fixture.mutex.@lock()
154 defer { server.fixture.mutex.unlock() }
155 server.fixture.tls_names << unsafe { cstring_to_vstring(name) }
156}
157
158fn (mut server SecureFixture) serve(mut connection openssl.SSLConn) {
159 defer { connection.shutdown() or { eprintln(err) } }
160 connection.set_read_timeout(5 * time.second)
161 connection.accept_handshake() or {
162 server.capture_name(connection)
163 return
164 }
165 server.capture_name(connection)
166 mut data := []u8{}
167 mut block := []u8{len: 1024}
168 for data.len < 16384 {
169 n := connection.read(mut block) or { return }
170 if n == 0 { return }
171 data << block[..n]
172 if data.bytestr().contains('\r\n\r\n') { break }
173 }
174 parts := data.bytestr().all_before('\r\n').split(' ')
175 if parts.len < 2 { return }
176 response := server.fixture.reply('https', parts[1])
177 mut text := 'HTTP/1.1 ${response.status} Fixture\r\nConnection: close\r\nContent-Length: ${response.body.len}\r\n'
178 for key, value in response.headers { text += '${key}: ${value}\r\n' }
179 text += '\r\n' + response.body
180 mut position := 0
181 for position < text.len {
182 n := connection.write_string(text[position..]) or { return }
183 if n <= 0 { return }
184 position += n
185 }
186}
187
188struct Observation {
189mut:
190 success bool
191 known bool
192 questions []string
193 detail string
194 code int
195 scenario string
196 backend string
197 requests [][]string
198 tls_names []string
199 log string
200 actions []string
201}
202
203fn configure(path string, server string, cert string) !signaturefixtures.Keyring {
204 os.mkdir(path, mode: 0o700)!
205 os.write_file(os.join_path(path, 'gpg.conf'), 'no-auto-key-retrieve\nauto-key-locate clear,wkd\ntrust-model direct\nkeyserver ${server}\n')!
206 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')!
207 return signaturefixtures.Keyring{ path: path }
208}
209
210fn certificate(base string, name string) !(string, string) {
211 cert := os.join_path(base, name + '.pem')
212 key := os.join_path(base, name + '-key.pem')
213 signaturefixtures.command('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days',
214 '1', '-subj', '/CN=fixture.test', '-addext',
215 'subjectAltName=DNS:fixture.test,DNS:openpgpkey.fixture.test', '-keyout', key, '-out',
216 cert])!
217 return cert, key
218}
219
220fn isolate(base string, cert string, parent_mount string, parent_net string) ! {
221 if os.getuid() != 0 || os.readlink('/proc/self/ns/mnt')! == parent_mount || os.readlink('/proc/self/ns/net')! == parent_net {
222 return error('key transport fixture requires private user/network/mount namespaces')
223 }
224 signaturefixtures.command('mount', ['--make-rprivate', '/'])!
225 signaturefixtures.command('ip', ['link', 'set', 'lo', 'up'])!
226 hosts := os.join_path(base, 'hosts')
227 os.write_file(hosts, '127.0.0.1 localhost fixture.test openpgpkey.fixture.test\n::1 localhost\n')!
228 signaturefixtures.command('mount', ['--bind', hosts, '/etc/hosts'])!
229 mut targets := map[string]bool{}
230 for path in ['/etc/ssl/certs/ca-certificates.crt', '/etc/ssl/cert.pem',
231 '/etc/pki/tls/certs/ca-bundle.crt'] {
232 if os.exists(path) { targets[os.real_path(path)] = true }
233 }
234 for target, _ in targets { signaturefixtures.command('mount', ['--bind', cert, target])! }
235 anchors := os.join_path(base, 'anchors')
236 os.mkdir(anchors)!
237 os.cp(cert, os.join_path(anchors, 'fixture.pem'))!
238 for target in ['/etc/ca-certificates/trust-source/anchors', '/etc/pki/ca-trust/source/anchors'] {
239 if os.is_dir(target) { signaturefixtures.command('mount', ['--bind', anchors, target])! }
240 }
241}
242
243fn (mut fixture Fixture) scenario(name string, correct_armor string, wrong_armor string, wrong_key string, wrong_fingerprint string) {
244 fixture.mutex.@lock()
245 defer { fixture.mutex.unlock() }
246 fixture.requests = [][]string{}
247 fixture.tls_names = []string{}
248 fixture.listing = if name in ['missing', 'wkd', 'wkd-untrusted', 'load-missing'] {
249 ''
250 } else {
251 fixture.fingerprint
252 }
253 if name in ['hkp-id', 'body-mismatch', 'load-id'] {
254 fixture.listing = fixture.fingerprint[fixture.fingerprint.len - 16..]
255 }
256 if name == 'index-mismatch' { fixture.listing = wrong_fingerprint }
257 fixture.armor = if name in ['body-mismatch', 'load-mismatch'] {
258 wrong_armor
259 } else {
260 correct_armor
261 }
262 fixture.short_only = name in ['hkp-short', 'load-short']
263 fixture.wkd_key = if name == 'wkd' {
264 ?string(fixture.key)
265 } else if name == 'wkd-wrong' {
266 ?string(wrong_key)
267 } else {
268 none
269 }
270}
271
272fn (mut fixture Fixture) observe(probe string, home string, name string, base string, backend string, action string) !Observation {
273 uid := if name.starts_with('wkd') { 'Fixture <alpm@fixture.test>' } else { '' }
274 text := signaturefixtures.command('timeout', ['20s', probe, home, fixture.fingerprint, uid,
275 if name in ['declined', 'load-declined', 'db-declined'] { 'no' } else { 'yes' }, base,
276 backend, action])!
277 signaturefixtures.command('gpgconf', ['--homedir', home, '--kill', 'all'])!
278 mut result := json2.decode[Observation](text)!
279 result.scenario = name
280 if action != 'import' { result.backend = backend }
281 fixture.mutex.@lock()
282 result.requests = fixture.requests.clone()
283 result.tls_names = fixture.tls_names.clone()
284 fixture.mutex.unlock()
285 logfile := os.join_path(home, 'dirmngr.log')
286 if os.exists(logfile) { result.log = os.read_file(logfile)! }
287 return result
288}
289
290fn main() {
291 run() or {
292 eprintln(err)
293 exit(1)
294 }
295}
296
297fn run() ! {
298 if os.args.len != 7 || os.args[3] != '--parent-mount' || os.args[5] != '--parent-net' {
299 return error('expected probe, base, --parent-mount ID and --parent-net ID')
300 }
301 probe := os.args[1]
302 base := os.args[2]
303 cert, key := certificate(base, 'trusted')!
304 bad_cert, bad_key := certificate(base, 'untrusted')!
305 isolate(base, cert, os.args[4], os.args[6])!
306 mut fixture := &Fixture{}
307 mut plain := httpfixtures.start(plain_reply, fixture)!
308 defer { plain.close() or { eprintln(err) } }
309 server := plain.url.replace('http://', 'hkp://')
310 mut homes := []string{}
311 defer {
312 for home in homes {
313 signaturefixtures.command('gpgconf', ['--homedir', home, '--kill', 'all']) or { eprintln(err) }
314 }
315 }
316 signer := configure(os.join_path(base, 'signer'), server, cert)!
317 homes << signer.path
318 fixture.fingerprint = signer.generate('Fixture <alpm@fixture.test>')!
319 fixture.key = signer.gpg(['--export'])!
320 correct_armor := signer.gpg(['--armor', '--export'])!
321 wrong := configure(os.join_path(base, 'wrong'), server, cert)!
322 homes << wrong.path
323 wrong_fingerprint := wrong.generate('Fixture <alpm@fixture.test>')!
324 wrong_key := wrong.gpg(['--export'])!
325 wrong_armor := wrong.gpg(['--armor', '--export'])!
326 package := os.join_path(base, 'fixture.pkg.tar')
327 archivefixtures.write(package, [archivefixtures.Entry{ name: '.PKGINFO', text: 'pkgname = fixture\npkgver = 1-1\narch = any\n' }], false)!
328 signer.sign(package, [fixture.fingerprint], false)!
329 mut results := []Observation{}
330 for scenario in ['hkp-full', 'hkp-id', 'hkp-short', 'missing', 'declined', 'wkd', 'wkd-fallback',
331 'wkd-wrong', 'wkd-untrusted', 'index-mismatch', 'body-mismatch'] {
332 home := os.join_path(base, scenario)
333 configure(home, server, cert)!
334 homes << home
335 fixture.scenario(scenario, correct_armor, wrong_armor, wrong_key, wrong_fingerprint)
336 mut secure := secure_start(fixture, if scenario == 'wkd-untrusted' {
337 bad_cert
338 } else {
339 cert
340 }, if scenario == 'wkd-untrusted' { bad_key } else { key })!
341 // this scope closes TLS even if the probe or JSON decoder fails.
342 result := fixture.observe(probe, home, scenario, base, 'native', 'import') or {
343 secure.close() or { eprintln(err) }
344 return err
345 }
346 secure.close()!
347 results << result
348 }
349 for scenario in ['load-full', 'load-id', 'load-short', 'load-missing', 'load-declined',
350 'load-mismatch'] {
351 for backend in ['reference', 'native', 'public'] {
352 home := os.join_path(base, scenario + '-' + backend)
353 configure(home, server, cert)!
354 homes << home
355 // signing.c checks the legacy keyring before trying its import prepass.
356 os.write_file(os.join_path(home, 'pubring.gpg'), '')!
357 fixture.scenario(scenario, correct_armor, wrong_armor, wrong_key, wrong_fingerprint)
358 results << fixture.observe(probe, home, scenario, base, backend, package)!
359 }
360 }
361 // refresh an expired key through WKD; a new self-signature makes the retry converge.
362 refresh := configure(os.join_path(base, 'refresh-signer'), server, cert)!
363 homes << refresh.path
364 past := time.now().unix() - 10 * 86400
365 refresh_fpr := refresh.generate_at('Fixture <alpm@fixture.test>', past, '1d')!
366 expired := os.join_path(base, 'expired-public')
367 refresh.gpg(['--output', expired, '--export', refresh_fpr])!
368 os.mkdir_all(os.join_path(base, 'sync'))!
369 database := os.join_path(base, 'sync', 'refresh.db')
370 archivefixtures.write(database, [archivefixtures.Entry{ name: 'fixture-1-1/desc', text: '%NAME%\nfixture\n\n%VERSION%\n1-1\n\n' }], false)!
371 refresh.sign_at(database, refresh_fpr, past + 3600, '0')!
372 refresh.gpg(['--pinentry-mode', 'loopback', '--passphrase', '', '--quick-set-expire', refresh_fpr,
373 '0'])!
374 fixture.fingerprint = refresh_fpr
375 fixture.key = refresh.gpg(['--export', refresh_fpr])!
376 updated_armor := refresh.gpg(['--armor', '--export', refresh_fpr])!
377 for scenario in ['wkd', 'wkd-fallback', 'wkd-wrong', 'wkd-untrusted', 'declined'] {
378 for backend in ['reference', 'native', 'public'] {
379 home := os.join_path(base, 'db-' + scenario + '-' + backend)
380 ring := configure(home, server, cert)!
381 homes << home
382 ring.gpg(['--import', expired])!
383 ring.trust(refresh_fpr, 6)!
384 ring.gpg(['--output', os.join_path(home, 'pubring.gpg'), '--export'])!
385 fixture.scenario(scenario, updated_armor, wrong_armor, wrong_key, wrong_fingerprint)
386 mut secure := secure_start(fixture, if scenario == 'wkd-untrusted' {
387 bad_cert
388 } else {
389 cert
390 }, if scenario == 'wkd-untrusted' { bad_key } else { key })!
391 mut result := fixture.observe(probe, home, 'db-' + scenario, base, backend, 'db:refresh') or {
392 secure.close() or { eprintln(err) }
393 return err
394 }
395 secure.close()!
396 results << result
397 }
398 }
399 println(json2.encode(results))
400}
401