Debian Codegraph @

test/verify/check-system-realms

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 hashlib
10 import hmac
11 import re
12 import struct
13 import time
14
15 import packagelib
16 import testlib
17
18 WAIT_KRB_SCRIPT = """
19 set -ex
20 # Configuring kerberos in sssd takes some time
21 for _retry in $(seq 5); do
22 if getent passwd {0} &&
23 ssh -oStrictHostKeyChecking=no -oBatchMode=yes -l {0} x0.cockpit.lan true; then
24 exit 0
25 fi
26 if systemctl --quiet is-failed sssd.service; then
27 systemctl status --lines=100 sssd.service >&2
28 exit 1
29 fi
30 sss_cache -E || true
31 systemctl reset-failed sssd.service
32 systemctl restart sssd.service
33 sleep 10
34 done
35 exit 1
36 """
37
38 # https://en.wikipedia.org/wiki/HMAC-based_One-time_Password_algorithm
39 # https://stackoverflow.com/questions/8529265/google-authenticator-implementation-in-python
40
41
42 def hotp_token(secret, counter, digits=6, hash_alg=hashlib.sha1):
43 counter_bytes = struct.pack('>Q', int(counter))
44 hs = hmac.new(secret, counter_bytes, hash_alg).digest()
45 ofs = hs[-1] & 0xF
46 numbers = str(int.from_bytes(hs[ofs:ofs + 4], 'big') & 0x7fffffff)
47 return numbers[-digits:].rjust(digits, '0')
48
49
50 def maybe_setup_fake_chrony(machine):
51 # Some of our VM images have systemd-timesyncd installed, which
52 # conflicts with chrony. Set up a mock chrony.service to make
53 # ipa-client-install happy.
54 if machine.execute("type chronyc || echo not-found").strip() == "not-found":
55 machine.write("/run/systemd/system/chrony.service", """
56 [Service]
57 Type=oneshot
58 ExecStart=/bin/true
59 """)
60 machine.execute("ln -s /bin/true /usr/bin/chronyc")
61 machine.execute("systemctl unmask chrony")
62
63
64 class CommonTests:
65
66 def wait_discover(self):
67 with self.browser.wait_timeout(60):
68 self.browser.wait_attr("#realms-op-address", "data-discover", "done")
69
70 def wait_address_helper(self, expected=None):
71 with self.browser.wait_timeout(60):
72 self.browser.wait_text("#realms-op-address-helper", expected or "Contacted domain")
73
74 @testlib.timeout(900)
75 def testQualifiedUsers(self):
76 m = self.machine
77 b = self.browser
78
79 # Tell realmd to enable domain-qualified logins; unqualified ones are covered in testUnqualifiedUsers
80 m.write("/etc/realmd.conf", "[cockpit.lan]\nfully-qualified-names = yes\n", append=True)
81
82 # Test that we reconnect on privileges change
83 self.login_and_go("/system", superuser=False)
84 b.wait_visible(f"{self.domain_sel}:disabled")
85 b.become_superuser()
86
87 def wait_number_domains(n):
88 if n == 0:
89 b.wait_text(self.domain_sel, "Join domain")
90 else:
91 b.wait_text_not(self.domain_sel, "Join domain")
92 b.wait_not_attr(self.domain_sel, "disabled", "disabled")
93
94 wait_number_domains(0)
95
96 def wait_domain_detected():
97 with b.wait_timeout(60):
98 b.wait_val(self.op_address, "cockpit.lan")
99
100 # Join cockpit.lan
101 b.click(self.domain_sel)
102 b.wait_popup("realms-join-dialog")
103 wait_domain_detected()
104 self.wait_address_helper()
105 # admin gets auto-detected
106 b.wait_val(self.op_admin, self.admin_user)
107 b.set_input_text(self.op_admin_password, self.admin_password)
108 # FIXME: there is tons of subpixel noise in the fonts, impossible to match with our naïve algorithm
109 # b.assert_pixels("#realms-join-dialog", "realm-join")
110 b.click(f"#realms-join-dialog button{self.primary_btn_class}")
111 # running operation cannot be cancelled any more
112 b.wait_visible("#realms-join-dialog button.pf-m-link:disabled")
113 # disables inputs during join
114 b.wait_visible("#realms-op-address:disabled")
115 b.wait_visible("#realms-op-admin:disabled")
116 b.wait_visible("#realms-op-admin-password:disabled")
117 with b.wait_timeout(300):
118 b.wait_not_present("#realms-join-dialog")
119
120 # Check that this has worked
121 wait_number_domains(1)
122
123 # when joined to a domain, changing the hostname is fatal, so should be disabled
124 b.wait_not_present("#system_information_hostname_button")
125
126 # should not have any leftover tickets from the joining
127 m.execute("! klist")
128 m.execute("! su -c klist " + self.admin_user)
129 b.logout()
130
131 # wait until IPA user works
132 m.execute(f'while ! su -l -c "echo {self.admin_password} | sudo -S true" {self.admin_user}@cockpit.lan; do '
133 ' sleep 5; sss_cache -E || true; systemctl reset-failed sssd; systemctl try-restart sssd; done',
134 timeout=300)
135
136 # change existing local "admin" home dir to domain "admin" user
137 m.execute(f"chown -R {self.admin_user}@cockpit.lan /home/admin")
138
139 # log in as domain admin and check that we can do privileged operations
140 b.login_and_go('/system/services#/systemd-tmpfiles-clean.timer', user=f'{self.admin_user}@cockpit.lan', password=self.admin_password)
141 b.wait_in_text("#statuses", "Running")
142 b.click(".service-top-panel button.pf-v6-c-menu-toggle")
143 b.click("button.pf-v6-c-menu__item:contains('Stop')")
144 b.wait_in_text("#statuses", "Not running")
145 # stopping the unit may interrupt the D-Bus proxy inspection of that unit
146 self.allow_journal_messages(".*systemd1:.*systemd_2dtmpfiles_2dclean_2etimer: Timeout was reached")
147 b.logout()
148
149 # should also work with capitalized domain and lower-case user (fixed in PR #13934)
150 # need to change URL to actually reload the page
151 b.login_and_go('/system', user=f'{self.admin_user.lower()}@COCKPIT.LAN', password=self.admin_password)
152 b.go('/system/services#/systemd-tmpfiles-clean.timer')
153 b.enter_page('/system/services')
154 b.wait_in_text("#statuses", "Not running")
155 b.click(".service-top-panel button.pf-v6-c-menu-toggle")
156 b.click("button.pf-v6-c-menu__item:contains('Start')")
157 b.wait_in_text("#statuses", "Running")
158 b.logout()
159
160 self.checkBackendSpecifics()
161
162 # change home directory ownership back to local user
163 m.execute("chown -R admin /home/admin")
164
165 if m.image.startswith("debian"):
166 # HACK: https://bugs.debian.org/1038925
167 m.execute(r"sed -i '/\[ntp\]/,/^$/ d' /var/lib/ipa-client/sysrestore/sysrestore.state")
168
169 # Test domain info (PR #11096), leave the domain
170 b.login_and_go("/system")
171 b.wait_in_text(self.domain_sel, "cockpit.lan")
172 b.click(self.domain_sel)
173 b.wait_popup("realms-leave-dialog")
174 b.wait_text("#realms-op-info-domain", "cockpit.lan")
175 b.wait_text("#realms-op-info-login-format", "[email protected]")
176 b.wait_text("#realms-op-info-server-sw", self.expected_server_software)
177 b.wait_text("#realms-op-info-client-sw", "sssd")
178 # leave button should be hidden behind expander by default
179 b.wait_not_visible("#realms-op-leave")
180 b.wait_not_visible("#realms-leave-dialog .pf-v6-c-alert")
181 b.click("#realms-leave-dialog .pf-v6-c-expandable-section__toggle button")
182 b.wait_visible("#realms-leave-dialog .pf-v6-c-alert")
183 # caret expander is animated and not reproducible even after a sleep
184 # FIXME: there is tons of subpixel noise in the fonts, impossible to match with our naïve algorithm
185 # b.assert_pixels("#realms-leave-dialog", "realm-leave", [".pf-v6-c-expandable-section__toggle-icon"])
186 b.click("#realms-op-leave")
187
188 with b.wait_timeout(60):
189 b.wait_not_present("#realms-leave-dialog")
190 wait_number_domains(0)
191 # re-enables hostname changing
192 b.wait_visible("#system_information_hostname_button:not([disabled])")
193
194 self.checkBackendSpecificCleanup()
195
196 # Sometimes with some versions of realmd the Leave operation
197 # from above is still active in the realmd daemon. So we loop
198 # here until we get the expected error instead of "Already
199 # running another action".
200
201 tries = 0
202 while tries < 3:
203 # Send a wrong password
204 b.click(self.domain_sel)
205 b.wait_popup("realms-join-dialog")
206 wait_domain_detected()
207 b.wait_val(self.op_admin, self.admin_user)
208 b.set_input_text(self.op_admin_password, "foo")
209 b.click(f"#realms-join-dialog button{self.primary_btn_class}")
210 with b.wait_timeout(60):
211 b.wait_text_not(".realms-op-error", "")
212 error = b.text(".realms-op-error")
213 if "Already running another action" not in error:
214 # "More" link is part of the message component, so this looks a little funny here
215 if self.expected_server_software == 'active-directory':
216 self.assertEqual(error, "Danger alert:Failed to join the domainDetails")
217 else:
218 self.assertEqual(error, "Danger alert:Password is incorrectDetails")
219 # "More" should be visible, and diagnostics not shown by default
220 b.wait_not_present(".realms-op-diagnostics")
221 b.click(".realms-op-error button")
222 # that hides the Details link
223 b.wait_not_present(".realms-op-error button")
224 # and shows the raw log
225 b.wait_visible(".realms-op-diagnostics")
226 if self.expected_server_software == 'active-directory':
227 b.wait_in_text(".realms-op-diagnostics", "Couldn't authenticate as: [email protected]")
228 else:
229 b.wait_in_text(".realms-op-diagnostics", "ipa-client-install command failed")
230 b.click("#realms-join-dialog button.pf-m-link")
231 b.wait_not_present("#realms-join-dialog")
232 if "Already running another action" not in error:
233 break
234 print("Another operation running, retry")
235 time.sleep(20)
236 tries += 1
237
238 # Try to join a non-existing domain
239 b.click(self.domain_sel)
240 b.wait_popup("realms-join-dialog")
241 # wait for auto-detection
242 wait_domain_detected()
243 b.set_input_text(self.op_address, "NOPE")
244 self.wait_address_helper("Domain could not be contacted")
245 b.wait_visible(f"#realms-join-dialog button{self.primary_btn_class}:disabled")
246 b.click("#realms-join-dialog button.pf-m-link")
247 b.wait_not_present("#realms-join-dialog")
248
249 # Join a domain with the server as address (input differs from domain name)
250 b.click(self.domain_sel)
251 b.wait_popup("realms-join-dialog")
252 self.wait_discover()
253 b.set_input_text(self.op_address, "f0.cockpit.lan")
254 self.wait_address_helper()
255 # admin gets auto-detected
256 b.wait_val(self.op_admin, self.admin_user)
257 b.set_input_text(self.op_admin_password, self.admin_password)
258 b.click(f"#realms-join-dialog button{self.primary_btn_class}")
259 with b.wait_timeout(300):
260 b.wait_not_present("#realms-join-dialog")
261 wait_number_domains(1)
262
263 self.allow_journal_messages(".*No authentication agent found.*")
264 # sometimes polling for info and joining a domain creates this noise
265 self.allow_journal_messages('.*org.freedesktop.DBus.Error.Spawn.ChildExited.*')
266 # HACK: idling too long on the login page in Negotiate while waiting for FreeIPA to init
267 # times out in ws and kills cockpit-session; this should be fixed properly in ws
268 self.allow_journal_messages('.*session timed out during authentication')
269 self.allow_journal_messages('.*authentication timed out')
270
271 def testUnqualifiedUsers(self):
272 m = self.machine
273 b = self.browser
274
275 # delete the local admin user, going to use the domain one instead
276 m.execute("userdel --remove admin; systemctl try-restart sssd")
277
278 # Tell realmd to not enable domain-qualified logins
279 # (https://bugzilla.redhat.com/show_bug.cgi?id=1575538)
280 m.write("/etc/realmd.conf", "[cockpit.lan]\nfully-qualified-names = no\n", append=True)
281 m.execute(f"echo {self.admin_password} | realm join -vU {self.admin_user} cockpit.lan", timeout=300)
282
283 # wait until domain user works
284 m.execute('while ! su -l -c "echo %s | sudo -S true" %s; do sleep 5; sss_cache -E || true; systemctl try-restart sssd; done' %
285 (self.admin_password, self.admin_user), timeout=300)
286
287 # login should now work with the domain admin user
288 b.password = self.admin_password
289 self.login_and_go("/system", user=self.admin_user)
290 b.wait_in_text(self.domain_sel, "cockpit.lan")
291
292 # Show domain information
293 b.click(self.domain_sel)
294 b.wait_popup("realms-leave-dialog")
295 b.wait_text("#realms-op-info-domain", "cockpit.lan")
296 b.wait_text("#realms-op-info-login-format", "username") # no @domain
297 b.wait_text("#realms-op-info-server-sw", self.expected_server_software)
298 b.wait_text("#realms-op-info-client-sw", "sssd")
299 b.click(f"#realms-leave-dialog button{self.default_btn_class}")
300 with b.wait_timeout(30):
301 b.wait_not_present("#realms-leave-dialog")
302
303 # should be able to run admin operations
304 b.go('/system/services#/systemd-tmpfiles-clean.timer')
305 b.enter_page('/system/services')
306
307 b.wait_in_text("#statuses", "Running")
308 b.click(".service-top-panel button.pf-v6-c-menu-toggle")
309 b.click("button.pf-v6-c-menu__item:contains('Stop')")
310 b.wait_in_text("#statuses", "Not running")
311
312 b.go('/system')
313 b.enter_page('/system')
314 # shutdown button should be enabled and working
315 # it takes a while for the permission check to finish, it is always enabled at first
316 b.click("#overview #reboot-button")
317
318 b.wait_popup("shutdown-dialog")
319 b.click("#delay")
320 b.click("button:contains('No delay')")
321 b.wait_text("#delay .pf-v6-c-menu-toggle__text", "No delay")
322 b.click("#shutdown-dialog button:contains('Reboot')")
323 b.switch_to_top()
324 b.wait_in_text(".curtains-ct h1", "Disconnected")
325 self.wait_reboot()
326
327 self.allow_journal_messages(".*No authentication agent found.*")
328 # sometimes polling for info and joining a domain creates this noise
329 self.allow_journal_messages('.*org.freedesktop.DBus.Error.Spawn.ChildExited.*')
330
331 def checkClientCertAuthentication(self):
332 """Common tests for certificate authentication
333
334 This assumes that IdM and sssd are all set up correctly already.
335 """
336 m = self.machine
337 b = self.browser
338
339 # join domain, wait until it works
340 m.write("/etc/realmd.conf", "[cockpit.lan]\nfully-qualified-names = no\n", append=True)
341 # join client machine with Cockpit, to create the HTTP/ principal and /etc/cockpit/krb5.keytab
342 self.login_and_go("/system")
343 b.click("#system_information_domain_button")
344 b.wait_popup("realms-join-dialog")
345 self.wait_discover()
346
347 b.set_input_text("#realms-op-address", "cockpit.lan")
348 self.wait_address_helper()
349 b.set_input_text("#realms-op-admin", self.admin_user)
350 b.set_input_text("#realms-op-admin-password", self.admin_password)
351 b.click(f"#realms-join-dialog button{self.primary_btn_class}")
352 with b.wait_timeout(300):
353 b.wait_not_present("#realms-join-dialog")
354 b.logout()
355 m.execute('while ! id alice; do sleep 5; done', timeout=300)
356
357 # alice's certificate was written by testClientCertAuthentication()
358 alice_cert_key = ['--cert', "/var/tmp/alice.pem", '--key', "/var/tmp/alice.key"]
359 alice_user_pass = ['-u', 'alice:' + self.alice_password]
360
361 if self.__class__ == TestIPA:
362 # `realm join` does not automatically configure sssd to be able to validate certificates;
363 # it needs to be explicitly told the CA to trust. Use the IPA's CA. (That would be an
364 # excellent default, but oh well, we can't have all nice things.)
365 m.execute("mkdir -p /etc/sssd/pki/; cp /etc/ipa/ca.crt /etc/sssd/pki/sssd_auth_ca_db.pem")
366
367 # ensure sssd certificate lookup works
368 user_obj = m.execute('busctl call org.freedesktop.sssd.infopipe /org/freedesktop/sssd/infopipe/Users '
369 'org.freedesktop.sssd.infopipe.Users FindByCertificate s -- '
370 """"$(cat /var/tmp/alice.pem)" | sed 's/^o "//; s/"$//' """)
371 self.assertEqual(m.execute('busctl get-property org.freedesktop.sssd.infopipe ' + user_obj.strip() +
372 ' org.freedesktop.sssd.infopipe.Users.User name').strip(),
373 's "alice"')
374
375 # These tests have to be run with curl, as chromium-headless does not support selecting/handling client-side
376 # certificates; it just rejects cert requests. For interactive tests, grab src/tls/ca/alice.p12 and import
377 # it into the browser.
378
379 def do_test(authopts, expected, not_expected=None, session_leader=None, retry=False):
380 m.start_cockpit(tls=True)
381
382 def try_auth():
383 output = m.execute(['curl', '-ksS', '-D-', *authopts, 'https://localhost:9090/cockpit/login'])
384 for s in expected:
385 self.assertIn(s, output)
386 for s in (not_expected or []):
387 self.assertNotIn(s, output)
388 return True
389
390 if retry:
391 testlib.wait(try_auth, delay=5, tries=10)
392 else:
393 try_auth()
394
395 # sessions/users often hang around in State=closing for a long time, ignore these
396 if session_leader:
397 m.execute('until [ "$(loginctl show-user --property=State --value alice)" = "active" ]; do sleep 1; done')
398 sessions = m.execute('loginctl show-user --property=Sessions --value alice').strip().split()
399 self.assertGreaterEqual(len(sessions), 1)
400 for session in sessions:
401 out = m.execute('loginctl session-status ' + session)
402 if "State: active" in out and "Class: manager" not in out: # skip closing and manager sessions
403 self.assertIn(session_leader, out)
404 self.assertIn('cockpit-bridge', out)
405 # systemd < 255: "Service: cockpit; type web; class user"
406 # systemd ≥ 255: "Service: cockpit\n Type: web\n Class: user"
407 self.assertRegex(out, r"Service:\s+cockpit")
408 self.assertRegex(out, "[tT]ype.*web")
409 break
410 else:
411 self.fail("no active session for active user")
412
413 # sessions time out after 10s, but let's not wait for that
414 m.execute('loginctl terminate-session ' + sessions[0])
415 # wait until the session is gone
416 m.execute("while loginctl show-user alice | grep -q 'State=active'; do sleep 1; done")
417
418 m.stop_cockpit()
419
420 # from sssd
421 self.allow_journal_messages("alice is not allowed to run sudo on x0. This incident will be reported.")
422 # occasional intermediate error during password auth
423 self.allow_journal_messages("cockpit-session: user account access failed: 4 alice: System error")
424
425 # cert auth should not be enabled by default
426 do_test(alice_cert_key, ["HTTP/1.1 401 Authentication failed", '"authorize"'])
427 # password auth should work (but might need to be retried)
428 do_test(alice_user_pass, ['HTTP/1.1 200 OK', '"csrf-token"'], session_leader='cockpit-session', retry=True)
429
430 # enable cert based auth
431 # FIXME: this is ugly, and we don't currently accept multiple [WebService] sections
432 if self.multihost_enabled:
433 # no previous cockpit.conf
434 m.write("/etc/cockpit/cockpit.conf", '[WebService]\nClientCertAuthentication = true\n', append=True)
435 else:
436 # enable_multihost above already wrote [WebService]
437 m.write("/etc/cockpit/cockpit.conf", 'ClientCertAuthentication = true\n', append=True)
438 # cert auth should work now
439 do_test(alice_cert_key, ['HTTP/1.1 200 OK', '"csrf-token"'])
440 # password auth, too
441 do_test(alice_user_pass, ['HTTP/1.1 200 OK', '"csrf-token"'], session_leader='cockpit-session')
442 # cert auth should go through PAM stack and re-create home dir
443 m.execute("rm -r ~alice")
444 do_test(alice_cert_key, ['HTTP/1.1 200 OK', '"csrf-token"'])
445 m.execute("test -f ~alice/.bashrc")
446
447 # another certificate gets rejected
448 self.allow_journal_messages("cockpit-session: .*User not found")
449 self.allow_journal_messages("cockpit-session: No matching user for certificate")
450 m.upload(["bob.pem", "bob.key"], "/var/tmp", relative_dir="src/tls/ca/")
451 do_test(['--cert', "/var/tmp/bob.pem", '--key', "/var/tmp/bob.key"],
452 ["HTTP/1.1 401 Authentication failed"],
453 not_expected=["crsf-token"])
454 self.allow_journal_messages("cockpit-session: Failed to map certificate to user: .* Invalid certificate provided")
455
456 # disallow password auth
457 m.write("/etc/cockpit/cockpit.conf", "[Basic]\naction = none\n", append=True)
458 do_test(alice_cert_key, ['HTTP/1.1 200 OK', '"csrf-token"'])
459 do_test(alice_user_pass, ['HTTP/1.1 401 Authentication disabled'],
460 not_expected=["crsf-token"])
461
462 # valid user certificate which fails CA validation
463 m.execute("mv /etc/sssd/pki/sssd_auth_ca_db.pem /etc/sssd/pki/sssd_auth_ca_db.pem.valid")
464 self.allow_journal_messages("cockpit-session: Failed to map certificate to user: .* Certificate authority file not found")
465 with open("src/tls/ca/alice-expired.pem") as f:
466 m.write("/etc/sssd/pki/sssd_auth_ca_db.pem", f.read())
467 api = m.execute("busctl introspect org.freedesktop.sssd.infopipe /org/freedesktop/sssd/infopipe/Users")
468 has_validate_api = 'FindByValidCertificate' in api
469 if has_validate_api:
470 do_test(alice_cert_key, ["HTTP/1.1 401 Authentication failed"])
471 else:
472 # earlier sssd just matches the certificate verbatim, without CA validation
473 do_test(alice_cert_key, ['HTTP/1.1 200 OK', '"csrf-token"'])
474 m.execute("mv /etc/sssd/pki/sssd_auth_ca_db.pem.valid /etc/sssd/pki/sssd_auth_ca_db.pem")
475
476
477 @testlib.skipOstree("No realmd available")
478 @testlib.skipWsContainer("No sssd PAM integration in beiboot mode")
479 @testlib.skipImage("No realmd available", "arch")
480 @testlib.no_retry_when_changed
481 class TestRealms(testlib.MachineCase):
482 """Common variables and tests for all supported domain backends"""
483
484 provision = {
485 "0": {"address": "10.111.113.1/20", "dns": "10.111.112.100"},
486 "services": {"image": "services", "memory_mb": 2048}
487 }
488
489 def setUp(self):
490 super().setUp()
491 self.op_address = "#realms-op-address"
492 self.op_admin = "#realms-op-admin"
493 self.op_admin_password = "#realms-op-admin-password"
494 self.domain_sel = "#system_information_domain_button"
495 self.machine.execute("hostnamectl set-hostname x0.cockpit.lan")
496 self.enable_multihost(self.machine)
497
498 # realmd times out on inactivity, which occasionally races with the proxy
499 self.allow_journal_messages("couldn't get all properties of org.freedesktop.realmd.Service.*org.freedesktop.DBus.Error.NoReply: Remote peer disconnected")
500
501
502 @testlib.no_retry_when_changed
503 class TestIPA(TestRealms, CommonTests):
504 def setUp(self):
505 super().setUp()
506 m = self.machine
507
508 self.admin_user = "admin"
509 self.admin_password = "foobarfoo"
510 self.alice_password = 'WonderLand123'
511 self.expected_server_software = "ipa"
512 self.machines['services'].execute("/root/run-freeipa")
513 # Wait for FreeIPA to come up and DNS to work as expected
514 # https://bugzilla.redhat.com/show_bug.cgi?id=1071356#c11
515 testlib.wait(lambda: self.machine.execute("nslookup -type=SRV _ldap._tcp.cockpit.lan"))
516
517 maybe_setup_fake_chrony(self.machine)
518
519 # wait until FreeIPA started up
520 self.machines['services'].execute(f"""podman exec -i freeipa sh -ec '
521 while ! echo {self.admin_password} | kinit -f {self.admin_user}; do sleep 5; done
522 while ! ipa user-find >/dev/null; do sleep 5; done'
523 """, timeout=300)
524
525 # during image creation the /var/cache directory gets cleaned up, recreate the krb5rcache
526 m.execute("mkdir -pZ /var/cache/krb5rcache")
527
528 # IPA CA cert has OCSP entry with that host name, make it available
529 m.execute("echo '10.111.112.100 ipa-ca.cockpit.lan' >> /etc/hosts")
530
531 # HACK: Figure out why this happens
532 self.allow_journal_messages(""".*didn't receive expected "authorize" message""",
533 'cockpit-session:$')
534 self.allow_journal_messages('/bin/bash: /home/admin/.bashrc: Permission denied')
535
536 # sudo-rs does not support centralized sudoers rules (FreeIPA), switch to classic sudo
537 if self.has_sudo_rs:
538 if "currently points to /usr/lib/cargo/bin/sudo" not in m.execute("update-alternatives --display sudo"):
539 raise NotImplementedError("expected sudo-rs by default; adjust the test setup")
540 m.execute("update-alternatives --set sudo /usr/bin/sudo.ws")
541
542 def checkBackendSpecifics(self):
543 """Check domain backend specific integration"""
544
545 m = self.machine
546 b = self.browser
547
548 def cockpit_sessions():
549 """Return list of users who have a running Cockpit session"""
550 # unfortunately the session type isn't part of the list view/query
551 # --json=short is very recent, not yet available in Fedora 40 and older; so parse lines
552 users = []
553 for line in m.execute("loginctl --no-legend list-sessions").strip().splitlines():
554 fields = line.split()
555 info = m.execute(f"loginctl show-session {fields[0]}")
556 if "Type=web" in info and "State=closing" not in info:
557 users.append(fields[2])
558 return users
559
560 def wait_cockpit_sessions(expected):
561 # "assertEqual" returns None when successful, but
562 # testlib.wait wants to see something truthy, that's why
563 # we add the "or True".
564 testlib.wait(lambda: self.assertEqual(cockpit_sessions(), expected) or True)
565
566 # should have added SPN to ws keytab
567 output = m.execute(['klist', '-k', '/etc/cockpit/krb5.keytab'])
568 self.assertIn('HTTP/[email protected]', output)
569
570 # validate Kerberos setup for ws
571 m.execute(f"echo {self.admin_password} | kinit -f {self.admin_user}@COCKPIT.LAN")
572 m.execute(WAIT_KRB_SCRIPT.format(f"{self.admin_user}@cockpit.lan"), timeout=300)
573
574 # kerberos login should work
575 output = m.execute(['curl', '-s', '--negotiate', '--delegation', 'always', '-u', ':', "-D", "-",
576 'http://x0.cockpit.lan:9090/cockpit/login'])
577 self.assertIn("HTTP/1.1 200 OK", output)
578 self.assertIn('"csrf-token"', output)
579
580 # Restart cockpit with SSL enabled, this should have gotten an SSL cert from FreeIPA
581 m.stop_cockpit()
582 m.start_cockpit(tls=True)
583 # OpenSSL and curl should use the system PKI which should trust the IPA server CA
584 out = m.execute("openssl s_client -verify 5 -verify_return_error -connect localhost:9090")
585 self.assertRegex(out, "subject=/?O *= *COCKPIT.LAN.*CN *= *x0.cockpit.lan", out)
586 self.assertRegex(out, "issuer=/?O *= *COCKPIT.LAN.*CN *= *Certificate Authority")
587 self.assertIn("Content-Type: text/html", m.execute("curl --head https://x0.cockpit.lan:9090"))
588 # don't leave the secret key copy behind
589 m.execute("! test -e /run/cockpit/ipa.key")
590 # cockpit-certificate-ensure agrees
591 self.assertIn("/etc/cockpit/ws-certs.d/10-ipa.cert",
592 m.execute(f"{self.libexecdir}/cockpit-certificate-ensure --check"))
593 # correct permissions
594 self.assertEqual("root:root/640", m.execute("stat --printf '%U:%G/%a' /etc/cockpit/ws-certs.d/10-ipa.key"))
595 # cert is being tracked
596 out = m.execute("ipa-getcert list")
597 self.assertIn("MONITORING", out)
598 # certmonger must be able to directly write and auto-refresh the certificates
599 self.assertIn("/etc/cockpit/ws-certs.d/10-ipa.key", out)
600 # ensure that refreshing works
601 old_cert = m.execute("cat /etc/cockpit/ws-certs.d/10-ipa.cert").strip()
602 m.execute("ipa-getcert rekey --verbose --wait -f /etc/cockpit/ws-certs.d/10-ipa.cert")
603 new_cert = m.execute("cat /etc/cockpit/ws-certs.d/10-ipa.cert").strip()
604 self.assertNotEqual(old_cert, new_cert)
605
606 # Restart without SSL (IPA certificate is not on the testing host)
607 m.stop_cockpit()
608 m.start_cockpit()
609
610 # check respecting FreeIPA's/sssd's ssh known host keys; login_and_go() does not expect/answer
611 # unknown host prompts
612 b.login_and_go(user=f'{self.admin_user}@cockpit.lan', password=self.admin_password)
613 # starts proper session
614 wait_cockpit_sessions(["[email protected]"])
615 b.logout()
616
617 # does not leak any processes or the session itself
618 wait_cockpit_sessions([])
619
620 def checkBackendSpecificCleanup(self):
621 """Check domain backend specific integration after leaving domain"""
622
623 m = self.machine
624
625 # should have cleaned up ws keytab
626 m.execute("! klist -k /etc/cockpit/krb5.keytab | grep COCKPIT.LAN")
627 # should have cleaned up certificates
628 m.execute("! test -e /etc/cockpit/ws-certs.d/10-ipa.cert")
629 m.execute("! test -e /etc/cockpit/ws-certs.d/10-ipa.key")
630 # should have stopped cert tracking
631 testlib.wait(lambda: "status:" not in m.execute("ipa-getcert list"))
632
633 def testUnqualifiedUsers(self):
634 """Extend the common test with 2FA login"""
635
636 m = self.machine
637 b = self.browser
638
639 super().testUnqualifiedUsers()
640
641 if "debian" in m.image or "ubuntu" in m.image:
642 # additional PAM setup on Debian to actually use pam_sss for non-local users
643 self.sed_file(r"/pam_unix/ s/^/auth [default=1 ignore=ignore success=ok] pam_localuser.so\n/; "
644 r"/pam_sss/ s/use_first_pass/forward_pass/", "/etc/pam.d/common-auth")
645
646 # set up "alice" user with HOTP; that won't affect existing users (admin)
647 # https://docs.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/linux_domain_identity_authentication_and_policy_guide/otp
648 out = self.machines['services'].execute("""podman exec -i freeipa sh -ec '
649 ipa config-mod --user-auth-type=otp
650 ipa user-add --first=Alice --last=Developer alice
651 yes alicessecret | ipa user-mod --password alice
652 ipa user-mod --password-expiration="2030-01-01T00:00:00Z" alice
653 ipa otptoken-add --type=hotp --owner=alice
654 ' """)
655 # if the default ever changes, hotp_token() needs to be updated
656 self.assertIn(" Algorithm: sha1\n", out)
657 alice_hotp_key = re.search(r'^ Key: (.*)', out, re.M).group(1)
658 # print("alice's HOTP key:", alice_hotp_key)
659 alice_hotp_key = base64.b64decode(alice_hotp_key)
660
661 # wait until this propagates to the client
662 testlib.wait(lambda: m.execute("su -s /bin/sh -c 'su - alice </dev/null' - nobody 2>&1 | grep 'Second Factor'"))
663
664 m.start_cockpit()
665
666 # normal b.login_and_go() doesn't support 2FA
667 b.open("/")
668 b.wait_visible("#login")
669 b.set_val('#login-user-input', "alice")
670 b.set_val('#login-password-input', "alicessecret")
671 b.click('#login-button')
672 b.wait_in_text("#conversation-prompt", "Second Factor")
673 # wrong token (wrong number of digits)
674 b.set_val("#conversation-input", "1234")
675 b.click('#login-button')
676 b.wait_text("#login-error-title", "Authentication failed")
677 b.wait_not_visible("#login-error-message")
678
679 b.set_val('#login-user-input', "alice")
680 b.set_val('#login-password-input', "alicessecret")
681 b.click('#login-button')
682 b.wait_in_text("#conversation-prompt", "Second Factor")
683 token = hotp_token(alice_hotp_key, 0) # first usage, counter == 0
684 # print("alice first token:", token)
685 b.set_val("#conversation-input", token)
686 b.click('#login-button')
687 b.wait_visible('#content')
688
689 def testNotSupported(self):
690 m = self.machine
691 b = self.browser
692
693 # Disable sssd support in realmd
694 m.execute("echo -e '[providers]\nsssd = no\n' >> /usr/lib/realmd/realmd-distro.conf")
695
696 self.login_and_go("/system")
697
698 # Join cockpit.lan
699 b.click(self.domain_sel)
700 b.wait_popup("realms-join-dialog")
701 self.wait_discover()
702 b.set_input_text(self.op_address, "cockpit.lan")
703 self.wait_address_helper("Domain is not supported")
704 # no admin name auto-detection for unsupported domains
705 b.wait_val(self.op_admin, "")
706 b.set_input_text(self.op_admin, self.admin_user)
707 b.set_input_text(self.op_admin_password, self.admin_password)
708 # Join button disabled
709 b.wait_visible(f"#realms-join-dialog button{self.primary_btn_class}:disabled")
710
711 self.allow_journal_messages(".*couldn't introspect /org/freedesktop/realmd.*",
712 "sudo: unable to resolve host x0.cockpit.lan: Name or service not known")
713
714 @testlib.timeout(900)
715 def testClientCertAuthentication(self):
716 m = self.machine
717 b = self.browser
718
719 ipa_machine = self.machines['services']
720 # set up an IPA user with a TLS certificate; can't use "admin" due to https://pagure.io/freeipa/issue/6683
721 ipa_machine.execute(f"""podman exec -i freeipa sh -exc '
722 ipa user-add --first=Alice --last="Developer" --shell=/bin/bash alice
723 yes "{self.alice_password}" | ipa user-mod --password alice
724 ipa user-mod --password-expiration=2030-01-01T00:00:00Z alice' """)
725
726 ipa_machine.execute(r"""podman exec -i freeipa sh -exc '
727 # generate IPA CA signed certificate for alice
728 openssl req -new -newkey rsa:2048 -nodes -keyout /tmp/alice.key -out /tmp/alice.csr -subj "/CN=alice"
729 ipa cert-request /tmp/alice.csr --principal=alice --certificate-out=/tmp/alice.pem
730 # make alice an admin
731 ipa group-add-member admins --users=alice
732 ipa-advise enable-admins-sudo | sh -ex
733 ' """)
734 # download certificate to cockpit machine
735 m.write("/var/tmp/alice.pem", ipa_machine.execute("podman exec -i freeipa cat /tmp/alice.pem").strip())
736 m.write("/var/tmp/alice.key", ipa_machine.execute("podman exec -i freeipa cat /tmp/alice.key").strip())
737
738 self.checkClientCertAuthentication()
739
740 # the above password login implicitly creates a persistent user ticket
741 alice_klist_cmd = 'su -c klist alice'
742 persistent_ticket = m.execute(alice_klist_cmd)
743
744 # enable sudo GSSAPI authentication
745 m.execute(r"""#!/bin/sh -eu
746 sed -i '/\[domain\/cockpit.lan\]/ a pam_gssapi_services = sudo, sudo-i' /etc/sssd/sssd.conf
747 sed -i '1 a auth sufficient pam_sss_gss.so' /etc/pam.d/sudo
748 systemctl restart sssd
749 """)
750
751 # enable ssh GSSAPI authentication
752 m.execute("sed -ri 's/#GSSAPIAuthentication.*/GSSAPIAuthentication yes/' /etc/ssh/sshd_config")
753 m.execute(self.restart_sshd)
754
755 # avoid "unknown host" error in SSH
756 m.execute("su -c 'mkdir -p ~/.ssh; ssh-keyscan localhost > ~/.ssh/known_hosts' alice")
757
758 # the test below assumes exactly one running bridge
759 m.execute("! pgrep cockpit-bridge")
760
761 # check S4U proxy ticket for the user (not functional for anything without delegation rules)
762 # this is specific to IPA, as with AD cockpit-ws does not get a keytab
763
764 # as we can't do cert auth in the browser, splice socat in between to do that for us
765 m.execute(f"""! selinuxenabled || semanage port -m -t websm_port_t -p tcp 443
766 mkdir -p /run/systemd/system/cockpit.socket.d/
767 printf "[Socket]\nListenStream=\nListenStream=443" > /run/systemd/system/cockpit.socket.d/listen.conf
768 sed -i '/\\[WebService/ aOrigins = http://{m.web_address}:{m.web_port}' /etc/cockpit/cockpit.conf""")
769 m.spawn("socat TCP-LISTEN:9090,reuseaddr,fork OPENSSL:x0.cockpit.lan:443,cert=/var/tmp/alice.pem,key=/var/tmp/alice.key", "socat-certauth.log")
770 m.start_cockpit(tls=True)
771
772 # S4U ticket is in the session
773 b.open("/system/terminal")
774 b.enter_page("/system/terminal")
775 # WebGL2 is not supported in firefox headless mode
776 if b.browser != "firefox":
777 b.wait_in_text(".terminal .xterm-accessibility-tree", "alice")
778 b.input_text("klist\n")
779 b.wait_in_text(".terminal .xterm-accessibility-tree", "Ticket cache: FILE:/run/user")
780 b.wait_in_text(".terminal .xterm-accessibility-tree", "Default principal: [email protected]")
781 b.wait_in_text(".terminal .xterm-accessibility-tree", "for client HTTP/[email protected]")
782
783 self.assertIn("cockpit-session-", m.execute("ls /run/user/$(id -u alice)/*.ccache"))
784 ccache_env = m.execute("xargs -0n1 < /proc/$(pgrep cockpit-bridge)/environ | grep KRB5CCNAME=").strip()
785
786 # does not interfere with persistent ticket in other sessions
787 self.assertEqual(m.execute(alice_klist_cmd), persistent_ticket)
788
789 # destroy global user ccache, so that sudo/ssh really have to use the ccache_env one
790 m.execute("su -c 'kdestroy || true' alice")
791
792 # sanity check: sudo and ssh do not work without a ticket and password
793 self.assertIn("no askpass program", m.execute("su -c '! sudo -A whoami' alice 2>&1"))
794 self.assertIn("Permission denied", m.execute("su -c '! ssh x0.cockpit.lan 2>&1' alice"))
795
796 # in default configuration, ticket is not trusted by IPA
797 self.assertIn("no askpass program", m.execute(f"su -c '! {ccache_env} sudo -A whoami' alice 2>&1"))
798 self.assertIn("Permission denied", m.execute(f"su -c '! {ccache_env} ssh x0.cockpit.lan 2>&1' alice"))
799 b.switch_to_top()
800 b.open_superuser_dialog()
801 b.wait_text(".pf-v6-c-modal-box__title-text", "Switch to administrative access")
802 b.wait_in_text(".pf-v6-c-modal-box", "Password for alice:")
803 b.click(".pf-v6-c-modal-box .btn-cancel")
804 b.wait_not_present(".pf-v6-c-modal-box")
805
806 # set up delegation rule
807 script = """
808 ipa servicedelegationtarget-add cockpit-target
809 ipa servicedelegationtarget-add-member cockpit-target --principals="host/[email protected]"
810 ipa servicedelegationrule-add cockpit-delegation
811 ipa servicedelegationrule-add-member cockpit-delegation --principals="HTTP/[email protected]"
812 ipa servicedelegationrule-add-target cockpit-delegation --servicedelegationtargets="cockpit-target"
813 """
814 ipa_machine.execute(f"podman exec freeipa bash -euc '{script}'")
815
816 b.become_superuser(passwordless=True)
817 self.assertEqual("root\n", m.execute(f"su -c '{ccache_env} sudo -A whoami' alice"))
818
819 b.go("/system")
820 b.enter_page("/system")
821 b.wait_visible("#reboot-button")
822
823 # CLI ssh works with the delegated ticket
824 out = m.execute(f"su -c '{ccache_env} ssh -vv -K x0.cockpit.lan echo hello' alice")
825 self.assertEqual(out.strip(), "hello")
826
827 # cockpit session through ssh works with the delegated ticket
828 b.switch_to_top()
829 b.go("/@x0.cockpit.lan/system")
830 # only ack the addition of host, no authentication/password
831 b.click("#machine-troubleshoot")
832 b.wait_visible('#hosts_setup_server_dialog')
833 b.click('#hosts_setup_server_dialog button:contains("Add")')
834 b.wait_not_present('#hosts_setup_server_dialog')
835 b.wait_visible('#hosts_connect_server_dialog')
836 b.click('#hosts_connect_server_dialog button.pf-m-warning')
837
838 # Getting root privs through sudo with kerberos in the remote SSH session does not currently work.
839 # ssh -K is supposed to forward the credentials cache, but doesn't; klist in the ssh session is empty
840 # and there is no ccache.
841 b.enter_page("/system", "x0.cockpit.lan")
842 b.wait_in_text(".ct-limited-access-alert", "Web console is running in limited access mode.")
843 b.wait_not_present("#reboot-button")
844
845 # S4U proxy ticket gets cleaned up on logout
846 b.logout()
847 m.execute("while ls /run/user/$(id -u alice)/*.ccache; do sleep 1; done")
848 m.execute(f"! su -c '{ccache_env} klist' alice")
849
850
851 @testlib.skipImage("adcli not on test images", "debian-*", "ubuntu-*")
852 @testlib.no_retry_when_changed
853 class TestAD(TestRealms, CommonTests):
854 def setUp(self):
855 super().setUp()
856 self.admin_user = "Administrator"
857 self.admin_password = "foobarFoo123"
858 self.alice_password = 'WonderLand123'
859 self.expected_server_software = "active-directory"
860 self.machines['services'].execute("/root/run-samba-domain")
861
862 m = self.machine
863
864 # Wait for AD to come up and DNS to work as expected
865 testlib.wait(lambda: m.execute("nslookup -type=SRV _ldap._tcp.cockpit.lan"))
866 # DNS is not sufficient yet, needs to start LDAP server as well
867 m.execute("until nc -z f0.cockpit.lan 389; do sleep 1; done")
868 # also wait for Kerberos
869 m.execute(f"until echo {self.admin_password} | kinit {self.admin_user}@COCKPIT.LAN; do sleep 1; done; kdestroy")
870
871 # allow sudo access to domain admins; FIXME: Is there a server-side setting for this,
872 # similar to "ipa-advise enable-admins-sudo"?
873 m.write("/etc/sudoers.d/domain-admins", r"%domain\ [email protected] ALL=(ALL) ALL")
874
875 # HACK: Figure out why this happens
876 self.allow_journal_messages(""".*didn't receive expected "authorize" message""",
877 'cockpit-session:$')
878 self.allow_journal_messages('/bin/bash: /home/admin/.bashrc: Permission denied')
879
880 def checkBackendSpecifics(self):
881 """Check domain backend specific integration"""
882
883 def checkBackendSpecificCleanup(self):
884 """Check domain backend specific integration after leaving domain"""
885
886 def testUnqualifiedUsers(self):
887 """Extend the test to check a new AD user"""
888
889 super().testUnqualifiedUsers()
890
891 m = self.machine
892 b = self.browser
893
894 m.start_cockpit()
895 # create another AD user
896 self.machines['services'].execute(f"podman exec -i samba samba-tool user add alice {self.alice_password}")
897 # ensure it works
898 m.execute('while ! id alice; do sleep 5; done', timeout=300)
899 b.login_and_go('/system', user='alice', password=self.alice_password)
900 b.wait_visible("#overview")
901 b.logout()
902
903 def testClientCertAuthentication(self):
904 m = self.machine
905
906 services_machine = self.machines['services']
907 # samba has no default CA and no helpers, so just re-use our completely independent cockpit-tls unit test one
908 m.upload(["alice.pem", "alice.key"], "/var/tmp", relative_dir="src/tls/ca/")
909
910 with open("src/tls/ca/alice.pem") as f:
911 alice_cert = f.read().strip()
912 # mangle into form palatable for LDAP
913 alice_cert = ''.join([line for line in alice_cert.splitlines() if not line.startswith("----")])
914 # set up an AD user and import their TLS certificate
915 services_machine.write("/tmp/alice_edit", f'''#!/bin/sh -eu
916 sed -i "/^$/d" "$1"
917 echo "userCertificate: {alice_cert}" >> "$1"
918 ''', perm="755")
919 services_machine.execute(f"""
920 podman cp /tmp/alice_edit samba:/tmp/
921 podman exec -i samba sh -exc '
922 samba-tool user add alice {self.alice_password}
923 samba-tool user edit --editor=/tmp/alice_edit alice
924 # for debugging:
925 samba-tool user show alice
926 ' """, stdout=None)
927
928 # set up sssd for certificate mapping to AD
929 # see sssd.conf(5) "CERTIFICATE MAPPING SECTION" and sss-certmap(5)
930 m.write("/etc/sssd/conf.d/certmap.conf", """
931 [certmap/cockpit.lan/certs]
932 # our test certificates don't have EKU, and as we match full certificates it is not important to check anything here
933 matchrule = <KU>digitalSignature
934 # default rule; doesn't work because samba's LDAP doesn't understand ";binary"
935 # maprule = LDAP:(userCertificate;binary={cert!bin})
936 # match verbatim base64 certificate
937 maprule = LDAP:(userCertificate={cert!base64})
938 # match cert properties only; this looks at SubjectAlternativeName, which our test certs don't have
939 # this also requires CA validation in cockpit-tls or sssd, which we don't have yet
940 # maprule = (|(userPrincipalName={subject_principal})(sAMAccountName={subject_principal.short_name}))
941 """, perm="0600")
942 # tell sssd about our CA for validating certs
943 with open("src/tls/ca/ca.pem") as f:
944 m.write("/etc/sssd/pki/sssd_auth_ca_db.pem", f.read())
945
946 self.checkClientCertAuthentication()
947
948
949 JOIN_SCRIPT = """
950 set -ex
951 # Wait until zones from LDAP get loaded
952 for x in $(seq 1 20); do
953 if nslookup -type=SRV _ldap._tcp.cockpit.lan; then
954 break
955 else
956 sleep $x
957 fi
958 done
959
960 if ! echo '%(password)s' | realm join -vU admin cockpit.lan; then
961 if systemctl --quiet is-failed sssd.service; then
962 systemctl status --lines=100 sssd.service >&2
963 fi
964 journalctl -u realmd.service
965 exit 1
966 fi
967
968 # On certain OS's it takes time for sssd to come up properly
969 # [8347] 1528294262.886088: Sending initial UDP request to dgram 172.27.0.15:88
970 # kinit: Cannot contact any KDC for realm 'COCKPIT.LAN' while getting initial credentials
971 for x in $(seq 1 20); do
972 if echo '%(password)s' | KRB5_TRACE=/dev/stderr kinit -f [email protected]; then
973 break
974 else
975 sleep $x
976 fi
977 done
978
979 # create SPN and keytab for ws
980 if type ipa >/dev/null 2>&1; then
981 LC_ALL=C.UTF-8 ipa service-add --ok-as-delegate=true --force HTTP/[email protected]
982 else
983 curl --insecure -s --negotiate -u : \\
984 --header 'Referer: https://services.cockpit.lan/ipa' \\
985 --header "Content-Type: application/json" \\
986 --header "Accept: application/json" \\
987 --data '{"params":
988 [
989 ["HTTP/[email protected]"],
990 {"raw": false, "all": false, "version": "2.101",
991 "force": true, "no_members": false, "ipakrbokasdelegate": true}
992 ], "method": "service_add", "id": 0}' \\
993 https://services.cockpit.lan/ipa/json
994 fi
995 ipa-getkeytab -p HTTP/x0.cockpit.lan -k %(keytab)s
996
997 # HACK: due to sudo's "last rule wins", our /etc/sudoers rule becomes trumped by sssd's, so swap the order
998 sed -i '/^sudoers:/ s/files sss/sss files/' /etc/nsswitch.conf
999 """
1000
1001 # This is here because our test framework can't run ipa VM's twice
1002
1003
1004 @testlib.skipOstree("No realmd available")
1005 @testlib.skipWsContainer("No sssd PAM integration in beiboot mode")
1006 @testlib.skipImage("No realmd available", "arch")
1007 @testlib.skipImage("freeipa not currently available", "debian-*")
1008 @testlib.no_retry_when_changed
1009 class TestKerberos(testlib.MachineCase):
1010 provision = {
1011 "0": {"address": "10.111.113.1/20", "dns": "10.111.112.100"},
1012 "services": {"image": "services", "memory_mb": 2048}
1013 }
1014
1015 def setUp(self):
1016 super().setUp()
1017 maybe_setup_fake_chrony(self.machine)
1018 self.enable_multihost(self.machine)
1019
1020 def configure_kerberos(self, keytab):
1021 self.machines["services"].execute("/root/run-freeipa")
1022
1023 # Setup a place for kerberos caches
1024 args = {"addr": "10.111.112.100", "password": "foobarfoo", "keytab": keytab}
1025 self.machine.execute("hostnamectl set-hostname x0.cockpit.lan")
1026 if "ubuntu" in self.machine.image:
1027 # no nss-myhostname there
1028 self.machine.execute("echo '10.111.113.1 x0.cockpit.lan' >> /etc/hosts")
1029 self.machine.execute(JOIN_SCRIPT % args, timeout=1800)
1030 self.machine.execute(WAIT_KRB_SCRIPT.format("admin"), timeout=300)
1031
1032 def testNegotiate(self):
1033 self.allow_hostkey_messages()
1034 b = self.browser
1035 m = self.machine
1036
1037 # Tell realmd to not enable domain-qualified logins
1038 # (https://bugzilla.redhat.com/show_bug.cgi?id=1575538)
1039 m.write("/etc/realmd.conf", "[cockpit.lan]\nfully-qualified-names = no\n", append=True)
1040
1041 # delete the local admin user, going to use the IPA one instead
1042 m.execute("userdel --remove admin")
1043
1044 # HACK: There is no operating system where the domain admins can do passwordless sudo
1045 # while having a kerberos ticket, so we can't start a root bridge.
1046 # This is something that needs to be worked on at an OS level. We use admin level
1047 # features below, such as adding a machine to the host switcher
1048 m.execute("echo 'admin ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers")
1049
1050 # Make sure negotiate auth is not offered first
1051 m.start_cockpit()
1052
1053 output = m.execute('/usr/bin/curl -v -s '
1054 '--resolve x0.cockpit.lan:9090:10.111.113.1 '
1055 'http://x0.cockpit.lan:9090/cockpit/login 2>&1')
1056 self.assertIn("HTTP/1.1 401", output)
1057 self.assertNotIn("WWW-Authenticate: Negotiate", output)
1058
1059 self.configure_kerberos("/etc/cockpit/krb5.keytab")
1060 m.restart_cockpit()
1061
1062 # user has no cockpit kerberos session tickets initially
1063 m.execute("! ls /run/user/$(id -u admin)/*.ccache")
1064
1065 output = m.execute(['/usr/bin/curl', '-s', '--negotiate', '--delegation', 'always', '-u', ':', "-D", "-",
1066 '--resolve', 'x0.cockpit.lan:9090:10.111.113.1',
1067 'http://x0.cockpit.lan:9090/cockpit/login'])
1068 self.assertIn("HTTP/1.1 200 OK", output)
1069 self.assertIn('"csrf-token"', output)
1070
1071 cookie = re.search(r"Set-Cookie: cockpit=([^ ;]+)", output).group(1)
1072 b.open("/system/terminal", cookie={"name": "cockpit", "value": cookie, "domain": m.web_address, "path": "/"})
1073 b.wait_visible('#content')
1074
1075 # Remove failed units which will show up in the first terminal line
1076 m.execute("systemctl reset-failed")
1077
1078 # kerberos ticket got forwarded into the session
1079 b.enter_page("/system/terminal")
1080 # WebGL2 is not supported in firefox headless mode
1081 if b.browser != "firefox":
1082 # wait for prompt
1083 b.wait_in_text(".terminal .xterm-accessibility-tree", "admin")
1084 b.input_text("klist\n")
1085 b.wait_in_text(".terminal .xterm-accessibility-tree", "Ticket cache")
1086 b.wait_in_text(".terminal .xterm-accessibility-tree", "Default principal: [email protected]")
1087 b.wait_in_text(".terminal .xterm-accessibility-tree", "krbtgt/COCKPIT.LAN")
1088 self.assertIn("cockpit-session-", m.execute("ls /run/user/$(id -u admin)/*.ccache"))
1089
1090 # Now connect to another machine
1091 self.assertNotIn("admin", m.execute("ps -xa | grep sshd"))
1092 b.switch_to_top()
1093 b.go("/@x0.cockpit.lan/system/terminal")
1094 b.click("#machine-troubleshoot")
1095 b.wait_visible('#hosts_setup_server_dialog')
1096 b.click('#hosts_setup_server_dialog button:contains("Add")')
1097 b.wait_not_present('#hosts_setup_server_dialog')
1098 b.wait_visible('#hosts_connect_server_dialog')
1099 b.click('#hosts_connect_server_dialog button.pf-m-warning')
1100
1101 b.enter_page("/system/terminal", host="x0.cockpit.lan")
1102 # WebGL2 is not supported in firefox headless mode
1103 if b.browser != "firefox":
1104 b.wait_visible(".terminal")
1105
1106 # Make sure we connected via SSH
1107 self.assertIn("admin", m.execute("ps -xa | grep sshd"))
1108
1109 # forwarded ticket gets cleaned up with the session; this is not completely synchronous
1110 b.logout()
1111 m.execute("while ls /run/user/$(id -u admin)/*.ccache; do sleep 1; done", timeout=10)
1112
1113 # Remove cockpit keytab
1114 m.execute("mv /etc/cockpit/krb5.keytab /etc/cockpit/bk.keytab")
1115 output = m.execute(['/usr/bin/curl', '-s', '--negotiate', '--delegation', 'always', '-u', ':', "-D", "-",
1116 '--resolve', 'x0.cockpit.lan:9090:10.111.113.1',
1117 'http://x0.cockpit.lan:9090/cockpit/login'])
1118 self.assertIn("HTTP/1.1 401", output)
1119
1120 # Pull http into default keytab
1121 m.execute('printf "rkt /etc/cockpit/bk.keytab\nwkt /etc/krb5.keytab\nq" | ktutil')
1122 output = m.execute(['/usr/bin/curl', '-s', '--negotiate', '--delegation', 'always', '-u', ':', "-D", "-",
1123 '--resolve', 'x0.cockpit.lan:9090:10.111.113.1',
1124 'http://x0.cockpit.lan:9090/cockpit/login'])
1125 self.assertIn("HTTP/1.1 200 OK", output)
1126 self.assertIn('"csrf-token"', output)
1127
1128 m.write("/etc/cockpit/cockpit.conf", "[Negotiate]\naction = none\n", append=True)
1129 m.restart_cockpit()
1130 output = m.execute(['/usr/bin/curl', '-s', '--negotiate', '--delegation', 'always', '-u', ':', "-D", "-",
1131 '--resolve', 'x0.cockpit.lan:9090:10.111.113.1',
1132 'http://x0.cockpit.lan:9090/cockpit/login'])
1133 self.assertIn("HTTP/1.1 401 Authentication disabled", output)
1134 self.allow_journal_messages(".*Request ticket server HTTP/[email protected] not found in keytab.*")
1135
1136
1137 @testlib.skipImage("No realmd available", "arch")
1138 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
1139 @testlib.skipOstree("Package (un)install does not work on OSTree")
1140 class TestPackageInstall(packagelib.PackageCase):
1141
1142 def setUp(self):
1143 super().setUp()
1144 self.domain_sel = "#system_information_domain_button"
1145
1146 self.machine.execute("systemctl stop realmd")
1147
1148 def waitTooltip(self, text):
1149 b = self.browser
1150
1151 # the wait_timeout affects both the waiting in b.mouse() and the b.wait() (times 5!), thus is quadratic
1152 with b.wait_timeout(4):
1153 def check():
1154 try:
1155 b.mouse("#system_information_domain_tooltip", "mouseenter")
1156 b.wait_in_text("div.pf-v6-c-tooltip", text)
1157 b.mouse("#system_information_domain_tooltip", "mouseleave")
1158 return True
1159 except (RuntimeError, testlib.Error):
1160 return False
1161 b.wait(check)
1162
1163 def testInstall(self):
1164 m = self.machine
1165 b = self.browser
1166
1167 m.execute("dpkg --purge realmd 2>/dev/null || rpm --erase realmd || dnf remove -y realmd")
1168
1169 # case 1: disable package backend
1170 if self.backend == 'dnf5':
1171 m.execute("systemctl mask dnf5daemon-server; systemctl stop dnf5daemon-server.service || true")
1172 m.execute("systemctl mask packagekit; systemctl stop packagekit.service || true")
1173 self.allow_browser_errors('checkRealm failed.*"problem":"not-found"')
1174 self.login_and_go("/system")
1175 b.wait_text(self.domain_sel, "Join domain")
1176 b.wait_visible(self.domain_sel + "[disabled]")
1177 self.waitTooltip("realmd is not available on this system")
1178 b.logout()
1179
1180 # case 2: enable package backend, but no realmd package available
1181 if self.backend == 'dnf5':
1182 m.execute("systemctl unmask dnf5daemon-server")
1183 m.execute("systemctl unmask packagekit")
1184 self.login_and_go("/system")
1185 # Joining a domain should bring up the install dialog
1186 b.wait_text(self.domain_sel, "Install realmd support")
1187 self.waitTooltip("requires installation of realmd")
1188
1189 b.click(self.domain_sel)
1190 b.wait_text(".pf-v6-c-modal-box__header", "Install software")
1191 with b.wait_timeout(30):
1192 b.wait_in_text(".pf-v6-c-modal-box", "realmd is not available")
1193 b.wait_visible(".pf-v6-c-modal-box__footer button.pf-m-primary:disabled")
1194 b.click(".pf-v6-c-modal-box .pf-v6-c-modal-box__footer button.cancel")
1195 b.wait_not_present(".pf-v6-c-modal-box")
1196 b.logout()
1197
1198 # case 3: provide an available realmd package
1199 self.createPackage("realmd", "1", "1", content={"/realmd-stub": ""})
1200 self.enableRepo(refresh_repo=self.backend != "dnf5")
1201
1202 self.login_and_go("/system")
1203
1204 # Joining a domain should bring up the install dialog
1205 b.wait_text(self.domain_sel, "Install realmd support")
1206 self.waitTooltip("requires installation of realmd")
1207
1208 b.click(self.domain_sel)
1209 b.click(".pf-v6-c-modal-box .pf-v6-c-modal-box__footer button.pf-m-primary")
1210 b.wait_not_in_text(".pf-v6-c-modal-box__header", "Install software")
1211 # The dialog changes into a Join Domain dialog
1212 b.wait_text(".pf-v6-c-modal-box__header", "Join a domain")
1213
1214 # the stub package doesn't provide a realmd D-Bus service, so the "join
1215 # domain" dialog won't ever appear; just check that it was installed
1216 m.execute("test -e /realmd-stub")
1217
1218 @testlib.nondestructive
1219 def testDialogTransition(self):
1220 m = self.machine
1221 b = self.browser
1222
1223 # disable the realmd package's service, so that we can restore it, but
1224 # the package install code path will be triggered
1225 m.execute("systemctl stop realmd; systemctl mask realmd")
1226
1227 self.login_and_go("/system")
1228
1229 # Joining a domain should bring up the install dialog
1230 b.wait_text(self.domain_sel, "Install realmd support")
1231 self.waitTooltip("requires installation of realmd")
1232
1233 b.click(self.domain_sel)
1234 # restore realmd service, to pretend that package install completed
1235 m.execute("systemctl unmask realmd")
1236 b.wait_text(".pf-v6-c-modal-box__header", "Install software")
1237 b.click(".pf-v6-c-modal-box .pf-v6-c-modal-box__footer button.pf-m-primary")
1238 b.wait_not_in_text(".pf-v6-c-modal-box__header", "Install software")
1239
1240 # should continue straight to join dialog
1241 b.wait_visible("#realms-join-dialog")
1242
1243 # no auto-detected domain/admin
1244 with b.wait_timeout(60):
1245 b.wait_attr("#realms-op-address", "data-discover", "done")
1246 self.assertEqual(b.val("#realms-op-address"), "")
1247 self.assertEqual(b.val("#realms-op-admin"), "")
1248
1249 # no running IPA server for this test, so just cancel
1250 b.click("#realms-join-dialog button.pf-m-link")
1251 b.wait_not_present("#realms-join-dialog")
1252
1253 # should not have a tooltip any more
1254 b.wait_not_present("#system_information_domain_tooltip")
1255
1256
1257 if __name__ == '__main__':
1258 testlib.test_main()