Debian Codegraph @

test/verify/check-connection

raw
1 #!/usr/bin/python3 -cimport os, sys; os.execv(os.path.dirname(sys.argv[1]) + "/../common/pywrap", sys.argv)
2
3 #
4 # Copyright (C) 2013 Red Hat, Inc.
5 # SPDX-License-Identifier: LGPL-2.1-or-later
6
7
8 import base64
9 import json
10 import os
11 import re
12 import subprocess
13 import time
14
15 import testlib
16
17
18 class TestConnection(testlib.MachineCase):
19 def setUp(self):
20 super().setUp()
21 self.ws_executable = f"{self.libexecdir}/cockpit-ws"
22
23 def ostree_setup_ws(self):
24 """Overlay cockpit-ws package on OSTree image
25
26 Disable the cockpit/ws container. This is for tests that don't work with the container,
27 and to make sure that overlaying cockpit-ws works as well.
28 """
29 m = self.machine
30 if not m.ostree_image or "bootc" in m.image:
31 return
32
33 # uninstall cockpit/ws container startup script
34 m.execute("rm /etc/systemd/system/cockpit.service")
35 # overlay cockpit-ws rpm
36 m.execute("rpm-ostree install --cache-only /var/tmp/cockpit-ws-*.rpm", timeout=180)
37 m.reboot()
38
39 def assertNoAdminProcessLeaks(self):
40 """Check that machine did not leak any bridges or ssh-agent admin processes"""
41 m = self.machine
42 try:
43 # there may still be user-wide ones like dbus-broker
44 m.execute("while pgrep -au admin '(cockpit|ssh-agent)'; do sleep 0.1; done", timeout=30)
45 except RuntimeError:
46 # show the leaked processes in the assertion
47 self.fail(m.execute("pgrep -au admin '(cockpit|ssh-agent)'"))
48
49 def testBasic(self):
50 m = self.machine
51
52 # always test with the default ws install (container on OSTree, package everywhere else)
53 self.check_basic_with_start_stop(m.start_cockpit, m.stop_cockpit)
54
55 # on OSTree, also check with overlaid cockpit-ws rpm
56 if m.ostree_image:
57 def ws_start():
58 m.execute(r"""
59 mkdir -p /etc/systemd/system/cockpit.service.d/
60 printf "[Service]\nExecStart=\n%s --no-tls" `grep ExecStart= /lib/systemd/system/cockpit.service` \
61 > /etc/systemd/system/cockpit.service.d/notls.conf
62 systemctl daemon-reload
63 systemctl start cockpit.socket""")
64
65 def ws_stop():
66 m.execute("systemctl stop cockpit cockpit.socket")
67
68 self.ostree_setup_ws()
69 # HACK: Getting SELinux errors with just rpm-ostree install; there's a plethora of failures, so just allow them all
70 m.execute("setenforce 0")
71 self.allow_journal_messages('audit.*avc: denied .*')
72 self.check_basic_with_start_stop(ws_start, ws_stop)
73
74 def check_basic_with_start_stop(self, start_cockpit, stop_cockpit):
75 m = self.machine
76 b = self.browser
77 start_cockpit()
78
79 # take cockpit-ws down on the login page
80 b.open("/system")
81 b.wait_visible("#login")
82 b.set_val("#login-user-input", "admin")
83 b.set_val("#login-password-input", "foobar")
84 stop_cockpit()
85 b.click('#login-button')
86 b.wait_text_not('#login-fatal-message', "")
87 start_cockpit()
88 b.reload()
89 b.wait_visible("#login")
90 b.set_val("#login-user-input", "admin")
91 b.set_val("#login-password-input", "foobar")
92 b.click('#login-button')
93 b.enter_page("/system")
94
95 # cookie should not be marked as secure, it's not https
96 cookie = b.cookie("cockpit")
97 self.assertTrue(cookie["httpOnly"])
98 self.assertEqual(cookie["sameSite"], "strict")
99 self.assertFalse(cookie["secure"])
100
101 # take cockpit-ws down on the server page
102 stop_cockpit()
103 b.switch_to_top()
104 b.wait_in_text(".curtains-ct h1", "Disconnected")
105
106 start_cockpit()
107 b.click("#machine-reconnect")
108 b.wait_visible("#login")
109 b.set_val("#login-user-input", "admin")
110 b.set_val("#login-password-input", "foobar")
111
112 # sever the connection on the login page
113 stop_cockpit()
114 b.click('#login-button')
115 b.wait_text_not('#login-fatal-message', "")
116 start_cockpit()
117 b.reload()
118 b.wait_visible("#login")
119 b.set_val("#login-user-input", "admin")
120 b.set_val("#login-password-input", "foobar")
121 b.click('#login-button')
122 b.enter_page("/system")
123
124 # sever the connection on the server page
125 # would be nice to use `firewall-cmd --add-rich-rule`, but firewalld always allows "established" connections
126 m.execute("nft add table ip cockpittest")
127 m.execute("nft add chain ip cockpittest INPUT '{ type filter hook input priority 0; policy accept; }'")
128 m.execute("nft insert rule ip cockpittest INPUT tcp dport 9090 reject")
129
130 try:
131 b.switch_to_top()
132 with b.wait_timeout(90):
133 b.wait_visible(".curtains-ct")
134
135 b.wait_in_text(".curtains-ct h1", "Disconnected")
136 b.wait_in_text('.curtains-ct .pf-v6-c-empty-state__body', "Connection has timed out.")
137 finally:
138 m.execute("nft delete table ip cockpittest")
139
140 b.click("#machine-reconnect")
141 b.enter_page("/system")
142 b.logout()
143
144 # deleted cookie after logout should not be marked as secure, it's not https
145 cookie = b.cookie("cockpit")
146 self.assertEqual(cookie["value"], "deleted")
147 self.assertTrue(cookie["httpOnly"])
148 self.assertFalse(cookie["secure"])
149
150 self.assertNoAdminProcessLeaks()
151
152 if not m.ws_container and not m.ostree_image: # no cockpit-session or r/o file system
153 # damage cockpit-session socket → "Authentication not available"
154 m.execute(f"chmod g-x {self.libexecdir}/cockpit-session")
155 try:
156 m.execute("mv /run/cockpit/session /run/cockpit/session.disabled")
157 b.open("/system")
158 b.try_login()
159 # .. but the login page does not expose the error very specifically
160 b.wait_in_text('#login-error-title', "Authentication failed")
161 finally:
162 m.execute("mv /run/cockpit/session.disabled /run/cockpit/session")
163
164 self.allow_journal_messages("/run/cockpit/session: couldn't connect.*")
165
166 # pretend cockpit-bridge is not installed, expect specific error message
167 m.execute("while B=$(command -v cockpit-bridge); do mv $B ${B}.disabled; done")
168 b.open("/system")
169 b.try_login()
170 b.wait_in_text('#login-error-message', "Install the cockpit-system package")
171 m.execute("while B=$(command -v cockpit-bridge.disabled); do mv $B ${B%.disabled}; done")
172
173 # Lets crash a systemd-controlled process and see if we get a proper backtrace in the logs
174 # This helps with debugging failures in the tests elsewhere
175 m.write("/run/systemd/system/systemd-hostnamed.service.d/core.conf",
176 "[Service]\nLimitCORE=infinity\n")
177 m.execute("""systemctl daemon-reload
178 systemctl restart systemd-hostnamed
179 pkill -e -SEGV systemd-hostnam""")
180 testlib.wait(lambda: m.execute("journalctl -b | grep 'Process.*systemd-hostnam.*of user.*dumped core.'"))
181
182 # Make sure the core dumps exist in the directory, so we can download them
183 cores = m.execute("find /var/lib/systemd/coredump -type f")
184 self.assertNotEqual(cores, "")
185
186 self.allow_core_dumps = True
187 self.allow_journal_messages(".*org.freedesktop.hostname1.*DBus.Error.NoReply.*")
188
189 @testlib.skipWsContainer("cockpit/ws doesn't use systemd units")
190 @testlib.nondestructive
191 def testUnitLifecycle(self):
192 m = self.machine
193
194 def expect_active(unit, is_active):
195 status = m.execute(f"systemctl is-active {unit} || true").strip()
196 self.assertIn(status, ["active", "inactive"])
197 if is_active:
198 self.assertEqual(status, "active", f"{unit} is not active")
199 else:
200 self.assertEqual(status, "inactive", f"{unit} is active")
201
202 def expect_actives(ws_socket, instance_sockets, http_instances, https_instances=0):
203 expect_active("cockpit.socket", ws_socket)
204 # http instances
205 for instance in ["http"]:
206 expect_active(f"cockpit-wsinstance-{instance}.socket", instance_sockets)
207 expect_active(f"cockpit-wsinstance-{instance}.service", instance in http_instances)
208 # number of https instances
209 expect_active("cockpit-wsinstance-https-factory.socket", instance_sockets)
210 for unit_type in ["service", "socket"]:
211 out = m.execute(f"systemctl --no-legend -t {unit_type} list-units cockpit-wsinstance-https@*")
212 count = len(out.strip().splitlines())
213 self.assertEqual(count, https_instances, out)
214 # instance sockets get cleaned up when stopping cockpit.socket or the instances
215 if not ws_socket or not instance_sockets:
216 self.assertEqual(
217 m.execute("test ! -e /run/cockpit/wsinstance/ || ls /run/cockpit/wsinstance/").strip(),
218 "")
219
220 # at the beginning, no cockpit related units are running
221 m.execute("systemctl reset-failed")
222 m.stop_cockpit()
223 expect_actives(ws_socket=False, instance_sockets=False, http_instances=[])
224
225 # http only mode
226
227 m.start_cockpit(tls=False)
228 expect_actives(ws_socket=True, instance_sockets=False, http_instances=[])
229 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent --head http://127.0.0.1:9090"))
230
231 expect_actives(ws_socket=True, instance_sockets=True, http_instances=["http"])
232 self.assertRaises(subprocess.CalledProcessError, m.execute,
233 "curl --silent https://127.0.0.1:9090")
234 self.allow_journal_messages("cockpit-tls: got TLS connection, but our server does not have a certificate/key.*")
235 # c-tls knows it can't do https, and not activate that instance
236 expect_actives(ws_socket=True, instance_sockets=True, http_instances=["http"])
237
238 m.restart_cockpit()
239 expect_actives(ws_socket=True, instance_sockets=True, http_instances=["http"])
240
241 m.stop_cockpit()
242 expect_actives(ws_socket=False, instance_sockets=False, http_instances=[])
243
244 # cleans up also when cockpit-tls crashes or idle-exits, not just by explicit stop request
245 m.start_cockpit(tls=False)
246 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent --head http://127.0.0.1:9090"))
247 m.execute("pkill -e cockpit-tls")
248 expect_actives(ws_socket=True, instance_sockets=False, http_instances=[])
249
250 # and recovers from that
251 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent --head http://127.0.0.1:9090"))
252 expect_actives(ws_socket=True, instance_sockets=True, http_instances=["http"])
253
254 # cleans up instances when killing the DynamicUser helper unit
255 m.start_cockpit(tls=False)
256 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent --head http://127.0.0.1:9090"))
257 expect_actives(ws_socket=True, instance_sockets=True, http_instances=["http"])
258 m.execute("systemctl stop cockpit-wsinstance-socket-user")
259 expect_actives(ws_socket=True, instance_sockets=False, http_instances=[])
260
261 # https mode
262
263 m.start_cockpit(tls=True)
264 expect_actives(ws_socket=True, instance_sockets=False, http_instances=[], https_instances=0)
265
266 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent --head http://127.0.0.1:9090"))
267
268 expect_actives(ws_socket=True, instance_sockets=True, http_instances=["http"], https_instances=0)
269 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent -k --head https://127.0.0.1:9090"))
270 expect_actives(ws_socket=True, instance_sockets=True, http_instances=["http"], https_instances=1)
271
272 m.restart_cockpit()
273 expect_actives(ws_socket=True, instance_sockets=True, http_instances=["http"], https_instances=1)
274
275 m.stop_cockpit()
276 expect_actives(ws_socket=False, instance_sockets=False, http_instances=[], https_instances=0)
277
278 m.start_cockpit(tls=True)
279 expect_actives(ws_socket=True, instance_sockets=False, http_instances=[], https_instances=0)
280 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent --head http://127.0.0.1:9090"))
281
282 expect_actives(ws_socket=True, instance_sockets=True, http_instances=["http"], https_instances=0)
283 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent -k --head https://127.0.0.1:9090"))
284 expect_actives(ws_socket=True, instance_sockets=True, http_instances=["http"], https_instances=1)
285
286 # cleans up also when cockpit-tls crashes or idle-exits, not just by explicit stop request
287 m.execute("pkill -e cockpit-tls")
288 expect_actives(ws_socket=True, instance_sockets=False, http_instances=[], https_instances=0)
289 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent --head http://127.0.0.1:9090"))
290 expect_actives(ws_socket=True, instance_sockets=True, http_instances=["http"], https_instances=0)
291 # next https request after crash doesn't leak an instance
292 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent -k --head https://127.0.0.1:9090"))
293 expect_actives(ws_socket=True, instance_sockets=True, http_instances=["http"], https_instances=1)
294
295 # instance service+socket going away does not confuse cockpit-tls' bookkeeping
296 m.execute("systemctl stop cockpit-wsinstance-https@*.service cockpit-wsinstance-https@*.socket")
297 expect_actives(ws_socket=True, instance_sockets=True, http_instances=["http"], https_instances=0)
298 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent --show-error -k --head https://127.0.0.1:9090"))
299 expect_actives(ws_socket=True, instance_sockets=True, http_instances=["http"], https_instances=1)
300
301 # sockets are inaccessible to users, only to cockpit-tls
302 for s in ["http.sock", "https-factory.sock"]:
303 out = m.execute(f"su -c '! nc -U /run/cockpit/wsinstance/{s} 2>&1 || exit 1' admin")
304 self.assertIn("Permission denied", out)
305
306 @testlib.skipWsContainer("cockpit/ws doesn't use systemd units")
307 @testlib.nondestructive
308 def testHttpsInstanceDoS(self):
309 m = self.machine
310 # prevent generating core dump artifacts
311 orig = m.execute("cat /proc/sys/kernel/core_pattern").strip()
312 m.execute("echo core > /proc/sys/kernel/core_pattern")
313 self.addCleanup(m.execute, f"echo '{orig}' > /proc/sys/kernel/core_pattern")
314 self.addCleanup(m.execute, "systemctl reset-failed")
315 m.start_cockpit(tls=True)
316
317 # some netcat versions need an explicit shutdown option, others default to shutting down and don't have -N
318 n_opt = "-N" if "-N" in m.execute("nc -h 2>&1") else ""
319
320 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent -k --head https://127.0.0.1:9090"))
321
322 # number of https instances is bounded (DoS prevention)
323 # with MaxTasks=200 und 2 threads per ws instance we should have a
324 # rough limit of 100 instances, so at some point curl should start failing
325 m.execute("runuser -u cockpit-wsinstance-socket -- sh -ec 'RC=1; for i in `seq 120`; do "
326 " echo -n $i | nc %s -U /run/cockpit/wsinstance/https-factory.sock;"
327 " curl --silent --head --max-time 5 --unix-socket /run/cockpit/wsinstance/https@$i.sock http://dummy > /dev/null || RC=0; "
328 "done; exit $RC'" % n_opt)
329
330 for type_ in ["socket", "service"]:
331 active = int(m.execute("systemctl --no-legend list-units -t %s --state=active "
332 "'cockpit-wsinstance-https@*' | wc -l" % type_).strip())
333 self.assertGreater(active, 45)
334 self.assertLess(active, 110)
335 failed = int(m.execute("systemctl --no-legend list-units --state=failed 'cockpit-wsinstance-https@*' | wc -l").strip())
336 self.assertGreater(failed, 0)
337 self.assertLess(failed, 75) # services and sockets
338
339 # this can kill ws at all kinds of sensitive moments, often in thread pool code; ignore all of its complaints
340 self.allow_journal_messages(".*cockpit-ws.*")
341 self.allow_journal_messages(".*GLib-GIO.*")
342 self.allow_journal_messages(".*Error creating thread: Resource temporarily unavailable.*")
343 self.allow_journal_messages(".*Failed to check for ssh: Failed to fork.*")
344 # annoying line splits with glib messages in journal
345 self.allow_journal_messages(r"\*\*")
346
347 # initial instance still works
348 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent --show-error -k --head https://127.0.0.1:9090"))
349
350 # can launch new instances after freeing up some old ones
351 m.execute("systemctl stop cockpit-wsinstance-https@30 cockpit-wsinstance-https@31 cockpit-wsinstance-https@32")
352 m.execute(f"echo -n new | nc {n_opt} -U /run/cockpit/wsinstance/https-factory.sock")
353 out = m.execute("curl --silent --show-error --head --unix-socket /run/cockpit/wsinstance/[email protected] http://dummy")
354 self.assertIn("HTTP/1.1 200 OK", out)
355
356 @testlib.nondestructive
357 @testlib.skipBeiboot("beiboot doesn't have certs on the host")
358 def testTls(self):
359 m = self.machine
360 b = self.browser
361
362 def check_tls():
363 m.start_cockpit(tls=True)
364
365 # A normal TLS connection works
366 output = m.execute('openssl s_client -connect 172.27.0.15:9090 2>&1')
367 m.message(output)
368 self.assertIn("DONE", output)
369
370 # c-tls respects crypto-policy: newer Fedora-like OSes use hybrid PQC+EC key exchange by default
371 if (m.image.startswith(("fedora", "rhel", "centos")) and
372 not m.image.startswith(("rhel-9", "centos-9"))):
373 self.assertIn("Negotiated TLS1.3 group: X25519MLKEM", output)
374 else:
375 self.assertNotIn("Negotiated TLS1.3 group", output)
376
377 # has proper keyUsage and SAN (both with sscg and with self-signed)
378 output = m.execute("openssl s_client -showcerts -connect 172.27.0.15:9090 |"
379 "openssl x509 -noout -ext keyUsage,extendedKeyUsage,subjectAltName")
380 # keyUsage
381 self.assertIn("Digital Signature", output)
382 self.assertIn("Key Encipherment", output)
383 # extendedKeyUsage
384 self.assertIn("TLS Web Server Authentication", output)
385 # SAN
386 self.assertIn("IP Address:127.0.0.1", output)
387 self.assertIn("DNS:localhost", output)
388
389 # SSLv3 should not work
390 output = m.execute('openssl s_client -connect 172.27.0.15:9090 -ssl3 2>&1 || true')
391 self.assertNotIn("DONE", output)
392
393 # Some operating systems fail SSL3 on the server side
394 self.assertRegex(output, "Secure Renegotiation IS NOT supported|"
395 "ssl handshake failure|"
396 "[uU]nknown option.* -ssl3|"
397 "null ssl method passed|"
398 "wrong version number")
399
400 # RC4 should not work
401 output = m.execute('! openssl s_client -connect 172.27.0.15:9090 -tls1_2 -cipher RC4 2>&1')
402 self.assertNotIn("DONE", output)
403 self.assertRegex(
404 output, r"no cipher match|no ciphers available|ssl handshake failure|Cipher is \(NONE\)")
405
406 # fails with useful error message with broken certs/keys
407 if not m.ostree_image: # not using systemd unit
408 def check_fail(expected: list[str]):
409 m.start_cockpit(tls=True)
410 m.execute('! openssl s_client -connect 172.27.0.15:9090 2>&1')
411 out = m.execute("! systemctl status cockpit.service")
412 self.assertIn("failed", out)
413 for s in expected:
414 self.assertIn(s, out)
415
416 # missing key
417 orig_key = m.execute("cat /etc/cockpit/ws-certs.d/0-self-signed.key")
418 m.execute("mv /etc/cockpit/ws-certs.d/0-self-signed.key /etc/cockpit/ws-certs.d/key.bak")
419 check_fail(["0-self-signed.key", "No such file or directory"])
420 # broken key
421 m.write("/etc/cockpit/ws-certs.d/0-self-signed.key", "-----BEGIN PRIVATE KEY-----\nnope")
422 check_fail(["/etc/cockpit/ws-certs.d/0-self-signed.cert/.key", "decoding error"])
423 m.execute("mv /etc/cockpit/ws-certs.d/key.bak /etc/cockpit/ws-certs.d/0-self-signed.key")
424 # missing cert; does not stomp over the existing key
425 m.execute("rm /etc/cockpit/ws-certs.d/0-self-signed.cert")
426 check_fail(["Found 0-self-signed.key but no 0-self-signed.cert", "Please remove the key file first"])
427 self.assertEqual(m.execute("cat /etc/cockpit/ws-certs.d/0-self-signed.key"), orig_key)
428 # broken cert
429 m.write("/etc/cockpit/ws-certs.d/0-self-signed.cert", "-----BEGIN CERTIFICATE-----\nnope")
430 check_fail(["/etc/cockpit/ws-certs.d/0-self-signed.cert/.key", "header error"])
431
432 # force cert regeneration: sscg by default
433 m.execute("rm -f /etc/cockpit/ws-certs.d/*")
434 check_tls()
435
436 # direct openssl fallback
437 m.stop_cockpit()
438 m.execute("rm -f /etc/cockpit/ws-certs.d/*")
439 try:
440 sscg = m.execute("command -v sscg").strip()
441 except subprocess.CalledProcessError:
442 # some images (Arch/Fedora CoreOS) don't have sscg; in that case the above already tested direct openssl
443 pass
444 else:
445 try:
446 m.execute(f"mount -o bind /dev/null {sscg}")
447 check_tls()
448 finally:
449 m.execute(f"umount {sscg}")
450
451 # gets along with missing directory
452 m.execute("rm -r /etc/cockpit/ws-certs.d")
453 m.start_cockpit(tls=True)
454 self.assertIn("HTTP/1.1 200 OK", m.execute("curl -k --head https://127.0.0.1:9090"))
455
456 # get along with read-only config directory, as long as certificate exists
457 if not m.ws_container:
458 m.stop_cockpit()
459 try:
460 m.execute("mount -o bind -r /etc/cockpit /etc/cockpit")
461 m.start_cockpit(tls=True)
462 self.assertIn("HTTP/1.1 200 OK", m.execute("curl -k --head https://127.0.0.1:9090"))
463 finally:
464 m.execute("umount /etc/cockpit")
465
466 # Install a certificate chain
467 m.upload(["verify/files/cert-chain.cert", "verify/files/cert-chain.key"], "/etc/cockpit/ws-certs.d")
468
469 def check_cert_chain():
470 # This should also reset the file context
471 m.restart_cockpit()
472 output = m.execute('openssl s_client -connect 172.27.0.15:9090 2>&1')
473 self.assertIn("DONE", output)
474 self.assertRegex(output, "s:/?CN *= *localhost")
475 self.assertRegex(output, "1 s:/?OU *= *Intermediate")
476
477 check_cert_chain()
478
479 # *.crt file also works
480 m.execute("mv /etc/cockpit/ws-certs.d/cert-chain.cert /etc/cockpit/ws-certs.d/cert-chain.crt")
481 check_cert_chain()
482
483 # backwards compat: merged cert+key file also still works with cockpit-tls (but not any more with cockpit-ws/container)
484 if not m.ws_container:
485 m.execute("""cat /etc/cockpit/ws-certs.d/cert-chain.key >> /etc/cockpit/ws-certs.d/cert-chain.crt
486 chmod 640 /etc/cockpit/ws-certs.d/cert-chain.crt
487 rm /etc/cockpit/ws-certs.d/cert-chain.key""")
488 check_cert_chain()
489
490 # certmonger generated certificate; asciibetically later than the above
491 # not all images have certmonger
492 if m.image not in ["fedora-coreos", "arch", "centos-9-bootc"]:
493 hostname = m.execute("hostname --fqdn").strip()
494 m.execute(f"getcert request -f /etc/cockpit/ws-certs.d/monger.cert -k /etc/cockpit/ws-certs.d/monger.key -D {hostname} --ca=local --wait")
495 self.addCleanup(m.execute, "getcert stop-tracking -f /etc/cockpit/ws-certs.d/monger.cert")
496 # cert generation succeeded, and it is being tracked
497 self.assertIn("MONITORING", m.execute("getcert list"))
498 self.assertIn("/etc/cockpit/ws-certs.d/monger.cert",
499 m.execute(f"{self.libexecdir}/cockpit-certificate-ensure --check"))
500 m.restart_cockpit()
501 output = m.execute('openssl s_client -connect 172.27.0.15:9090 2>&1')
502 self.assertIn("DONE", output)
503 self.assertRegex(output, f"CN.*=.*{hostname}")
504 self.assertRegex(output, "i:/?CN.*=.*Local Signing Authority.*")
505
506 # login handler: correct password
507 m.execute("curl -k -c cockpit.jar -s --head --header 'Authorization: Basic {}' https://127.0.0.1:9090/cockpit/login".format(
508 base64.b64encode(b"admin:foobar").decode(), ))
509 headers = m.execute("curl -k --head -b cockpit.jar -s https://127.0.0.1:9090/")
510
511 # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/connect-src
512 #
513 # Note: connect-src 'self' does not resolve to websocket
514 # schemes in all browsers, more info in this issue.
515 #
516 # https://github.com/w3c/webappsec-csp/issues/7
517 #
518 # Make sure we send the explicit `wss://` item until we're absolutely
519 # sure about the browser support situation for `connect-src 'self';`.
520 self.assertIn("wss://127.0.0.1:9090", headers)
521
522 # We want to make sure we're *not* sending any CORS headers.
523 CORS_HEADERS = [
524 # https://en.wikipedia.org/wiki/Cross-origin_resource_sharing#Response_headers
525 'Access-Control-Allow-Credentials',
526 'Access-Control-Expose-Headers',
527 'Access-Control-Max-Age',
528 'Access-Control-Allow-Methods',
529 'Access-Control-Allow-Headers',
530 ]
531 for cors_header in CORS_HEADERS:
532 self.assertNotIn(cors_header, headers)
533
534 # CORP and Frame-Options are also set for dynamic paths
535 self.assertIn("Cross-Origin-Resource-Policy: same-origin", headers)
536 self.assertIn("X-Frame-Options: sameorigin", headers)
537
538 # IPv6 connection
539 self.assertIn("HTTP/1.1 200 OK", m.execute("curl -6 --head http://[::1]:9090"))
540 self.assertIn("HTTP/1.1 200 OK", m.execute("curl -6 -k --head https://[::1]:9090"))
541
542 self.allow_journal_messages(
543 ".*Peer failed to perform TLS handshake",
544 ".*Peer sent fatal TLS alert:.*",
545 ".*invalid base64 data in Basic header",
546 ".*Error performing TLS handshake: No supported cipher suites have been found.",
547 ".*Error performing TLS handshake: Could not negotiate a supported cipher suite.")
548
549 # check the Debian smoke test
550 m.upload(["../tools/debian/tests/smoke"], "/tmp")
551 m.execute("/tmp/smoke")
552
553 self.login_and_go("/system", tls=True)
554 cookie = b.cookie("cockpit")
555 # cookie should be marked as secure
556 self.assertTrue(cookie["httpOnly"])
557 self.assertTrue(cookie["secure"])
558 self.assertEqual(cookie["sameSite"], "strict")
559 # same after logout
560 b.logout()
561 cookie = b.cookie("cockpit")
562 self.assertEqual(cookie["value"], "deleted")
563 self.assertTrue(cookie["httpOnly"])
564 self.assertTrue(cookie["secure"])
565 self.assertEqual(cookie["sameSite"], "strict")
566
567 # http on localhost should not redirect to https
568 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --head http://127.0.0.1:9090"))
569 # http on other IP should redirect to https
570 output = m.execute("curl --head http://172.27.0.15:9090")
571 self.assertIn("HTTP/1.1 301 Moved Permanently", output)
572 self.assertIn("Location: https://172.27.0.15:9090/", output)
573 # enable AllowUnencrypted, this disables redirect
574 m.write("/etc/cockpit/cockpit.conf", "[WebService]\nAllowUnencrypted=true")
575 m.restart_cockpit()
576 # now it should not redirect
577 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --head http://127.0.0.1:9090"))
578 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --head http://172.27.0.15:9090"))
579
580 @testlib.nondestructive
581 @testlib.skipWsContainer("ws container doesn't have certs on the host")
582 @testlib.skipImage("no PQC support", "arch", "debian*", "ubuntu*", "rhel-9*", "centos-9*")
583 def testPQC(self):
584 m = self.machine
585 b = self.browser
586
587 # note: deploying this is NOT RECOMMENDED! Production systems should use a hybrid PQC + EC certificate,
588 # but that is not specified/supported yet as of Jan 2026.
589 # See https://issues.redhat.com/browse/RHELMISC-11973
590 m.execute("sscg --key-type=mldsa --cert-key-file /etc/cockpit/ws-certs.d/mldsa.key "
591 "--cert-file /etc/cockpit/ws-certs.d/mldsa.crt "
592 "--ca-file /etc/cockpit/ws-certs.d/mldsa-ca.crt "
593 "--subject-alt-name localhost "
594 "--subject-alt-name IP:172.27.0.15 "
595 "--subject-alt-name IP:127.0.0.2")
596
597 m.start_cockpit(tls=True)
598
599 # Check PQC signature and KEX with curl, can't do that with browser (no API)
600 output = m.execute('openssl s_client -CAfile /etc/cockpit/ws-certs.d/mldsa-ca.crt -connect 172.27.0.15:9090 2>&1')
601 self.assertIn("DONE", output)
602 self.assertIn("Peer signature type: mldsa44", output)
603 self.assertIn("Negotiated TLS1.3 group: X25519MLKEM", output)
604
605 # TODO: this does not currently work with Firefox, Firefox doesn't accept MLKEM certificates
606 # see discussion in https://issues.redhat.com/browse/RHELMISC-11973
607 if b.browser == "firefox":
608 self.assertRaises(testlib.Error, self.login_and_go, "/system", tls=True)
609 self.allow_journal_messages(".*gnutls_handshake failed: No supported cipher suites.*")
610 else:
611 self.login_and_go("/system", tls=True)
612 b.wait_visible("#overview")
613
614 @testlib.nondestructive
615 def testConfigOrigins(self):
616 m = self.machine
617
618 # Test default behavior without explicit Origins= configuration
619
620 headers = {
621 'Connection': 'Upgrade',
622 'Upgrade': 'websocket',
623 'Host': 'localhost:9090',
624 'Sec-Websocket-Key': '3sc2c9IzwRUc3BlSIYwtSA==',
625 'Sec-Websocket-Version': "13"
626 }
627
628 # https connection tests
629 m.start_cockpit(tls=True)
630
631 # good: https:// origin on https connection
632 headers['Origin'] = "https://localhost:9090"
633 output = m.curl('-f', '-N', '-k', 'https://localhost:9090/cockpit/socket', headers=headers)
634 self.assertIn('"no-session"', output)
635
636 # bad: http:// origin on https connection
637 headers['Origin'] = "http://localhost:9090"
638 with self.assertRaises(subprocess.CalledProcessError):
639 m.curl('-f', '-N', '-k', 'https://localhost:9090/cockpit/socket', headers=headers)
640 self.allow_journal_messages("received request from bad Origin: .*")
641
642 # good: https:// origin on https connection with IPv4
643 headers['Host'] = '127.0.0.1:9090'
644 headers['Origin'] = "https://127.0.0.1:9090"
645 output = m.curl('-f', '-N', '-k', 'https://127.0.0.1:9090/cockpit/socket', headers=headers)
646 self.assertIn('"no-session"', output)
647
648 # bad: http:// origin on https connection with IPv4
649 headers['Origin'] = "http://127.0.0.1:9090"
650 with self.assertRaises(subprocess.CalledProcessError):
651 m.curl('-f', '-N', '-k', 'https://127.0.0.1:9090/cockpit/socket', headers=headers)
652
653 # good: https:// origin on https connection with IPv6
654 headers['Host'] = '[::1]:9090'
655 headers['Origin'] = "https://[::1]:9090"
656 output = m.curl('-f', '-N', '-k', '-6', 'https://[::1]:9090/cockpit/socket', headers=headers)
657 self.assertIn('"no-session"', output)
658
659 # bad: http:// origin on https connection with IPv6
660 headers['Origin'] = "http://[::1]:9090"
661 with self.assertRaises(subprocess.CalledProcessError):
662 m.curl('-f', '-N', '-k', '-6', 'https://[::1]:9090/cockpit/socket', headers=headers)
663
664 # http connection tests
665 m.stop_cockpit()
666 m.start_cockpit(tls=False)
667
668 # good: http:// origin on http connection
669 headers['Host'] = 'localhost:9090'
670 headers['Origin'] = "http://localhost:9090"
671 output = m.curl('-f', '-N', 'http://localhost:9090/cockpit/socket', headers=headers)
672 self.assertIn('"no-session"', output)
673
674 # bad: https:// origin on http connection
675 headers['Origin'] = "https://localhost:9090"
676 with self.assertRaises(subprocess.CalledProcessError):
677 m.curl('-f', '-N', 'http://localhost:9090/cockpit/socket', headers=headers)
678
679 self.allow_journal_messages("Received invalid handshake request from the client")
680
681 # good: http:// origin on http connection with IPv4
682 headers['Host'] = '127.0.0.1:9090'
683 headers['Origin'] = "http://127.0.0.1:9090"
684 output = m.curl('-f', '-N', 'http://127.0.0.1:9090/cockpit/socket', headers=headers)
685 self.assertIn('"no-session"', output)
686
687 # bad: https:// origin on http connection with IPv4
688 headers['Origin'] = "https://127.0.0.1:9090"
689 with self.assertRaises(subprocess.CalledProcessError):
690 m.curl('-f', '-N', 'http://127.0.0.1:9090/cockpit/socket', headers=headers)
691
692 # good: http:// origin on http connection with IPv6
693 headers['Host'] = '[::1]:9090'
694 headers['Origin'] = "http://[::1]:9090"
695 output = m.curl('-f', '-N', '-6', 'http://[::1]:9090/cockpit/socket', headers=headers)
696 self.assertIn('"no-session"', output)
697
698 # bad: https:// origin on http connection with IPv6
699 headers['Origin'] = "https://[::1]:9090"
700 with self.assertRaises(subprocess.CalledProcessError):
701 m.curl('-f', '-N', '-6', 'http://[::1]:9090/cockpit/socket', headers=headers)
702
703 # Test explicit Origins= configuration; IPv6 address requires escaping due to fnmatch()
704
705 m.stop_cockpit()
706 m.write("/etc/cockpit/cockpit.conf",
707 r"""[WebService]
708 Origins = http://origin-one:9090 http://localhost:9090 http://*.origin-two:9090 http://\[::1\]:*
709 """)
710 m.start_cockpit()
711 headers['Origin'] = 'http://origin-one:9090'
712 output = m.curl('-f', '-N', 'http://localhost:9090/cockpit/socket', headers=headers)
713 self.assertIn('"no-session"', output)
714
715 # Test wildcard functionality of Origin Matching
716 headers['Origin'] = "http://wildcard.origin-two:9090"
717 output = m.curl('-f', '-N', 'http://localhost:9090/socket', headers=headers)
718 self.assertIn('"no-session"', output)
719
720 # The socket should also answer at /socket
721 output = m.curl('-f', '-N', 'http://localhost:9090/socket', headers=headers)
722 self.assertIn('"no-session"', output)
723
724 # Test IPv6 wildcard pattern (escaped brackets, wildcard port)
725 headers['Host'] = '[::1]:9090'
726 headers['Origin'] = "http://[::1]:9090"
727 output = m.curl('-f', '-N', '-6', 'http://[::1]:9090/cockpit/socket', headers=headers)
728 self.assertIn('"no-session"', output)
729
730 self.allow_journal_messages('peer did not close io when expected')
731
732 @testlib.skipWsContainer("cockpit/ws doesn't have certs on the host")
733 @testlib.nondestructive
734 def test100YearsCert(self):
735 m = self.machine
736
737 selfsign = '/etc/cockpit/ws-certs.d/0-self-signed.cert'
738 helper = f'{self.libexecdir}/cockpit-certificate-helper'
739 ensure = f'{self.libexecdir}/cockpit-certificate-ensure'
740
741 # Ensure things are as we expect them to be
742 m.execute('rm -f /etc/cockpit/ws-certs.d/*')
743 m.execute(f'grep DAYS=395 {helper}')
744
745 # Generate a 100 years expiry certificate
746 self.sed_file('s/DAYS=395/DAYS=36500/', helper)
747 m.execute(f'grep DAYS=36500 {helper}') # double-check
748 m.execute(ensure)
749
750 # Verify the expiry date to be in the far-future. This is a bit
751 # annoying due to the date format OpenSSL uses (which Python can't
752 # trivially parse) and the question of locales
753 expires = m.execute(f'date -d "$(openssl x509 -enddate -noout < {selfsign} | cut -f2 -d=)" +%s')
754 self.assertGreater(int(expires), time.time() + 99 * 365 * 24 * 60 * 60)
755
756 # Put things back: avoid problematic multiple invocations of .sed_file()
757 m.execute(f'sed -i s/DAYS=36500/DAYS=395/ {helper}')
758 m.execute(f'grep DAYS=395 {helper}') # double-check
759
760 # Run ensure again and make sure we get a new certificate
761 m.execute('touch /tmp/timestamp')
762 m.execute(ensure)
763 m.execute(f'test {selfsign} -nt /tmp/timestamp')
764 m.execute('rm /tmp/timestamp')
765
766 # Check that the expiry is less than 420 days
767 # See https://github.com/sgallagher/sscg/pull/28 for why 420
768 expires = m.execute(f'date -d "$(openssl x509 -enddate -noout < {selfsign} | cut -f2 -d=)" +%s')
769 self.assertLess(int(expires), time.time() + 420 * 24 * 60 * 60)
770
771 # Run ensure again and make sure we *don't* get a new certificate
772 m.execute('touch /tmp/timestamp')
773 m.execute(ensure)
774 m.execute(f'test ! {selfsign} -nt /tmp/timestamp')
775 m.execute('rm /tmp/timestamp')
776
777 @testlib.skipWsContainer("cockpit/ws doesn't use systemd units")
778 @testlib.nondestructive
779 def testSocket(self):
780 m = self.machine
781
782 # non-admin user
783 m.execute("useradd bob")
784
785 # enable no-password login for 'admin' and 'bob'
786 m.execute("passwd -d admin")
787 m.execute("passwd -d bob")
788
789 if "opensuse" in m.image:
790 self.write_file("/etc/ssh/sshd_config", "PermitEmptyPasswords yes")
791 m.execute(self.restart_sshd)
792 else:
793 self.sed_file('$ a\\\nPermitEmptyPasswords yes', '/etc/ssh/sshd_config', self.restart_sshd)
794
795 def assertInOrNot(string: str, result: str, *, expected: bool) -> None:
796 if expected:
797 self.assertIn(string, result)
798 else:
799 self.assertNotIn(string, result)
800
801 def checkMotdForUser(string: str, user: str, *, expected: bool) -> None:
802 result = m.execute(f"ssh -o StrictHostKeyChecking=no -n {user}@localhost")
803 assertInOrNot(string, result, expected=expected)
804
805 def checkMotdContent(string: str, *, expected: bool = True) -> None:
806 # Needs https://github.com/linux-pam/linux-pam/pull/292 (or PAM 1.5.0)
807 old_pam = m.image.startswith('rhel-8-')
808
809 # check issue (should be exactly the same as motd)
810 assertInOrNot(string, m.execute("cat /etc/issue.d/cockpit.issue"), expected=expected)
811
812 # check motd as 'root' (via cat) and 'admin' and 'bob' (via ssh)
813 assertInOrNot(string, m.execute("cat /etc/motd.d/cockpit"), expected=expected)
814 # opensuse has permissions that block non root users from reading /etc/issue.d and motd.d
815 if "opensuse" not in m.image:
816 checkMotdForUser(string, expected=expected, user='admin')
817 checkMotdForUser(string, expected=old_pam and expected, user='bob')
818
819 m.stop_cockpit()
820 checkMotdContent('systemctl')
821 checkMotdContent(':9090/', expected=False)
822 m.start_cockpit()
823
824 checkMotdContent(':9090/')
825 checkMotdContent('systemctl', expected=False)
826 m.execute("systemctl stop cockpit.socket")
827
828 # Change port according to documentation: https://docs.cockpit-project.org/cockpit-guide/latest/guide/listen.html
829 m.execute('! selinuxenabled || semanage port -m -t websm_port_t -p tcp 443')
830 self.write_file("/etc/systemd/system/cockpit.socket.d/listen.conf",
831 "[Socket]\nListenStream=\nListenStream=/run/cockpit/sock\nListenStream=443",
832 post_restore_action="systemctl stop cockpit.socket; systemctl daemon-reload")
833
834 checkMotdContent('systemctl')
835 checkMotdContent(':9090/', expected=False)
836 checkMotdContent(':443/', expected=False)
837 m.start_cockpit(tls=True)
838
839 checkMotdContent('systemctl', expected=False)
840 checkMotdContent(':9090/', expected=False)
841 checkMotdContent(':443/')
842
843 output = m.execute('curl -k https://localhost 2>&1 || true')
844 self.assertIn('Loading...', output)
845 output = m.execute('curl -k --unix-socket /run/cockpit/sock https://dummy 2>&1 || true')
846 self.assertIn('Loading...', output)
847
848 output = m.execute('curl -k https://localhost:9090 2>/dev/null || echo $?')
849 self.assertIn('7', output.strip())
850
851 self.allow_journal_messages(".*Peer failed to perform TLS handshake")
852
853 @testlib.skipWsContainer("no cockpit-ws package with cockpit/ws container")
854 def testWsPackage(self):
855 m = self.machine
856
857 # On RHEL-8 SSH allows password root login by default, so Cockpit does too.
858 ROOT_LOGIN_ENABLED = ['rhel-8']
859 root_login_disallowed = not any(m.image.startswith(img) for img in ROOT_LOGIN_ENABLED)
860
861 if m.image.startswith("debian") or m.image.startswith("ubuntu"):
862 # clean up debug symbols, they get in the way of upgrading
863 m.execute("dpkg --purge cockpit-ws-dbgsym")
864 elif m.image.startswith("rhel"):
865 # subscription-manager-cockpit depends on cockpit-ws, and cockpit.rpm metapackage depends on sub-man on RHEL
866 m.execute("rpm --erase cockpit subscription-manager-cockpit")
867
868 def install():
869 if m.image.startswith("debian") or m.image.startswith("ubuntu"):
870 m.execute("dpkg --install /var/tmp/build/cockpit-ws_*.deb")
871 elif m.image == "arch":
872 m.execute("pacman -U --noconfirm /var/tmp/build/cockpit-*.pkg.tar.zst")
873 else:
874 m.execute("if rpm -q cockpit-ws; then rpm --verify cockpit-ws; fi")
875 m.execute("rpm --upgrade --force /var/tmp/build/cockpit-ws-*.rpm")
876 m.execute("rpm --verify cockpit-ws")
877
878 def remove():
879 if m.image.startswith("debian") or m.image.startswith("ubuntu"):
880 m.execute("dpkg --purge cockpit cockpit-ws")
881 elif m.image == "arch":
882 m.execute("pacman -Rdd --noconfirm cockpit")
883 elif m.image.startswith("rhel"):
884 m.execute("rpm --erase cockpit-ws")
885 else:
886 m.execute("rpm --erase cockpit cockpit-ws")
887
888 # clean install sets up dynamic motd/issue symlink and pam disallowed users.
889 self.assertIn('Activate the web console', m.execute("cat /etc/motd.d/cockpit"))
890 self.assertIn('Activate the web console', m.execute("cat /etc/issue.d/cockpit.issue"))
891 if root_login_disallowed:
892 self.assertIn('root', m.execute("cat /etc/cockpit/disallowed-users"))
893 # remove disallowed-users to simulate an upgrade where we did not have this file yet.
894 m.execute("rm /etc/cockpit/disallowed-users")
895
896 # package upgrade keeps them
897 install()
898 self.assertIn('Activate the web console', m.execute("cat /etc/motd.d/cockpit"))
899 self.assertIn('Activate the web console', m.execute("cat /etc/issue.d/cockpit.issue"))
900 # disallowed-users should not exists now as this is an upgrade, except on Arch
901 if m.image != "arch":
902 m.execute("test ! -e /etc/cockpit/disallowed-users")
903 m.execute("echo 'root' > /etc/cockpit/disallowed-users")
904 else:
905 m.execute("test -e /etc/cockpit/disallowed-users")
906
907 # HACK: On Arch Linux the symlink is overwritten, bug?
908 if m.image != "arch":
909 # manual change/removal is respected on upgrade
910 m.execute("ln -sf /dev/null /etc/motd.d/cockpit; rm /etc/issue.d/cockpit.issue")
911 install()
912 self.assertEqual(m.execute("readlink /etc/motd.d/cockpit").strip(), "/dev/null")
913 m.execute("test ! -e /etc/issue.d/cockpit.issue")
914
915 # removing the package cleans up the links
916 remove()
917 m.execute("test ! -e /etc/motd.d/cockpit")
918 m.execute("test ! -e /etc/issue.d/cockpit.issue")
919 m.execute("test ! -e /etc/cockpit/disallowed-users")
920
921 # fresh install (most of our test images have cockpit-ws preinstalled, so the first test above does not cover that)
922 install()
923 # verify that we installed relative links in the new package
924 self.assertEqual(m.execute("readlink /etc/motd.d/cockpit").strip(), "../../run/cockpit/issue")
925 self.assertEqual(m.execute("readlink /etc/issue.d/cockpit.issue").strip(), "../../run/cockpit/issue")
926 if root_login_disallowed:
927 self.assertIn('root', m.execute("cat /etc/cockpit/disallowed-users"))
928
929 @testlib.skipWsContainer("no cockpit-ws binary with cockpit/ws container")
930 @testlib.nondestructive
931 def testCommandline(self):
932 m = self.machine
933
934 # Large requests are processed correctly with plain HTTP through cockpit-tls
935 m.start_cockpit(tls=True)
936 large_headers = {'Authorization': f'Negotiate {1:07000}'}
937 self.assertIn('id="login"', m.curl('http://localhost:9090/', headers=large_headers))
938
939 # Large requests are processed correctly with TLS through cockpit-tls
940 self.assertIn('id="login"', m.curl('-k', 'https://localhost:9090/', headers=large_headers))
941 m.stop_cockpit()
942
943 m.execute("rm -f /etc/cockpit/ws-certs.d/* /etc/cockpit/cockpit.conf")
944 m.write("/etc/cockpit/cockpit.conf", "[WebService]\nLoginTitle = A Custom Title\n")
945
946 pid = m.spawn(f"{self.ws_executable} --port 9000 --address 127.0.0.1", "cockpit-ws.log")
947 self.addCleanup(m.execute, f"kill {pid}")
948
949 # The port may not be available immediately, so wait for it
950 testlib.wait(lambda: 'A Custom Title' in m.curl('http://localhost:9000/'))
951
952 # listens on localhost only
953 output = m.execute('curl -s -S http://172.27.0.15:9000/ 2>&1 || echo $?')
954 self.assertIn('7', output.strip())
955
956 # Large requests are processed correctly
957 self.assertIn('A Custom Title', m.curl('http://localhost:9000/', headers=large_headers))
958
959 # unsupported HTTP method
960 self.assertIn("HTTP/1.1 405 Method Not Allowed",
961 m.execute('curl -k --verbose -X PATCH http://localhost:9000/ 2>&1'))
962
963 # no body with HEAD request
964 out = m.execute('curl -k --head http://localhost:9000/')
965 self.assertIn("HTTP/1.1 200", out)
966 self.assertNotIn("<html>", out)
967
968 # robots.txt from any directory and with/without TLS, and without auth
969 expected = "User-agent: *\nDisallow: /\n"
970 self.assertEqual(m.execute("curl http://localhost:9000/robots.txt"), expected)
971 self.assertEqual(m.execute("curl http://localhost:9000/somedir/robots.txt"), expected)
972
973 @testlib.nondestructive
974 def testHeadRequest(self):
975 m = self.machine
976 m.start_cockpit()
977
978 # static handler
979 headers = m.execute("curl -s --head http://172.27.0.15:9090/cockpit/static/login.html")
980 self.assertIn("HTTP/1.1 200 OK\r\n", headers)
981 self.assertIn("Content-Type: text/html\r\n", headers)
982 self.assertIn("Cross-Origin-Resource-Policy: same-origin\r\n", headers)
983 self.assertIn("X-Frame-Options: sameorigin\r\n", headers)
984 # login.html is not always accessible as a file (e.g. on CoreOS), so just assert a reasonable content length
985 self.assertIn("Content-Length: ", headers)
986 length = int(headers.split('Content-Length: ', 1)[1].split()[0])
987 self.assertGreater(length, 5000)
988 self.assertLess(length, 100000)
989
990 # login handler: wrong password
991 headers = m.execute("curl -s --head --header 'Authorization: Basic {}' http://172.27.0.15:9090/cockpit/login".format(
992 base64.b64encode(b"admin:hahawrong").decode()))
993 self.assertRegex(headers, r"HTTP/1.1 (401 Authentication failed|403 Permission denied)\r\n")
994 self.assertNotIn("Set-Cookie:", headers)
995
996 # login handler: correct password
997 headers = m.execute("curl -s --head --header 'Authorization: Basic {}' http://172.27.0.15:9090/cockpit/login".format(
998 base64.b64encode(b"admin:foobar").decode()))
999 self.assertIn("HTTP/1.1 200 OK\r\n", headers)
1000 self.assertIn("Set-Cookie: cockpit", headers)
1001
1002 # socket handler; this should refuse HEAD (as it makes little sense on sockets), so 404
1003 headers = m.execute("curl -s --head http://172.27.0.15:9090/cockpit/socket")
1004 self.assertIn("HTTP/1.1 404 Not Found\r\n", headers)
1005
1006 # external channel handler; unauthenticated, thus 404
1007 headers = m.execute("curl -s --head http://172.27.0.15:9090/cockpit+123/channel/foo")
1008 self.assertIn("HTTP/1.1 404 Not Found\r\n", headers)
1009
1010 @testlib.skipWsContainer("ssh root login not allowed")
1011 @testlib.skipBrowser("Chromium 133 does not survive large downloads, https://issues.chromium.org/issues/399131925",
1012 "chromium")
1013 @testlib.nondestructive
1014 def testFlowControlDownload(self):
1015 m = self.machine
1016 b = self.browser
1017
1018 self.login_and_go("/playground/speed", user="root", enable_root_login=True)
1019 b.wait_text_not("#pid", "")
1020 pid = b.text("#pid")
1021
1022 b.set_val("#read-path", "/dev/vda")
1023 b.click("#read-sideband")
1024
1025 b.wait_text_not("#speed", "")
1026 time.sleep(20)
1027 output = m.execute(f"cat /proc/{pid}/statm")
1028 rss = int(output.split(" ")[0])
1029
1030 # This fails when flow control is not present
1031 self.assertLess(rss, 250000)
1032
1033 @testlib.nondestructive
1034 @testlib.skipBrowser("Chromium 133 does not survive large uploads, https://issues.chromium.org/issues/399131925",
1035 "chromium")
1036 def testFlowControlUpload(self):
1037 m = self.machine
1038 b = self.browser
1039
1040 self.login_and_go("/playground/speed")
1041 self.addCleanup(m.execute, "rm -f /tmp/spawninput")
1042 b.click("#spawn-input")
1043
1044 b.wait_text_not("#speed", "")
1045 with b.wait_timeout(60):
1046 b.wait_text("#spawn-input-result", "success")
1047
1048 self.assertEqual(int(m.execute("stat -c %s /tmp/spawninput")), 65536000)
1049 self.assertEqual(m.execute("tail -c10 /tmp/spawninput").strip(), "a" * 10)
1050
1051 @testlib.skipWsContainer("no cockpit-ws binary with cockpit/ws container")
1052 @testlib.nondestructive
1053 def testLocalSession(self):
1054 m = self.machine
1055
1056 def check_session():
1057 m.wait_for_cockpit_running('localhost', 9090)
1058 b = self.browser
1059 # session works directly, no login page
1060 b.open("/")
1061 b.wait_visible('#content')
1062 b.enter_page("/system")
1063 b.switch_to_top()
1064
1065 # disconnect browser, and wait past ws session timeout
1066 b.kill()
1067 time.sleep(17) # cockpit_ws_service_idle plus a bit
1068 self.browser = self.new_browser()
1069 b = self.browser
1070
1071 # can start new session
1072 b.open("/")
1073 b.wait_visible('#content')
1074
1075 # shut it down, wait until it is gone
1076 m.execute("pkill cockpit-ws; while pgrep -a cockpit-ws; do sleep 1; done")
1077 b.wait_in_text(".curtains-ct", "Disconnected")
1078
1079 # start ws with --local-session, let it spawn bridge; ensure that this works without /etc/cockpit/
1080 m.stop_cockpit()
1081 m.spawn("su -l -c 'G_MESSAGES_DEBUG=all XDG_CONFIG_DIRS=/usr/local %s --no-tls "
1082 "--local-session=cockpit-bridge' admin" % self.ws_executable,
1083 "cockpit-ws-local")
1084 check_session()
1085
1086 # start ws with --local-session and existing running bridge
1087 self.write_file("/tmp/local.sh", f"""#!/bin/bash -eu
1088 coproc env G_MESSAGES_DEBUG=all cockpit-bridge
1089 export G_MESSAGES_DEBUG=all
1090 export XDG_CONFIG_DIRS=/usr/local
1091 {self.ws_executable} --no-tls --local-session=- <&${{COPROC[0]}} >&${{COPROC[1]}}
1092 """, perm="755")
1093 m.spawn("su -l -c /tmp/local.sh admin", "local.sh")
1094 check_session()
1095
1096 self.allow_journal_messages("couldn't register polkit authentication agent.*")
1097
1098 @testlib.skipWsContainer("no cockpit-ws binary with cockpit/ws container")
1099 @testlib.skipImage("Kernel does not allow user namespaces", "debian-*")
1100 @testlib.nondestructive
1101 def testCockpitDesktop(self):
1102 m = self.machine
1103 m.stop_cockpit()
1104
1105 cases = [(['/cockpit/@localhost/system/index.html', 'system', 'system/index', 'system/'],
1106 ['id="overview"']
1107 ),
1108 (['/cockpit/@localhost/network/firewall.html', 'network/firewall'],
1109 ['div id="firewall"', 'script src="firewall.js"']
1110 ),
1111 (['/cockpit/@localhost/playground/react-patterns.html', 'playground/react-patterns'],
1112 ['script src="react-patterns.js"']
1113 ),
1114 # no ssh host
1115 (['/cockpit/@localhost/manifests.json'],
1116 ['"system"', '"Overview"']
1117 ),
1118 # remote ssh host
1119 (['/cockpit/@localhost/manifests.json test1@localhost'],
1120 ['"system"', '"Overview"', '"HACK"']
1121 )
1122 ]
1123
1124 # prepare fake ssh target; to verify that we really use that, fake dashboard manifest
1125 m.execute("""useradd test1
1126 [ -f ~admin/.ssh/id_rsa ] || su -c "ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa" admin
1127 mkdir -p ~test1/.ssh ~test1/.local/share/cockpit/dashboard
1128 echo '{ "version": "42", "dashboard": { "index": { "label": "HACK" } } }' > ~test1/.local/share/cockpit/dashboard/manifest.json
1129 cp ~admin/.ssh/id_rsa.pub ~test1/.ssh/authorized_keys
1130 ssh-keyscan localhost >> ~admin/.ssh/known_hosts
1131 chown admin:admin ~admin/.ssh/known_hosts
1132 chown -R test1:test1 ~test1
1133 su -c "ssh test1@localhost cockpit-bridge --packages" admin | grep -q test1.*dashboard # validate setup
1134 """)
1135
1136 for (pages, asserts) in cases:
1137 for page in pages:
1138 m.execute(f"""su -l -c 'BROWSER="curl --silent --compressed -o /tmp/out.html" {self.libexecdir}/cockpit-desktop {page}' admin""",
1139 timeout=10)
1140
1141 out = m.execute("cat /tmp/out.html")
1142 for a in asserts:
1143 self.assertIn(a, out)
1144
1145 self.assertNoAdminProcessLeaks()
1146
1147 # cockpit-desktop can start a privileged bridge through polkit
1148 # we don't have an agent, so just allow the privilege without interactive authentication
1149 if m.image == "arch":
1150 self.write_file("/etc/polkit-1/rules.d/test.rules", r"""
1151 polkit.addRule(function(action, subject) {
1152 if (action.id == "org.cockpit-project.cockpit.root-bridge" && subject.user == "admin")
1153 return polkit.Result.YES;
1154 }); """)
1155 else:
1156 self.write_file("/etc/polkit-1/localauthority/50-local.d/test.pkla", r"""
1157 [Testing without an agent]
1158 Identity=unix-user:admin
1159 Action=org.cockpit-project.cockpit.root-bridge
1160 ResultAny=yes
1161 ResultInactive=yes
1162 ResultActive=yes""")
1163
1164 self.write_file("/tmp/browser.sh", """#!/bin/sh -e
1165 curl --silent --compressed -o /tmp/out.html "$@"
1166 # wait until privileged bridge starts
1167 until pgrep -f '^(/usr/[^ ]+/[^ /]*python[^ /]* )?/usr/bin/cockpit-bridge'; do sleep 1; done
1168 """)
1169 m.execute("chmod 755 /tmp/browser.sh")
1170 m.execute(f"su -l -c 'BROWSER=/tmp/browser.sh {self.libexecdir}/cockpit-desktop system' admin", timeout=10)
1171 self.assertIn('id="overview"', m.execute("cat /tmp/out.html"))
1172
1173 self.assertNoAdminProcessLeaks()
1174
1175 self.allow_journal_messages("couldn't register polkit authentication agent.*")
1176 self.allow_journal_messages("Refusing to render service to dead parents.")
1177 self.allow_journal_messages(".*No authentication agent found.*")
1178 self.allow_journal_messages(".*Peer failed to perform TLS handshake.*")
1179 self.allow_journal_messages(r".*cannot reauthorize identity\(s\): unix-user:.*")
1180 self.allow_journal_messages("admin: Executing command .*COMMAND=.*cockpit-bridge --privileged.*")
1181
1182 @testlib.skipBeiboot("test does not make sense in beiboot mode")
1183 def testReverseProxy(self):
1184 m = self.machine
1185 b = self.browser
1186
1187 self.ostree_setup_ws()
1188
1189 # set up a poor man's reverse TLS proxy with socat
1190 m.upload(["../test/data/mock-server.crt", "../test/data/mock-server.key"], "/tmp")
1191 m.spawn("socat OPENSSL-LISTEN:9090,reuseaddr,fork,cert=/tmp/mock-server.crt,"
1192 "key=/tmp/mock-server.key,verify=0 TCP:localhost:9099",
1193 "socat-tls.log")
1194
1195 # and another proxy for plain http
1196 m.spawn("socat TCP-LISTEN:9091,reuseaddr,fork TCP:localhost:9099", "socat.log")
1197
1198 # ws with plain --no-tls should fail after login with mismatching Origin (expected http, got https)
1199 m.execute("systemctl start cockpit-session.socket")
1200 m.spawn(f"runuser -u cockpit-session-socket -- {self.ws_executable} --no-tls -p 9099",
1201 "ws-notls.log")
1202 m.wait_for_cockpit_running(tls=True)
1203
1204 b.open(f"https://{b.address}:{b.port}/system")
1205 b.wait_visible("#login")
1206 b.set_val("#login-user-input", "admin")
1207 b.set_val("#login-password-input", "foobar")
1208 b.click('#login-button')
1209
1210 b.wait_text(".early-failure .pf-v6-c-empty-state__title", "Connection failed")
1211 b.wait_in_text(".early-failure ", "unexpected error while connecting to the machine")
1212
1213 testlib.wait(lambda: m.execute("grep 'received request from bad Origin' /var/log/ws-notls.log"))
1214
1215 # sanity check: unencrypted http through SSL proxy does not work
1216 m.execute("! curl http://localhost:9090")
1217
1218 # does not redirect to https (through plain http proxy)
1219 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent --head http://127.0.0.1:9091"))
1220 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent --head http://172.27.0.15:9091"))
1221
1222 m.execute("pkill -e cockpit-ws; while pgrep -a cockpit-ws; do sleep 1; done")
1223 # this page failure is reeally noisy
1224 self.allow_journal_messages(".*No authentication agent found.*")
1225 self.allow_journal_messages("couldn't register polkit authentication agent.*")
1226 self.allow_journal_messages("received request from bad Origin.*")
1227 self.allow_journal_messages(".*invalid handshake.*")
1228 self.allow_browser_errors(".*received unsupported version in init message.*")
1229 self.allow_browser_errors(".*received message before init.*")
1230 self.allow_browser_errors("Error reading machine id")
1231
1232 # ws with --for-tls-proxy accepts only https origins, thus should work
1233 m.spawn(f"runuser -u cockpit-session-socket -- {self.ws_executable} --for-tls-proxy -p 9099 -a 127.0.0.1",
1234 "ws-fortlsproxy.log")
1235 m.wait_for_cockpit_running(tls=True)
1236 # Firefox does not handle connection interruptions well, retry once when opening fails.
1237 try:
1238 b.open(f"https://{b.address}:{b.port}/system")
1239 except testlib.Error as exc:
1240 if 'NS_ERROR' in str(exc):
1241 b.open(f"https://{b.address}:{b.port}/system")
1242
1243 b.wait_visible("#login")
1244 b.set_val("#login-user-input", "admin")
1245 b.set_val("#login-password-input", "foobar")
1246 b.click('#login-button')
1247 b.wait_visible('#content')
1248 b.enter_page("/system")
1249 # cookie should be marked as secure, as for the browser it's https
1250 cookie = b.cookie("cockpit")
1251 self.assertTrue(cookie["httpOnly"])
1252 self.assertTrue(cookie["secure"])
1253 b.logout()
1254 # deleted cookie after logout should be marked as secure
1255 cookie = b.cookie("cockpit")
1256 self.assertEqual(cookie["value"], "deleted")
1257 self.assertTrue(cookie["httpOnly"])
1258 self.assertTrue(cookie["secure"])
1259
1260 # should have https:// URLs in Content-Security-Policy
1261 out = m.execute("curl --insecure --head https://localhost:9090/")
1262 self.assertIn("Content-Security-Policy: connect-src 'self' https://localhost:9090 wss://localhost:9090;", out)
1263
1264 # sanity check: does not redirect to https (through plain http proxy) -- this isn't a supported mode, though!
1265 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent --head http://127.0.0.1:9091"))
1266 self.assertIn("HTTP/1.1 200 OK", m.execute("curl --silent --head http://172.27.0.15:9091"))
1267
1268 @testlib.nondestructive
1269 @testlib.skipBeiboot("beiboot doesn't use systemd units")
1270 def testCaCert(self):
1271 m = self.machine
1272
1273 # force cert regeneration
1274 m.execute("systemctl stop cockpit; rm -f /etc/cockpit/ws-certs.d/*")
1275 m.start_cockpit()
1276 if not m.ws_container:
1277 # Really start Cockpit to make sure it has generated all its certificates.
1278 m.execute("systemctl start cockpit")
1279
1280 # Start without a CA certificate.
1281 self.addCleanup(m.execute, "rm -f /etc/cockpit/ws-certs.d/0-self-signed-ca.pem")
1282 m.execute("rm -f /etc/cockpit/ws-certs.d/0-self-signed-ca.pem")
1283 m.execute("! curl -sfS http://localhost:9090/ca.cer")
1284
1285 # Now make one up and check that is is served.
1286 m.write("/etc/cockpit/ws-certs.d/0-self-signed-ca.pem", "FAKE CERT FOR TESTING\n")
1287 self.assertEqual(m.execute("curl -sfS http://localhost:9090/ca.cer"), "FAKE CERT FOR TESTING\n")
1288
1289 @testlib.nondestructive
1290 def testBranding(self):
1291 m = self.machine
1292 m.start_cockpit()
1293
1294 # for all of our CI images, the part before the dash is the name of the
1295 # subdirectory in /usr/share/cockpit/branding.
1296 brand = m.image.split('-')[0]
1297 branddir = f'/usr/share/cockpit/branding/{brand}'
1298
1299 # We don't have access to the stuff on the filesystem if it's living in
1300 # the container.
1301 if not m.ws_container:
1302 # make sure that there are no broken links in "our" directory
1303 self.assertEqual(m.execute(f'find {branddir} -xtype l'), '')
1304
1305 # branding.css undergoes variable substitution based on the content of
1306 # /usr/lib/os-release. Perform the substitution for ourselves for
1307 # validation. envsubst comes from gettext.
1308 os_release_vars = m.execute("cat /usr/lib/os-release")
1309 os_release_vars = re.sub(r"#.*\n", '', os_release_vars, flags=re.MULTILINE).replace('\n', ' ')
1310 m.execute(f'{os_release_vars} envsubst < {branddir}/branding.css > /tmp/branding.ref')
1311 self.addCleanup(m.execute, "rm /tmp/branding.ref")
1312
1313 # fetch some files and make sure they match what we expect
1314 def curl_and_compare(name, content_type=None, reference=None):
1315 url = f'http://localhost:9090/cockpit/static/{name}'
1316 reference = reference or f'{branddir}/{name}'
1317
1318 # Check that the expected content type is served
1319 if content_type is not None:
1320 self.assertIn(f'Content-Type: {content_type}', m.execute(f'curl --head {url}'))
1321
1322 # Check that we can fetch the file
1323 m.execute(f'curl --fail -o /tmp/{name} {url}')
1324 self.addCleanup(m.execute, f"rm /tmp/{name}")
1325
1326 # compare that it matches what we expected
1327 if not m.ws_container:
1328 m.execute(f'cmp /tmp/{name} {reference}')
1329
1330 # some brands miss the images, but the OSes we CI have them all except in opensuse which is missing logo.png
1331 curl_and_compare('branding.css', 'text/css', reference='/tmp/branding.ref')
1332 if "opensuse" in m.image:
1333 curl_and_compare('default.png', 'image/png')
1334 else:
1335 curl_and_compare('logo.png', 'image/png')
1336 curl_and_compare('favicon.ico')
1337
1338 # do a pixel test to make sure everything looks like we expect
1339 b = self.browser
1340 b.open("/system")
1341 b.wait_visible("#login")
1342 b.assert_pixels("body", "login-screen")
1343
1344 # our supported OSes should all have branding make sure it matches os-release
1345 if m.image.startswith("ubuntu"):
1346 # reflects src/branding/ubuntu/branding.scss
1347 expected = m.execute('. /usr/lib/os-release; echo "$PRETTY_NAME"').strip()
1348 else:
1349 expected = m.execute('. /usr/lib/os-release; echo "$NAME $VARIANT"').strip()
1350 # quirk: trailing space hard to avoid due to the empty variant wrapped in <b>
1351 if m.image == 'arch':
1352 expected += ' '
1353
1354 b.wait_text("#brand", expected)
1355
1356 # customize branding in package dirs
1357 if not m.ws_container and not m.ostree_image:
1358 self.write_file(f"{branddir}/branding.css", """
1359 :root {
1360 --pf-t--global--color--brand--default: #FF5001;
1361 }""")
1362 b.reload(ignore_cache=True)
1363 b.login_and_go("/system", superuser=False)
1364 # PF button uses PF brand color, check that
1365 b.wait_visible('.ct-limited-access-alert button')
1366 bgcol = b.eval_js(
1367 "getComputedStyle(document.querySelector('.ct-limited-access-alert button')).backgroundColor")
1368 self.assertEqual(bgcol, "rgb(255, 80, 1)")
1369 b.logout()
1370
1371 # customize branding in /etc/cockpit; overrides package dirs
1372 if not m.ws_container:
1373 m.upload(["verify/files/bg-plain.jpg"], "/etc/cockpit/branding/")
1374 m.write("/etc/cockpit/branding/branding.css", """
1375 :root {
1376 --pf-t--global--color--brand--default: #50FF02;
1377 }
1378 html body.login-pf { background: url("bg-plain.jpg"); background-size: cover; }
1379 """)
1380 # cockpit-ws only detects branding on startup, and browsers cache; so apply some force
1381 m.restart_cockpit()
1382 b.login_and_go("/system", superuser=False)
1383 b.reload(ignore_cache=True)
1384 b.enter_page("/system")
1385
1386 b.wait_visible('.ct-limited-access-alert button')
1387 bgcol = b.eval_js(
1388 "getComputedStyle(document.querySelector('.ct-limited-access-alert button')).backgroundColor")
1389 self.assertEqual(bgcol, "rgb(80, 255, 2)")
1390 b.logout()
1391 b.wait_visible("#login")
1392 b.assert_pixels("body", "login-screen-custom-background")
1393
1394 @testlib.skipOstree("tests cockpit-ws package")
1395 @testlib.skipWsContainer("tests cockpit-ws package")
1396 @testlib.nondestructive
1397 def testAuthDirectSession(self):
1398 m = self.machine
1399 b = self.browser
1400
1401 m.stop_cockpit()
1402 # make sure that this doesn't use the session socket
1403 m.execute('systemctl stop cockpit-session.socket; systemctl mask cockpit-session.socket')
1404 self.addCleanup(m.execute, 'systemctl unmask cockpit-session.socket')
1405 m.write('/etc/cockpit/cockpit.conf', f"""
1406 [Negotiate]
1407 Action=none
1408
1409 [Basic]
1410 Command={self.libexecdir}/cockpit-session
1411 """)
1412
1413 # cockpit-ws has to run as root for this, as cockpit-session isn't suid root any more
1414 m.execute(f"systemd-run --unit=custom-ws.service {self.libexecdir}/cockpit-ws --no-tls")
1415 self.addCleanup(m.execute, "systemctl stop custom-ws.service")
1416 m.wait_for_cockpit_running()
1417
1418 b.login_and_go(None)
1419 b.wait_text('#current-username', 'admin')
1420 b.logout()
1421
1422 # Arch logs this to the journal
1423 self.allow_journal_messages("cockpit-session:.*Activate the web console with.*")
1424
1425 @testlib.skipWsContainer("no local config with cockpit/ws")
1426 @testlib.nondestructive
1427 def testXdgConfig(self):
1428 xdg_env = f"XDG_CONFIG_DIRS={self.vm_tmpdir}/xdg:/etc/test-xdg\n"
1429 m = self.machine
1430 self.write_file("/etc/systemd/system/service.d/xdg.conf",
1431 f"[Service]\nEnvironment={xdg_env}\n",
1432 post_restore_action="systemctl daemon-reload")
1433 m.execute("systemctl daemon-reload")
1434
1435 m.execute("mkdir -p /etc/test-xdg/cockpit; mv /etc/cockpit/ws-certs.d /etc/test-xdg/cockpit/")
1436 self.addCleanup(m.execute, "rm -rf /etc/test-xdg")
1437 m.write("/etc/test-xdg/cockpit/cockpit.conf",
1438 "[WebService]\nLoginTitle=ExDeeGee\nAllowUnencrypted=true\n")
1439
1440 # make sure this is not used
1441 m.write("/etc/cockpit/cockpit.conf",
1442 "[WebService]\nLoginTitle=NoNoNo\nAllowUnencrypted=false\n")
1443 m.start_cockpit(tls=True)
1444
1445 # https works
1446 out = m.execute("curl --insecure --head https://localhost:9090/")
1447 self.assertIn("HTTP/1.1 200 OK", out)
1448 self.assertIn("Set-Cookie: cockpit", out)
1449
1450 # http from non-localhost works
1451 b = self.browser
1452 b.open("/system")
1453 b.wait_visible("#login")
1454 b.wait_text("#server-name", "ExDeeGee")
1455
1456 # uses the expected certs
1457 self.assertEqual(m.execute("readlink /run/cockpit/tls/server/0.key.source").strip(),
1458 "/etc/test-xdg/cockpit/ws-certs.d/0-self-signed.key")
1459 # and did not generate new ones
1460 self.assertNotIn("ws-certs.d", m.execute("ls /etc/cockpit"))
1461 # properly iterates over dirs, ignores the one without files
1462 self.assertNotIn("xdg", m.execute(f"ls {self.vm_tmpdir}"))
1463
1464 # bridge respects it too
1465 self.write_file("/etc/environment", f"{xdg_env}\n", append=True)
1466 m.write("/etc/test-xdg/cockpit/systemd.override.json", """{
1467 "menu": {
1468 "services": { "label": "Hackices" }
1469 }
1470 }""")
1471 self.login_and_go(None)
1472 b.wait_visible("#nav-system li:contains('Hackices')")
1473 self.assertFalse(b.is_present("#nav-system li:contains('Services')"))
1474 b.logout()
1475
1476 # still starts with a broken config (no section headers)
1477 m.write("/etc/test-xdg/cockpit/cockpit.conf", "LoginTitle=NoNoNO\n")
1478 m.execute("systemctl stop cockpit")
1479 self.login_and_go(None)
1480 b.wait_visible("#nav-system li:contains('Hackices')")
1481 self.assertFalse(b.is_present("#nav-system li:contains('Services')"))
1482 b.logout()
1483 # message from cockpit-ws
1484 self.allow_journal_messages(".*cockpit.conf: key=val line not in any section.*")
1485 # message from bridge
1486 self.allow_journal_messages(".*cockpit.conf is invalid: File contains no section headers.*")
1487 self.allow_journal_messages(".*cockpit.conf.*line: 1")
1488 self.allow_journal_messages(".*LoginTitle=NoNoNO.*")
1489
1490 @testlib.nondestructive
1491 @testlib.skipBeiboot("no cockpit-bridge binary on host in beiboot mode")
1492 def testBridgeCLI(self):
1493 m = self.machine
1494
1495 out = m.execute("cockpit-bridge --help")
1496 # this needs to work with both the C and Python bridges
1497 self.assertRegex(out, r"[uU]sage:")
1498 self.assertIn("--packages", out)
1499
1500 version = m.execute("cockpit-bridge --version")
1501 self.assertIn("Protocol: 1", version)
1502 self.assertRegex(version, r"Version: \d{3,}")
1503
1504 packages = m.execute("cockpit-bridge --packages")
1505 self.assertRegex(packages, r"(^|\n)base1\s+.*/usr/share/cockpit/base1")
1506 # also includes menu and tools entries
1507 self.assertRegex(packages, r"(^|\n)system\s.*Services.*Terminal.*\s/usr/share/cockpit/systemd")
1508
1509 bridges = json.loads(m.execute("cockpit-bridge --bridges").strip())
1510 bridge_names = [b['name'] for b in bridges]
1511 self.assertGreater(len(bridges), 0)
1512 self.assertIn('sudo', bridge_names)
1513
1514
1515 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
1516 class TestReverseProxy(testlib.MachineCase):
1517
1518 provision = {
1519 "0": {"forward": {"443": 8443}}
1520 }
1521
1522 def setUp(self):
1523 super().setUp()
1524 m = self.machine
1525
1526 m.execute("if firewall-cmd --state >/dev/null 2>&1; then firewall-cmd --add-service https; fi")
1527
1528 m.upload(["../src/tls/ca/alice.pem", "../src/tls/ca/alice.key"], "/etc/pki")
1529
1530 m.write("/etc/cockpit/cockpit.conf", """[WebService]
1531 Origins = https://{origin} wss://{origin}
1532 ForwardedForHeader = X-Forwarded-For
1533 ProtocolHeader = X-Forwarded-Proto
1534 """.format(origin=m.forward["443"]), append=True)
1535
1536 m.execute("setsebool -P httpd_can_network_connect on")
1537 # these tests are running the cockpit-ws binary directly, not via cockpit.socket
1538 m.execute("systemctl start cockpit-session.socket")
1539 self.allow_journal_messages("audit.*bool=httpd_can_network_connect.*val=1.*")
1540 # tests don't patiently wait for sessions to shut down properly
1541 self.allow_restart_journal_messages()
1542
1543 def callProxyCurl(self, path, *args):
1544 # should use nginx' certificate, not cockpit's; use --resolve so that SNI matches the certificate's CN
1545 (https_host, https_port) = self.machine.forward["443"].split(':')
1546 return subprocess.check_output(
1547 ["curl", "--verbose",
1548 "--resolve", f"alice:{https_port}:{https_host}",
1549 "--cacert", os.path.join(testlib.TEST_DIR, "../src/tls/ca/ca.pem"),
1550 *args,
1551 f"https://alice:{https_port}{path}"],
1552 stderr=subprocess.STDOUT)
1553
1554 def checkCockpitOnProxy(self, urlroot="", login=True):
1555 b = self.new_browser()
1556
1557 out = self.callProxyCurl(f"{urlroot}/cockpit/static/login.html", "--head")
1558 self.assertIn(b"HTTP/1.1 200 OK", out)
1559 self.assertIn(b"subject: CN=alice; DC=COCKPIT", out)
1560
1561 # works with browser (but we can't set our CA)
1562 (https_host, https_port) = self.machine.forward["443"].split(':')
1563 b.open(f"https://{https_host}:{https_port}{urlroot}/system")
1564 if login:
1565 b.wait_visible("#login")
1566 b.set_val("#login-user-input", "admin")
1567 b.set_val("#login-password-input", "foobar")
1568 b.click('#login-button')
1569 b.wait_visible('#content')
1570 # Verify that the urlRoot is applied to links in the navbar.
1571 b.wait_visible(f'#host-apps a[href="{urlroot}/system"]')
1572
1573 if login:
1574 # check that we show up in the system logs from the browser's IP, not the proxy's
1575 self.assertIn('(172.27.0.2)', self.machine.execute('who'))
1576 b.logout()
1577
1578 @testlib.skipImage("nginx not installed", "centos-*", "rhel-*", "debian-*", "ubuntu-*", "arch")
1579 @testlib.skipOstree("nginx not installed")
1580 def testNginxTLS(self):
1581 """test proxying to Cockpit with TLS
1582
1583 As described on https://github.com/cockpit-project/cockpit/wiki/Proxying-Cockpit-over-NGINX
1584 This use use case is important for proxying a remote machine.
1585 """
1586 m = self.machine
1587
1588 m.write("/etc/nginx/conf.d/cockpit.conf", """
1589 server {{
1590 listen 443 ssl;
1591 server_name {origin};
1592 root /srv/www;
1593
1594 ssl_certificate "/etc/pki/alice.pem";
1595 ssl_certificate_key "/etc/pki/alice.key";
1596
1597 location / {{
1598 # Required to proxy the connection to Cockpit
1599 proxy_pass https://127.0.0.1:9090;
1600 proxy_set_header Host $host;
1601 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
1602 proxy_set_header X-Forwarded-Proto $scheme;
1603
1604 # Required for web sockets to function
1605 proxy_http_version 1.1;
1606 proxy_buffering off;
1607 proxy_set_header Upgrade $http_upgrade;
1608 proxy_set_header Connection "upgrade";
1609
1610 # Pass ETag header from Cockpit to clients.
1611 # See: https://github.com/cockpit-project/cockpit/issues/5239
1612 gzip off;
1613 }}
1614 }}
1615 """.format(origin=m.forward["443"]))
1616
1617 m.execute("systemctl start nginx")
1618 m.start_cockpit(tls=True)
1619 self.checkCockpitOnProxy()
1620
1621 # avoid crash when stopping the unit: https://bugzilla.redhat.com/show_bug.cgi?id=2304015
1622 m.execute("nginx -s stop")
1623
1624 # now test with UrlRoot
1625 m.write("/etc/cockpit/cockpit.conf", "UrlRoot = cockpit-root\n", append=True)
1626 m.execute("systemctl stop cockpit.service")
1627 self.sed_file("s_location /_location /cockpit-root_", "/etc/nginx/conf.d/cockpit.conf")
1628 m.execute("systemctl start nginx")
1629 self.checkCockpitOnProxy(urlroot="/cockpit-root")
1630
1631 # get a non-cockpit file from the server
1632 m.execute("mkdir -p /srv/www/embed-cockpit")
1633 m.upload(["verify/files/embed-cockpit/index.html",
1634 "verify/files/embed-cockpit/embed.js",
1635 "verify/files/embed-cockpit/embed.css"],
1636 "/srv/www/embed-cockpit/")
1637 m.execute("if selinuxenabled 2>&1; then chcon -R -t httpd_sys_content_t /srv/www; fi")
1638
1639 out = self.callProxyCurl("/embed-cockpit/embed.css")
1640 self.assertIn(b"HTTP/1.1 200 OK", out)
1641 self.assertIn(b"#embed-links", out)
1642
1643 # embedding
1644 b = self.browser
1645 (https_host, https_port) = self.machine.forward["443"].split(':')
1646 b.open(f"https://{https_host}:{https_port}/embed-cockpit/index.html")
1647 b.set_val("#embed-address", f"https://{https_host}:{https_port}/cockpit-root")
1648 b.click("#embed-full")
1649 b.wait_visible("iframe[name='embed-full'][loaded]")
1650 b.switch_to_frame("embed-full")
1651
1652 b.wait_visible("#login")
1653 b.set_val("#login-user-input", "admin")
1654 b.set_val("#login-password-input", "foobar")
1655 b.click('#login-button')
1656 b.wait_visible('.pf-v6-c-card.system-health')
1657
1658 @testlib.skipImage("nginx not installed", "centos-*", "rhel-*", "debian-*", "ubuntu-*", "arch")
1659 @testlib.skipOstree("nginx not installed")
1660 def testNginxNoTLS(self):
1661 """test proxying to Cockpit with plain HTTP
1662
1663 This can be done when nginx and cockpit run on the same machine.
1664 """
1665 m = self.machine
1666
1667 m.write("/etc/nginx/conf.d/cockpit.conf", """
1668 server {{
1669 listen 443 ssl;
1670 server_name {origin};
1671
1672 ssl_certificate "/etc/pki/alice.pem";
1673 ssl_certificate_key "/etc/pki/alice.key";
1674
1675 location / {{
1676 # Required to proxy the connection to Cockpit
1677 proxy_pass http://127.0.0.1:9090;
1678 proxy_set_header Host $host;
1679 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
1680 proxy_set_header X-Forwarded-Proto $scheme;
1681
1682 # Required for web sockets to function
1683 proxy_http_version 1.1;
1684 proxy_buffering off;
1685 proxy_set_header Upgrade $http_upgrade;
1686 proxy_set_header Connection "upgrade";
1687
1688 # Pass ETag header from Cockpit to clients.
1689 # See: https://github.com/cockpit-project/cockpit/issues/5239
1690 gzip off;
1691 }}
1692 }}
1693 """.format(origin=m.forward["443"]))
1694
1695 m.execute("systemctl start nginx")
1696
1697 def run_ws(extra_opts=""):
1698 m.spawn(
1699 f"runuser -u cockpit-session-socket -- {self.libexecdir}/cockpit-ws "
1700 f"--address=127.0.0.1 --for-tls-proxy {extra_opts}", "ws.log")
1701 m.wait_for_cockpit_running()
1702
1703 def kill_ws():
1704 m.execute("pkill cockpit-ws; while pgrep -a cockpit-ws; do sleep 1; done")
1705
1706 # start cockpit-ws in proxy mode, skip all the ws-certs.d/ steps
1707 run_ws()
1708 self.checkCockpitOnProxy()
1709 kill_ws()
1710
1711 # works also without the login page (krb, oauth, --local-session, etc.)
1712 run_ws("--local-session=cockpit-bridge")
1713 self.checkCockpitOnProxy(login=False)
1714 kill_ws()
1715
1716 # avoid crash when stopping the unit: https://bugzilla.redhat.com/show_bug.cgi?id=2304015
1717 m.execute("nginx -s stop")
1718
1719 # UrlRoot + login page
1720 m.write("/etc/cockpit/cockpit.conf", "UrlRoot = myroot\n", append=True)
1721 self.sed_file("s_location /_location /myroot_", "/etc/nginx/conf.d/cockpit.conf")
1722 m.execute("systemctl start nginx")
1723 run_ws()
1724 self.checkCockpitOnProxy(urlroot="/myroot")
1725 kill_ws()
1726
1727 # UrlRoot without login page
1728 run_ws("--local-session=cockpit-bridge")
1729 self.checkCockpitOnProxy(urlroot="/myroot", login=False)
1730 kill_ws()
1731
1732 self.allow_journal_messages("couldn't register polkit authentication agent.*")
1733 self.allow_journal_messages("couldn't change to runtime dir.*Permission denied")
1734
1735
1736 if __name__ == '__main__':
1737 testlib.test_main()