Debian Codegraph @

test/verify/check-static-login

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 re
10 import subprocess
11 import time
12
13 import testlib
14
15
16 @testlib.nondestructive
17 class TestLogin(testlib.MachineCase):
18 def check_shell(self):
19 b = self.browser
20 b.wait_visible("#content")
21 b.wait_text('#current-username', 'admin')
22 if self.multihost_enabled:
23 b.set_layout("mobile")
24 b.click("#hosts-sel button")
25 b.wait_in_text(".view-hosts .pf-m-current", "admin @")
26 b.click("#hosts-sel button")
27 b.set_layout("desktop")
28
29 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
30 def testBasic(self):
31 m = self.machine
32 b = self.browser
33
34 # Setup users and passwords
35 m.execute("useradd user -c 'Barney Bär'")
36 m.execute("echo user:abcdefg | chpasswd")
37
38 admins_only_pam = """account sufficient pam_succeed_if.so uid = 0\\
39 account required pam_succeed_if.so user ingroup %s""" % m.get_admin_group()
40
41 # Setup a special PAM config that disallows non-wheel users
42 def deny_non_root(remote_filename):
43 if m.image == "arch":
44 self.sed_file(f'1 a {admins_only_pam}', remote_filename)
45 else:
46 self.sed_file(f'/nologin/a {admins_only_pam}', remote_filename)
47
48 if not m.ws_container:
49 deny_non_root("/etc/pam.d/cockpit")
50 deny_non_root("/etc/pam.d/sshd")
51
52 m.start_cockpit()
53 b.open("/system")
54
55 # Test banner
56 # Test that we don't show banner when not specified
57 b.wait_visible("#login-user-input")
58 b.wait_not_visible("#banner")
59
60 if m.ws_container:
61 m.execute("podman exec ws printf '[Session]\nBanner = /host/etc/issue\n' > /etc/cockpit/cockpit.conf")
62 else:
63 m.execute("printf '[Session]\nBanner = /etc/issue\n' > /etc/cockpit/cockpit.conf")
64 m.restart_cockpit()
65 b.reload()
66 b.wait_visible("#login-user-input")
67 b.wait_visible("#banner")
68 self.assertEqual(b.text("#banner-message"), m.execute("cat /etc/issue").rstrip())
69
70 # Test non existent file
71 m.execute("printf '[Session]\nBanner = /etc/non-existing-file\n' > /etc/cockpit/cockpit.conf")
72 self.allow_journal_messages("error loading contents of banner: Failed to open file “/etc/non-existing-file”: No such file or directory")
73 m.restart_cockpit()
74 b.reload()
75 b.wait_visible("#login-user-input")
76 b.wait_not_visible("#banner")
77
78 def cockpit_sessions():
79 """Return list of users who have a running Cockpit session"""
80 # unfortunately the session type isn't part of the list view/query
81 # --json=short is very recent, not yet available in Fedora 40 and older; so parse lines
82 users = []
83 for line in m.execute("loginctl --no-legend list-sessions").strip().splitlines():
84 fields = line.split()
85 info = m.execute(f"loginctl show-session {fields[0]}")
86 if "Type=web" in info and "State=closing" not in info:
87 users.append(fields[2])
88 return users
89
90 # Try to login as a non-existing user
91 b.try_login("nonexisting", "blahblah")
92 b.wait_text("#login-error-title", "Authentication failed")
93 b.wait_text("#login-error-message", "Wrong user name or password")
94 self.assertEqual(cockpit_sessions(), [])
95
96 # Try to login as user with a wrong password
97 b.try_login("user", "gfedcba")
98 b.wait_text_not("#login-error-message", "")
99 self.assertEqual(cockpit_sessions(), [])
100 self.allow_journal_messages(".* user: Authentication failure.*")
101
102 # Try to login as user with correct password
103 b.try_login("user", "abcdefg")
104 b.wait_text("#login-error-title", "Authentication failed" if m.ws_container else "Permission denied")
105 self.assertEqual(cockpit_sessions(), [])
106
107 # Try to login with disabled shell; this does not work on OSTree where
108 # we log in through ssh
109 if not m.ws_container:
110 try:
111 m.execute("usermod --shell /bin/false admin; sync")
112 journal_cursor = self.machine.journal_cursor()
113 b.reload()
114 b.try_login("admin", "foobar")
115 b.wait_text("#login-error-title", "Authentication failed")
116 # arch enforces pam_shells, so it fails already in PAM auth
117 if m.image != "arch":
118 b.wait_in_text("#login-error-message", "Unsupported shell")
119
120 testlib.wait(
121 lambda: re.search(
122 r'User admin shell.*/bin/false.*exit 71.*unsupported',
123 m.execute(f"journalctl -ocat --cursor '{journal_cursor}' SYSLOG_IDENTIFIER=cockpit-session")
124 ),
125 tries=10)
126 finally:
127 m.execute("usermod --shell /bin/bash admin; sync")
128
129 # Login as admin
130 b.open("/system")
131 b.login_and_go()
132 self.check_shell()
133
134 if not m.ws_container: # logs in via ssh, not cockpit-session
135 # older coreutils shows the session type (web), newer ones the service name
136 self.assertEqual(cockpit_sessions(), ["admin"])
137
138 # reload, which should log us in with the cookie
139 b.reload()
140 self.check_shell()
141
142 if not m.ws_container: # logs in via ssh, not cockpit-session
143 self.assertEqual(cockpit_sessions(), ["admin"])
144
145 b.go("/users#/admin")
146 b.enter_page("/users")
147 b.wait_text("#account-user-name", "admin")
148 try:
149 m.execute("journalctl -p 7 SYSLOG_IDENTIFIER=cockpit-ws | grep 'cockpit-session: opening pam session'")
150 self.fail("cockpit-session debug messages found")
151 except subprocess.CalledProcessError:
152 pass
153
154 # Change login screen options
155 b.logout()
156 self.assertEqual(cockpit_sessions(), [])
157 b.wait_visible("#option-group")
158 m.execute("printf '[WebService]\nLoginTo = false\n' > /etc/cockpit/cockpit.conf")
159 m.restart_cockpit()
160 b.open("/system")
161 b.wait_visible("#login")
162 b.wait_not_visible("#option-group")
163
164 # LoginTo= also disables direct URL
165 b.open("/=192.168.99.99/")
166 b.wait_visible("#login")
167 b.wait_not_visible("#option-group")
168 # logging in does not go via ssh (which would cause a connection failure)
169 b.try_login()
170 # this isn't the most helpful error message, but this is essentially hacking
171 b.wait_text("#login-error-title", "Authentication failed")
172 b.wait_text("#login-error-message", "Wrong user name or password")
173
174 # Default options be to display these options
175 m.execute("rm /etc/cockpit/cockpit.conf")
176 m.restart_cockpit()
177 b.open("/system")
178 b.wait_visible("#option-group")
179
180 # And now we remove ssh which affects the default
181 if not m.ws_container:
182 m.execute("mount -o bind /dev/null /usr/bin/ssh")
183 self.addCleanup(m.execute, "umount /usr/bin/ssh")
184 m.restart_cockpit()
185 b.open("/system")
186 b.wait_visible("#login")
187 b.wait_not_visible("#option-group")
188
189 # test login with tcsh
190 if not m.image.startswith("rhel") and not m.image.startswith("centos") and not m.image == "arch": # no tcsh in RHEL and in Arch Linux (TODO: available in [community])
191 try:
192 m.execute("sed -r -i.bak '/^admin:/ s_:[^:]+$_:/bin/tcsh_' /etc/passwd")
193 b.login_and_go()
194 b.enter_page('/system')
195 b.wait_visible('.system-information')
196 b.logout()
197 finally:
198 m.execute("mv /etc/passwd.bak /etc/passwd")
199
200 # login with user shell that prints some stdout/err noise
201 # having stdout output in ~/.bashrc confuses docker, so don't run on OSTree
202 m.execute("cd ~admin; [ ! -e .bashrc ] || cp -a .bashrc .bashrc.bak; [ ! -e .profile ] || cp -a .profile .profile.bak; "
203 "echo 'echo noise-rc-out; echo noise-rc-err >&2' >> .bashrc; "
204 "echo 'echo noise-profile-out; echo noise-profile-err >&2' >> .profile")
205 self.addCleanup(m.execute, "cd ~admin; if [ -e .bashrc.bak ]; then mv .bashrc.bak .bashrc; fi; "
206 "if [ -e .profile.bak ]; then mv .profile.bak .profile; else rm .profile; fi")
207 b.login_and_go()
208
209 self.allow_journal_messages(r"pam_unix\(cockpit:auth\): authentication failure; .*",
210 r"pam_unix\(cockpit:auth\): check pass; user unknown",
211 r"pam_succeed_if\(cockpit:auth\): requirement .* not met by user .*",
212 "noise-rc-.*")
213
214 @testlib.skipWsContainer("logs in via ssh, not cockpit-session")
215 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
216 def testLogging(self):
217 m = self.machine
218 b = self.browser
219
220 def assert_messages(has_last, n_fail):
221 if has_last:
222 b.wait_in_text('#system_last_login', "Last successful login")
223 b.wait_in_text('#system_last_login_from',
224 # this is the correct IP for our CI, and we don't run this on tmt
225 "from ::ffff:172.27.0.2 on web console") # only present if IP was logged
226
227 if n_fail:
228 b.wait_in_text('#system_last_login', f'{n_fail} failed login')
229 b.wait_in_text('#system_last_login_from', "from")
230 b.wait_in_text('#system_last_login_success', "Last successful login")
231 else:
232 self.assertFalse(b.is_present('#system_last_login_success'))
233
234 def verify_correct(has_last, n_fail):
235 b.login_and_go('/system')
236 assert_messages(has_last, n_fail)
237
238 # reload and make sure it's still there (or not)
239 b.reload()
240 b.enter_page('/system')
241 assert_messages(has_last, n_fail)
242
243 b.logout()
244
245 m.start_cockpit()
246
247 # Clean out the relevant logfiles
248 m.execute("truncate -s0 /var/log/{[bw]tmp{,.db},lastlog} /run/utmp")
249
250 if m.image == "arch":
251 self.sed_file("s/# deny = 3/deny = 4/", "/etc/security/faillock.conf")
252
253 # First login should have no messages
254 verify_correct(has_last=False, n_fail=0)
255
256 # Next login should see the last login
257 verify_correct(has_last=True, n_fail=0)
258
259 # Do some bogus login attempts
260 b.try_login('admin', 'xyz')
261 b.wait_text("#login-error-title", "Authentication failed")
262 b.try_login('admin', 'xyz')
263 b.wait_text("#login-error-title", "Authentication failed")
264 b.try_login('admin', 'xyz')
265 b.wait_text("#login-error-title", "Authentication failed")
266
267 # Some OSes are getting rid of /var/log/btmp, which means
268 # Cockpit will not report failed login attempts.
269 if m.execute("test -f /var/log/btmp || echo no").strip() != "no":
270 # We should see those bogus attempts now
271 verify_correct(has_last=False, n_fail=3)
272 # But after that login, they should be gone again
273 verify_correct(has_last=True, n_fail=0)
274 else:
275 # The failed attempts are not shown.
276 verify_correct(has_last=True, n_fail=0)
277
278 @testlib.skipImage("Arch Linux has no pwquality by default", "arch")
279 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
280 def testExpired(self):
281 m = self.machine
282 b = self.browser
283
284 # With the ws container this happens over ssh and we need
285 # ChallengeResponseAuthentication (or
286 # KbdInteractiveAuthentication, it's new name) to be allowed.
287 # Without that, OpenSSH will do the required password change
288 # without PAM and by running "/bin/passwd" instead.
289 #
290 if m.ws_container:
291 self.restore_dir("/etc/ssh", restart_unit=self.sshd_service)
292 m.execute("sed -i 's/.*ChallengeResponseAuthentication.*/ChallengeResponseAuthentication yes/' "
293 "/etc/ssh/sshd_config $(ls /etc/ssh/sshd_config.d/* 2>/dev/null || true)")
294 m.execute("sed -i 's/.*KbdInteractiveAuthentication.*/KbdInteractiveAuthentication yes/' "
295 "/etc/ssh/sshd_config $(ls /etc/ssh/sshd_config.d/* 2>/dev/null || true)")
296 m.execute(self.restart_sshd)
297
298 # test steps below assume a pam_pwquality config with retry > 1; on some images authselect drops that setting
299 if not m.image.startswith('debian') and not m.image.startswith('ubuntu') and not m.image.startswith("arch"):
300 self.sed_file("/password.*requisite.*pam_pwquality/ s/$/ retry=3/", "/etc/pam.d/password-auth")
301
302 m.execute("chage -d 0 admin")
303 m.start_cockpit()
304 b.open("/system")
305
306 b.wait_visible("#login")
307 b.wait_not_visible("#conversation-group")
308 b.wait_visible("#password-group")
309 b.wait_visible("#user-group")
310 b.set_val('#login-user-input', "admin")
311 b.set_val('#login-password-input', "foobar")
312 b.click('#login-button')
313
314 b.wait_visible("#conversation-group")
315 b.wait_not_visible("#password-group")
316 b.wait_not_visible("#user-group")
317 if m.ws_container:
318 b.wait_in_text("#conversation-prompt", "You are required to change your password")
319 else:
320 b.wait_in_text("#conversation-message", "You are required to change your password")
321 b.set_val('#conversation-input', 'foobar')
322 b.click('#login-button')
323
324 # Type a bad password
325 b.wait_visible("#conversation-group")
326 b.wait_not_visible("#password-group")
327 b.wait_not_visible("#user-group")
328
329 b.wait_in_text("#conversation-prompt", "New password")
330 b.set_val('#conversation-input', 'admin')
331 b.click('#login-button')
332
333 # We should see a message
334 if m.ws_container:
335 b.wait_in_text("#conversation-prompt", "BAD PASSWORD")
336 else:
337 b.wait_in_text("#conversation-message", "BAD PASSWORD")
338
339 # Now choose a better password
340 b.wait_not_present("#login-button:disabled")
341 b.wait_visible("#conversation-group")
342 b.wait_not_visible("#password-group")
343 b.wait_not_visible("#user-group")
344 b.wait_in_text("#conversation-prompt", "New password")
345 b.set_val('#conversation-input', '123foobar!@#')
346 b.click('#login-button')
347
348 # Retype the password wrong
349 b.wait_visible("#conversation-group")
350 b.wait_not_visible("#password-group")
351 b.wait_not_visible("#user-group")
352 b.wait_in_text("#conversation-prompt", "Retype")
353 b.set_val('#conversation-input', '123foobar!') # wrong
354 b.click('#login-button')
355
356 # We should see a message
357 if m.ws_container:
358 b.wait_in_text("#conversation-prompt", "passwords do not match")
359 else:
360 b.wait_in_text("#conversation-message", "passwords do not match")
361
362 # Type the password again
363 b.wait_visible("#conversation-group")
364 b.wait_not_visible("#password-group")
365 b.wait_not_visible("#user-group")
366
367 b.wait_in_text("#conversation-prompt", "New password")
368 b.set_val('#conversation-input', '123foobar!@#')
369 b.click('#login-button')
370
371 # Now type it right
372 b.wait_visible("#conversation-group")
373 b.wait_not_visible("#password-group")
374 b.wait_not_visible("#user-group")
375 b.wait_in_text("#conversation-prompt", "Retype")
376 b.set_val('#conversation-input', '123foobar!@#')
377 b.click('#login-button')
378
379 self.check_shell()
380
381 self.allow_journal_messages('.*You are required to change your password immediately.*',
382 '.*user account or password has expired.*',
383 '.*BAD PASSWORD.*',
384 '.*Sorry, passwords do not match.')
385 self.allow_restart_journal_messages()
386
387 @testlib.skipWsContainer("mock-pam-conv not installed")
388 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
389 def testConversation(self):
390 m = self.machine
391 b = self.browser
392 conf = "/etc/pam.d/cockpit"
393 if m.ostree_image:
394 conf = "/etc/pam.d/sshd"
395 self.restore_dir("/etc/ssh", restart_unit=self.sshd_service)
396 m.execute("sed -i 's/.*ChallengeResponseAuthentication.*/ChallengeResponseAuthentication yes/' "
397 "/etc/ssh/sshd_config $(ls /etc/ssh/sshd_config.d/* 2>/dev/null || true)")
398 m.execute(self.restart_sshd)
399
400 # On Arch Linux the ordering matters due to an auth include for system-remote-login
401 if self.machine.image == "arch":
402 self.sed_file('1 a auth required mock-pam-conv-mod.so', conf)
403 else:
404 self.sed_file('5 a auth required mock-pam-conv-mod.so', conf)
405
406 m.start_cockpit()
407 b.open("/system")
408
409 # Try to login as a non-existing user
410 b.try_login("nonexisting", "blahblah")
411
412 b.wait_visible("#conversation-group")
413 b.wait_not_visible("#password-group")
414 b.wait_not_visible("#user-group")
415 b.wait_in_text("#conversation-prompt", "life the universe")
416 b.set_val('#conversation-input', '43')
417 b.click('#login-button')
418 if m.ws_container:
419 # ssh asks for password again, despite NumberOfPasswordPrompts=1
420 b.wait_in_text("#conversation-prompt", "[email protected]'s password")
421 b.set_val('#conversation-input', 'blahblah')
422 b.click('#login-button')
423 b.wait_text_not("#login-error-title", "")
424
425 b.try_login("admin", "foobar")
426 b.wait_visible("#conversation-group")
427 b.wait_not_visible("#password-group")
428 b.wait_not_visible("#user-group")
429 b.wait_in_text("#conversation-prompt", "life the universe")
430 b.set_val('#conversation-input', '42')
431 b.click('#login-button')
432
433 self.check_shell()
434
435 self.allow_restart_journal_messages()
436
437 @testlib.skipImage("No tlog", "debian-*", "ubuntu-*", "arch", "opensuse-tumbleweed")
438 @testlib.skipOstree("No tlog")
439 @testlib.skipImage("FIXME: tlog messes up bridge frame protocol", "rhel-8-10")
440 def testSessionRecordingShell(self):
441 m = self.machine
442 b = self.browser
443
444 m.execute("useradd user --shell /usr/bin/tlog-rec-session")
445 m.execute("echo user:abcdefg | chpasswd")
446 # this doesn't actually record anything, but logging into cockpit should work
447 m.start_cockpit()
448 b.login_and_go("/system", user="user", password="abcdefg")
449 b.wait_visible(".pf-v6-c-alert:contains('Web console is running in limited access mode.')")
450 b.logout()
451
452 self.allow_journal_messages(".*value for the SHELL variable was not found the /etc/shells.*",
453 "Locale charset is ANSI.*",
454 "Assuming locale environment is lost.*",
455 "ATTENTION! Your session is being recorded!")
456
457 def curl_auth(self, url, userpass):
458 header = "Authorization: Basic " + base64.b64encode(userpass.encode()).decode()
459 return subprocess.check_output(['/usr/bin/curl', '-s', '-k', '-D', '-', '--header', header,
460 f'http://{self.machine.web_address}:{self.machine.web_port}{url}'],
461 text=True)
462
463 def curl_auth_code(self, url, userpass):
464 lines = self.curl_auth(url, userpass).splitlines()
465 self.assertGreater(len(lines), 0)
466 tokens = lines[0].split(' ', 2)
467 self.assertEqual(len(tokens), 3)
468 return int(tokens[1])
469
470 def testRaw(self):
471 self.machine.start_cockpit()
472 time.sleep(0.5)
473 self.assertEqual(self.curl_auth_code('/cockpit/login', ''), 401)
474 self.assertEqual(self.curl_auth_code('/cockpit/login', 'foo:'), 401)
475 self.assertEqual(self.curl_auth_code('/cockpit/login', 'foo:bar\n'), 401)
476 self.assertEqual(self.curl_auth_code('/cockpit/login', 'foo:bar:baz'), 401)
477 self.assertEqual(self.curl_auth_code('/cockpit/login', ':\n\n'), 401)
478 self.assertIn(self.curl_auth_code('/cockpit/login', 'admin:bar'), [401, 403])
479 self.assertEqual(self.curl_auth_code('/cockpit/login', 'foo:bar'), 401)
480 self.assertIn(self.curl_auth_code('/cockpit/login', 'admin:' + 'x' * 4000), [401, 403])
481 self.assertEqual(self.curl_auth_code('/cockpit/login', 'x' * 4000 + ':bar'), 401)
482 self.assertEqual(self.curl_auth_code('/cockpit/login', 'a' * 4000 + ':'), 401)
483 self.assertEqual(self.curl_auth_code('/cockpit/login', 'a' * 4000 + ':b\nc'), 401)
484 self.assertEqual(self.curl_auth_code('/cockpit/login', 'a' * 4000 + ':b\nc\n'), 401)
485
486 self.allow_journal_messages("Returning error-response ... with reason .*",
487 r"pam_unix\(cockpit:auth\): authentication failure; .*",
488 r"pam_unix\(cockpit:auth\): check pass; user unknown",
489 r"pam_succeed_if\(cockpit:auth\): requirement .* not met by user .*",
490 "couldn't parse login input: Malformed input",
491 "couldn't parse login input: Authentication failed")
492
493 @testlib.skipImage("No SELinux", "debian-*", "ubuntu-*", "arch")
494 @testlib.skipOstree("No semanage")
495 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
496 def testSELinuxRestrictedUser(self):
497 m = self.machine
498 b = self.browser
499
500 # non-admin user_u
501 m.execute("useradd unpriv; echo 'unpriv:foobar' | chpasswd; semanage login -a -s user_u unpriv")
502 self.addCleanup(m.execute, "semanage login -d -s user_u unpriv")
503 m.start_cockpit()
504 b.login_and_go("/system", user="unpriv")
505 # generate lastlog entry
506 b.logout()
507 b.login_and_go("/system", user="unpriv")
508 # not an admin
509 b.wait_visible(".pf-v6-c-alert:contains('Web console is running in limited access mode.')")
510
511 # ws container does not keep login history
512 if not m.ws_container:
513 b.wait_in_text('#system_last_login', "Last successful login")
514 b.wait_in_text('#system_last_login_from', "web console")
515
516 b.logout()
517 # not allowed to restricted users
518 self.allow_journal_messages('.*type=1400.*avc: denied { map }.*comm="cockpit-pcp".*')
519 self.allow_journal_messages('.*type=1400.*avc: denied .* comm="sudo".*')
520 self.allow_journal_messages('.*type=1400.*avc: denied .* comm="systemd".*')
521 self.allow_journal_messages('.*type=1400.*avc: denied { watch } .* comm="cockpit-bridge".*')
522 self.allow_journal_messages('.*sudo:.* setresuid(.*): Operation not permitted')
523 self.allow_journal_messages('.*sudo: error initializing audit plugin sudoers_audit')
524 # https://bugzilla.redhat.com/show_bug.cgi?id=1727887
525 self.allow_journal_messages('.*type=1400.*avc: denied { connectto } .* path="/run/user/.*/bus" scontext=user_u:user_r:user_t:s0.*')
526
527 # sysadm_u
528 # not allowed by default in RHEL 8
529 if m.image.startswith("rhel-8"):
530 m.execute("setsebool -P ssh_sysadm_login 1")
531 self.addCleanup(m.execute, "setsebool -P ssh_sysadm_login 0")
532 m.execute("useradd priv; echo 'priv:foobar' | chpasswd")
533 m.execute("usermod -aG wheel priv")
534 m.execute("semanage login -a -s sysadm_u priv")
535 self.addCleanup(m.execute, "semanage login -d -s sysadm_u priv")
536 b.login_and_go("/system", user="priv")
537 # passing login info memfd should work
538 b.logout()
539 b.login_and_go("/system", user="priv")
540 # ws container does not keep login history
541 if not m.ws_container:
542 b.wait_in_text('#system_last_login', "Last successful login")
543 b.wait_in_text('#system_last_login_from', "web console")
544
545 b.go("/playground/test")
546 b.enter_page("/playground/test")
547 b.click(".super-channel button")
548 b.wait_in_text(".super-channel span", 'result: ')
549
550 if m.image.startswith("rhel-8"):
551 # https://bugzilla.redhat.com/show_bug.cgi?id=1814569
552 self.assertIn('result: access-denied', b.text(".super-channel span"))
553 else:
554 self.assertIn('result: uid=0', b.text(".super-channel span"))
555
556 def testNoAdminGroup(self):
557 m = self.machine
558 b = self.browser
559
560 # Create a user that is not in wheel but can sudo
561 m.execute("useradd user -s /bin/bash -c User")
562 m.execute("echo user:foobar | chpasswd")
563 self.write_file("/etc/sudoers.d/user", "user ALL=(ALL) ALL")
564 self.password = "foobar"
565
566 self.login_and_go("/system", user="user")
567
568 # session is privileged
569 b.switch_to_top()
570 b.check_superuser_indicator("Administrative access")
571 b.enter_page('/system')
572
573 # shutdown button should be enabled and working
574 b.click("#reboot-button")
575 b.wait_popup("shutdown-dialog")
576 b.wait_in_text(f"#shutdown-dialog button{self.danger_btn_class}", 'Reboot')
577 b.click("#delay")
578 b.click("button:contains('5 minutes')")
579 b.wait_text("#delay .pf-v6-c-menu-toggle__text", "5 minutes")
580 b.click(f"#shutdown-dialog button{self.danger_btn_class}")
581
582 # cancel reboot
583 b.wait_in_text('#system-health-shutdown-status-text', "Scheduled reboot")
584 b.click("#system-health-shutdown-status-cancel-btn")
585 b.wait_not_present('#system-health-shutdown-status')
586
587 def testUnsupportedBrowser(self):
588 m = self.machine
589 b = self.browser
590
591 m.start_cockpit()
592 # pretend browser doesn't support a required capability
593 b.bidi("script.addPreloadScript", functionDeclaration="""() => {
594 window.WebSocket = undefined; }""")
595 b.open("/system")
596 b.wait_visible("#unsupported-browser")
597 b.wait_not_visible("#login-fatal")
598 b.wait_not_visible("#login")
599 b.wait_not_visible("#login-details")
600
601 def testBypassSoftRequirements(self):
602 m = self.machine
603 b = self.browser
604
605 m.start_cockpit()
606 b.bidi("script.addPreloadScript", functionDeclaration="""() => {
607 window.CSS.supports = () => false; }""")
608 b.open("/system")
609 b.wait_visible("#unsupported-browser")
610 b.wait_in_text("#bypass-browser-check", "Bypass browser check")
611 b.click(".pf-v6-c-expandable-section")
612
613 b.set_val('#login-user-input', "admin")
614 b.set_val('#login-password-input', "foobar")
615 b.click("#login-button")
616
617 self.check_shell()
618
619 @testlib.skipWsContainer("no local config with cockpit/ws container")
620 def testFailingWebsocket(self, safari=False, cacert=False):
621 m = self.machine
622 b = self.browser
623
624 # Cause cockpit-ws to reject WebSocket connections
625 m.write("/etc/cockpit/cockpit.conf", "[WebService]\nOrigins=foo.bar.com\n")
626 self.allow_journal_messages("received request from bad Origin: .*",
627 "connection unexpectedly closed by peer",
628 "Received invalid handshake request from the client")
629 self.allow_browser_errors(".*")
630
631 m.start_cockpit()
632
633 if safari:
634 b.set_user_agent("Safari/300")
635
636 if cacert:
637 m.write("/etc/cockpit/ws-certs.d/0-self-signed-ca.pem", "FAKE CERT FOR TESTING\n")
638 else:
639 m.execute("rm -f /etc/cockpit/ws-certs.d/0-self-signed-ca.pem")
640
641 b.open("/system")
642 b.try_login()
643
644 b.wait_visible("#early-failure")
645 if safari and cacert:
646 b.wait_visible("#safari-cert-help")
647 else:
648 b.wait_not_present("#safari-cert-help")
649
650 @testlib.skipBrowser("Enough when only chromium pretends to be a different browser", "firefox")
651 @testlib.skipWsContainer("no local config with cockpit/ws container")
652 def testFailingWebsocketSafari(self):
653 self.testFailingWebsocket(safari=True, cacert=True)
654
655 @testlib.skipBrowser("Enough when only chromium pretends to be a different browser", "firefox")
656 @testlib.skipWsContainer("no local config with cockpit/ws container")
657 def testFailingWebsocketSafariNoCA(self):
658 self.testFailingWebsocket(safari=True, cacert=False)
659
660 def enable_faillock(self, count: int):
661 m = self.machine
662 # ensure we have no faillock in our pam config already
663 # arch has faillock enabled by default
664 if m.image != "arch":
665 m.execute("! grep -r faillock /etc/pam.d")
666
667 # add it to the pam config
668 if m.image.startswith('debian-') or m.image.startswith('ubuntu'):
669 # enable pam_faillock. see example in pam_faillock(8)
670 self.sed_file(r"/fallback if no module succeeds/ s/^/"
671 f"auth [default=die] pam_faillock.so authfail deny={count}\\n"
672 f"auth sufficient pam_faillock.so authsucc deny={count}\\n/",
673 "/etc/pam.d/common-auth")
674 elif m.image == "arch":
675 self.sed_file(f"s/# deny = 3/deny = {count}/", "/etc/security/faillock.conf")
676 else:
677 # see https://access.redhat.com/solutions/62949
678 sed = ("/^auth.*pam_unix/ {"
679 "s/sufficient/[success=1 default=ignore]/\n"
680 f"aauth [default=die] pam_faillock.so authfail audit deny={count} unlock_time=600\n"
681 f"aauth sufficient pam_faillock.so authsucc audit deny={count} unlock_time=600\n"
682 "}")
683 self.sed_file(sed, "/etc/pam.d/password-auth")
684 self.sed_file(sed, "/etc/pam.d/system-auth")
685
686 m.execute("grep -r faillock /etc/pam.d")
687
688 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
689 def testFaillock(self):
690 m = self.machine
691 b = self.browser
692
693 module = 'faillock'
694
695 def logfile(user):
696 return '/run/faillock/' + user
697
698 def expect_fail_count(expected, user="admin", must_exist=True):
699 if must_exist:
700 cksum = m.execute(f"cksum {logfile(user)}")
701
702 output = m.execute(f"{module} --user {user}")
703
704 n_lines = len(output.splitlines())
705 if n_lines:
706 n_lines -= 2 # remove the header, if it's there
707
708 self.assertEqual(expected, n_lines)
709
710 # make sure the above command didn't change the file
711 if must_exist:
712 self.assertEqual(cksum, m.execute(f"cksum {logfile(user)}"))
713
714 def expect_failed_login(user, password, n_failed):
715 b.try_login(user, password)
716 b.wait_text_not("#login-error-title", "")
717 # this depends on the use case and OS implementation -- should just be something sensible
718 self.assertIn(b.text("#login-error-title"),
719 ["Permission denied", "Authentication failed", "Wrong user name or password"])
720 expect_fail_count(n_failed, user=user)
721
722 def expect_successful_login(user, password):
723 b.login_and_go('/system', user=user, password=password)
724 expect_fail_count(0, user=user)
725 b.logout()
726
727 self.enable_root_login()
728 self.enable_faillock(4)
729
730 m.start_cockpit()
731
732 # start from a clean slate
733 clean_cmd = f"rm -f {logfile('admin')}"
734 self.addCleanup(m.execute, clean_cmd)
735 m.execute(clean_cmd)
736
737 # make sure we can still login
738 b.login_and_go("/system")
739 b.logout()
740
741 # and it should show zero fails
742 expect_fail_count(0, must_exist=False)
743
744 # try three bogus login attempts
745 for n in [1, 2, 3]:
746 expect_failed_login("admin", "bad", n)
747 expect_fail_count(3)
748
749 # make sure we can still login
750 expect_successful_login("admin", "foobar")
751
752 # after the success, try three more bogus login attempts
753 for n in [1, 2, 3]:
754 expect_failed_login("admin", "bad", n)
755 expect_successful_login("admin", "foobar")
756
757 # now try four, which should lock the account
758 for n in [1, 2, 3, 4]:
759 expect_failed_login("admin", "bad", n)
760
761 # logging in should fail now
762 expect_failed_login("admin", "foobar", n)
763
764 # having given the correct password the last time should not have helped things
765 expect_failed_login("admin", "foobar", n)
766
767 # but we can reset the lockout
768 m.execute(module + " --reset --user admin")
769 expect_fail_count(0)
770
771 # and login again
772 expect_successful_login("admin", "foobar")
773
774 # ws container logs in via sshd, which forbids root logging in with a password
775 if not m.ws_container:
776 # make sure root never gets locked out
777 for n in range(1, 10):
778 expect_failed_login("root", "bad", n)
779 expect_successful_login("root", "foobar")
780
781 self.allow_journal_messages(".*[aA]ccount .*locked due to .* failed logins.*")
782 self.allow_journal_messages(".*minutes left to unlock.*")
783
784 @testlib.skipWsContainer("no local config with cockpit/ws container")
785 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
786 def testAutomaticSudoFaillock(self):
787 m = self.machine
788 b = self.browser
789
790 # only tolerate one failure; unfortunately sending no password (the second time) counts as second failure
791 self.enable_faillock(3)
792 self.addCleanup(m.execute, "faillock --user admin --reset")
793 # configure the account to force a password change
794 m.execute("chage -d 0 admin")
795 m.start_cockpit()
796 b.open("/")
797 b.try_login()
798
799 # set new password
800 new_pass = "fooBetterBar1@#"
801 if m.ws_container:
802 b.wait_in_text("#conversation-prompt", "You are required to change your password")
803 else:
804 b.wait_in_text("#conversation-message", "You are required to change your password")
805 b.set_val('#conversation-input', 'foobar')
806 b.click('#login-button')
807 b.wait_in_text("#conversation-prompt", "New password")
808 b.set_val('#conversation-input', new_pass)
809 b.click('#login-button')
810 b.wait_in_text("#conversation-prompt", "Retype")
811 b.set_val('#conversation-input', new_pass)
812 b.click('#login-button')
813 b.wait_visible('#content')
814 # automatic sudo will still try the old password
815 b.check_superuser_indicator("Limited access")
816 b.logout()
817
818 # can now login with new password and sudo, account isn't locked
819 b.login_and_go(password=new_pass)
820 b.check_superuser_indicator("Administrative access")
821 b.logout()
822
823 @testlib.skipWsContainer("root logins disabled by default with ssh")
824 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
825 def testPamAccess(self):
826 b = self.browser
827 m = self.machine
828
829 m.start_cockpit()
830 b.open("/system")
831
832 # root login is disabled by default via /etc/cockpit/disallowed-users on everything except RHEL 8
833 if not m.image.startswith("rhel-8"):
834 b.try_login("root", "foobar")
835 b.wait_in_text("#login-error-title", "Permission denied")
836 b.wait_not_visible("#login-error-message")
837
838 # disable root login with pam_access
839 self.enable_root_login()
840 self.write_file("/etc/security/access.conf", "- : root : ALL\n", append=True)
841 self.sed_file("1 aaccount required pam_access.so", "/etc/pam.d/cockpit")
842 b.try_login(user="root")
843 b.wait_in_text("#login-error-title", "Permission denied")
844 b.wait_not_visible("#login-error-message")
845
846 self.allow_journal_messages(r"cockpit-session: user account access failed.*root.*")
847
848 @testlib.skipWsContainer("sssd/cockpit-session not available with ws container")
849 def testClientCertAuthentication(self):
850 m = self.machine
851
852 if m.image.startswith("debian") or m.image.startswith("ubuntu") or m.image.startswith("opensuse-tumbleweed"):
853 # on Debian/Ubuntu, an unconfigured sssd fails to start, so only restart it at the end if it was running before
854 # also, sssd is split into several services
855 self.restore_dir("/etc/sssd", post_restore_action="systemctl stop 'sssd*'")
856 else:
857 self.restore_dir("/etc/sssd", restart_unit="sssd")
858
859 m.execute("useradd alice; echo alice:foobar123 | chpasswd")
860 m.upload(["alice.pem", "alice.key", "alice-expired.pem", "bob.pem", "bob.key"], self.vm_tmpdir,
861 relative_dir="src/tls/ca/")
862 alice_cert = self.vm_tmpdir + "/alice.pem"
863 alice_cert_expired = self.vm_tmpdir + "/alice-expired.pem"
864 alice_key = self.vm_tmpdir + "/alice.key"
865 alice_cert_key = ['--cert', alice_cert, '--key', alice_key]
866
867 # set up local (NIS) sssd provider and certificate mapping
868 id_provider = """id_provider = proxy
869 local_auth_policy = only
870 proxy_lib_name = files"""
871
872 self.write_file("/etc/sssd/sssd.conf", f"""
873 [sssd]
874 domains = local
875
876 [domain/local]
877 {id_provider}
878
879 [certmap/local/alice]
880 # Requires sssd >= 2.6.1 and installing sssd_auth_ca_db.pem; with earlier sssd this is completely unsafe
881 matchrule = <SUBJECT>^DC=LAN,DC=COCKPIT,CN=alice$
882 """, perm="0600")
883 m.execute("systemctl restart sssd")
884
885 # ensure sssd certificate lookup without validation works
886 user_obj = m.execute('busctl call org.freedesktop.sssd.infopipe /org/freedesktop/sssd/infopipe/Users '
887 'org.freedesktop.sssd.infopipe.Users FindByCertificate s -- '
888 """"$(cat %s)" | sed 's/^o "//; s/"$//' """ % alice_cert)
889 self.assertEqual(m.execute('busctl get-property org.freedesktop.sssd.infopipe ' + user_obj.strip() +
890 ' org.freedesktop.sssd.infopipe.Users.User name').strip(),
891 's "alice"')
892
893 err = m.execute('! busctl call org.freedesktop.sssd.infopipe /org/freedesktop/sssd/infopipe/Users '
894 'org.freedesktop.sssd.infopipe.Users FindByValidCertificate s -- '
895 """"$(cat %s)" 2>&1""" % alice_cert)
896 self.assertIn("Certificate authority file not found", err)
897
898 # install our CA, so that sssd can validate
899 with open("src/tls/ca/ca.pem") as f:
900 m.write("/etc/sssd/pki/sssd_auth_ca_db.pem", f.read())
901 u = m.execute('busctl call org.freedesktop.sssd.infopipe /org/freedesktop/sssd/infopipe/Users '
902 'org.freedesktop.sssd.infopipe.Users FindByCertificate s -- '
903 """"$(cat %s)" | sed 's/^o "//; s/"$//' """ % alice_cert)
904 self.assertEqual(u, user_obj)
905
906 # These tests have to be run with curl, as chromium-headless does not support selecting/handling client-side
907 # certificates; it just rejects cert requests. For interactive tests, grab src/tls/ca/alice.p12 and import
908 # it into the browser.
909
910 def do_test(authopts, expected, not_expected=None, session_leader=None):
911 # avoid running into start-limit-hit
912 m.execute("systemctl reset-failed")
913 m.start_cockpit(tls=True)
914 output = m.execute(['curl', '-ksS', '-D-', *authopts, 'https://localhost:9090/cockpit/login'])
915 for s in expected:
916 self.assertIn(s, output)
917 for s in (not_expected or []):
918 self.assertNotIn(s, output)
919 # sessions/users often hang around in State=closing for a long time, ignore these
920 if session_leader:
921 m.execute('until [ "$(loginctl show-user --property=State --value alice)" = "active" ]; do sleep 1; done')
922 sessions = m.execute('loginctl show-user --property=Sessions --value alice').strip().split()
923 self.assertGreaterEqual(len(sessions), 1)
924 for session in sessions:
925 out = m.execute('loginctl session-status ' + session)
926 # Skip manager session
927 if "Class: manager" in out:
928 continue
929 if "State: active" in out: # skip closing sessions
930 self.assertIn(session_leader, out)
931 self.assertIn('cockpit-bridge', out)
932 # systemd < 255: "Service: cockpit; type web; class user"
933 # systemd ≥ 255: "Service: cockpit\n Type: web\n Class: user"
934 self.assertRegex(out, r"Service:\s+cockpit")
935 self.assertRegex(out, "[tT]ype.*web")
936 break
937 else:
938 self.fail("no active session for active user")
939
940 # sessions time out after 10s, but let's not wait for that
941 m.execute('loginctl terminate-session ' + sessions[0])
942 # wait until the session is gone
943 m.execute("while loginctl show-user alice | grep -q 'State=active'; do sleep 1; done")
944
945 m.stop_cockpit()
946
947 # from sssd
948 self.allow_journal_messages("alice is not allowed to run sudo.*")
949
950 # cert auth should not be enabled by default
951 do_test(alice_cert_key, ["HTTP/1.1 401 Authentication failed"])
952 # password auth should work
953 do_test(['-u', 'alice:foobar123'],
954 ['HTTP/1.1 200 OK', '"csrf-token"'],
955 session_leader='cockpit-session')
956
957 # enable cert based auth
958 m.write("/etc/cockpit/cockpit.conf", '[WebService]\nClientCertAuthentication = true\n', append=True)
959 # cert auth should work now
960 do_test(alice_cert_key, ['HTTP/1.1 200 OK', '"csrf-token"'])
961 # password auth, too
962 do_test(['-u', 'alice:foobar123'],
963 ['HTTP/1.1 200 OK', '"csrf-token"'],
964 session_leader='cockpit-session')
965
966 # another certificate gets rejected
967 self.allow_journal_messages("cockpit-session: No matching user for certificate")
968 do_test(["--cert", self.vm_tmpdir + "/bob.pem", "--key", self.vm_tmpdir + "/bob.key"],
969 ["HTTP/1.1 401 Authentication failed"],
970 not_expected=["crsf-token"])
971
972 # check expired certificate
973 m.start_cockpit(tls=True)
974 journal_cursor = self.machine.journal_cursor()
975 m.execute(f'! curl -ksS --cert {alice_cert_expired} --key {alice_key} https://localhost:9090/cockpit/login')
976 m.stop_cockpit()
977 testlib.wait(lambda: re.search(r'.*Invalid TLS peer certificate.* expired',
978 m.execute(f"journalctl -ocat --cursor '{journal_cursor}' SYSLOG_IDENTIFIER=cockpit-tls")),
979 tries=10)
980 self.allow_journal_messages('.*Invalid TLS peer certificate.* expired.*')
981 self.allow_journal_messages('.*handshake failed: Error in the certificate verification.*')
982
983 # disallow password auth
984 m.write("/etc/cockpit/cockpit.conf", "[Basic]\naction = none\n", append=True)
985 do_test(alice_cert_key, ['HTTP/1.1 200 OK', '"csrf-token"'])
986 do_test(['-u', 'alice:foobar123'],
987 ['HTTP/1.1 401 Authentication disabled'],
988 not_expected=["crsf-token"])
989
990 # wwithout a CA, alice's cert fails
991 m.execute("rm /etc/sssd/pki/sssd_auth_ca_db.pem")
992 self.allow_journal_messages("cockpit-session: Failed to map .* Invalid certificate provided")
993 self.allow_journal_messages("cockpit-session: Failed to map .* Certificate authority file not found")
994 do_test(alice_cert_key, ['HTTP/1.1 401 Authentication failed'])
995
996 # sssd-dbus not available
997 self.allow_journal_messages("cockpit-session: Failed to map .* Could not activate remote peer.*")
998 self.allow_journal_messages("cockpit-session: Failed to map .* Unit sssd-ifp.service is masked.")
999 m.execute("systemctl mask sssd-ifp; systemctl stop sssd-ifp")
1000 do_test(alice_cert_key, ["HTTP/1.1 401 Authentication failed"],
1001 not_expected=["crsf-token"])
1002 m.execute("systemctl unmask sssd-ifp")
1003
1004 def testServer(self):
1005 m = self.machine
1006 b = self.browser
1007
1008 m.execute("useradd --create-home user")
1009 m.execute("echo user:foobar | chpasswd")
1010 m.start_cockpit()
1011 # the quick succession of login/logout is too much for packagekit's brain
1012 self.disable_preload("packagekit", "playground", "systemd")
1013
1014 def check_server(server, expect_fp_ack):
1015 b.open('/')
1016 b.wait_visible("#login")
1017 # start with no known keys every time
1018 b.eval_js("""window.localStorage.setItem("known_hosts", "{ }")""")
1019 b.set_val('#login-user-input', "user")
1020 b.set_val('#login-password-input', "foobar")
1021 b.click("#show-other-login-options")
1022 b.set_val("#server-field", server)
1023 b.click("#login-button")
1024
1025 if expect_fp_ack:
1026 b.wait_in_text("#hostkey-title", "New host")
1027 b.wait_in_text("#hostkey-message-1", "for the first time")
1028 b.click("#login-button")
1029
1030 b.wait_visible('#content')
1031 b.enter_page('/system')
1032 b.wait_visible('.system-information')
1033 b.logout()
1034
1035 # by name
1036 check_server("localhost", expect_fp_ack=True)
1037 # by name and port
1038 check_server("localhost:22", expect_fp_ack=True)
1039 # by IPv4 address; 127.0.0.1 is treated specially as ignore_hostkey fallback, and does not require FP
1040 check_server("127.0.0.1", expect_fp_ack=False)
1041 # by IPv4 address and port
1042 check_server("127.0.0.1:22", expect_fp_ack=False)
1043 # by IPv6 address
1044 check_server("::1", expect_fp_ack=True)
1045 # by IPv6 address and port
1046 check_server("[::1]:22", expect_fp_ack=True)
1047
1048 # enable this once our cockpit/ws container can beiboot
1049 @testlib.skipWsContainer("client setup does not work with ws container")
1050 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
1051 def testSSH(self):
1052 m = self.machine
1053 b = self.browser
1054
1055 # this matches our bots test VMs
1056 my_ip = "172.27.0.15"
1057
1058 m.start_cockpit()
1059
1060 def try_login(user, password, server=None, expect_hostkey=False):
1061 b.open("/")
1062 b.set_val('#login-user-input', user)
1063 b.set_val('#login-password-input', password)
1064 b.click("#show-other-login-options")
1065 b.set_val("#server-field", server or my_ip)
1066 b.click("#login-button")
1067 if expect_hostkey:
1068 b.wait_in_text("#hostkey-message-1", server or my_ip)
1069 b.wait_in_text("#hostkey-fingerprint", "SHA256:")
1070 b.click("#login-button")
1071
1072 def check_no_processes():
1073 m.execute(f"while pgrep -af '[s]sh .* {my_ip}' >&2; do sleep 1; done")
1074 m.execute("while pgrep -af '[c]ockpit.beiboot' >&2; do sleep 1; done")
1075
1076 def check_session(server=None):
1077 b.wait_visible('#content')
1078 b.enter_page('/system')
1079 b.wait_visible('.system-information')
1080 m.execute(f"pgrep -af '[s]sh .* -l admin .*{server or my_ip}'")
1081 m.execute(f"pgrep -af '[c]ockpit.beiboot.*{server or my_ip}'")
1082 b.logout()
1083 check_no_processes()
1084
1085 def check_store_hostkey(expected: str) -> None:
1086 db_hostkey = b.eval_js(f'JSON.parse(window.localStorage.getItem("known_hosts"))["{my_ip}"]')
1087 if m.image.startswith('debian') or m.image.startswith('ubuntu'):
1088 # these OSes encrypt host keys, so don't compare them
1089 db_hostkey = ' '.join(db_hostkey.split()[1:])
1090 expected = ' '.join(expected.split()[1:])
1091 self.assertEqual(db_hostkey, expected)
1092
1093 # successful login through SSH
1094 try_login("admin", "foobar", expect_hostkey=True)
1095 check_session()
1096 # wrote full host key into session storage
1097 # some OpenSSH versions add a comment here, filter that out
1098 real_hostkey = m.execute(f"ssh-keyscan -t ssh-ed25519 {my_ip} | grep -v ^#")
1099 check_store_hostkey(real_hostkey)
1100
1101 # host key is now known, but wrong password
1102 try_login("admin", "wrong")
1103 b.wait_text("#login-error-title", "Authentication failed")
1104 b.wait_text("#login-error-message", "Wrong user name or password")
1105 check_no_processes()
1106 # goes back to normal login form
1107 b.wait_visible('#login-user-input')
1108
1109 # colliding usernames; user names in "Connect to:" are *not* supported,
1110 # but pin down the behaviour
1111 try_login("admin", "foobar", server=f"other@{my_ip}")
1112 check_session()
1113
1114 # IPv6
1115 try_login("admin", "foobar", server="::1", expect_hostkey=True)
1116 check_session(server="::1")
1117 try_login("admin", "foobar", server="[::1]:22")
1118 check_session(server="::1")
1119
1120 # empty password
1121 self.write_file("/etc/ssh/sshd_config.d/01-empty-password.conf", "PermitEmptyPasswords yes",
1122 post_restore_action=self.restart_sshd)
1123 m.execute(self.restart_sshd)
1124 m.execute("passwd -d admin")
1125 try_login("admin", "")
1126 check_session()
1127 m.execute("echo 'admin:foobar' | chpasswd")
1128 if m.image == 'arch':
1129 # HACK: PermitEmptyPasswords somehow breaks regular password auth
1130 m.execute("rm /etc/ssh/sshd_config.d/01-empty-password.conf")
1131 m.execute(self.restart_sshd)
1132
1133 # non-matching host key
1134 bad_key = "172.27.0.15 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINKEIUL5s7ebg5Y6JdYNq4+mAaaaaaP1VRBDUiVdHT3R"
1135 b.eval_js(f"""window.localStorage.setItem('known_hosts', '{{"{my_ip}": "{bad_key}"}}')""")
1136
1137 # first try with wrong credentials
1138 try_login("admin", "wrong")
1139 b.wait_text("#hostkey-title", f"{my_ip} key changed")
1140 b.wait_in_text("#hostkey-fingerprint", "SHA256:")
1141 b.click("#login-button.pf-m-danger")
1142 b.wait_text("#login-error-title", "Authentication failed")
1143 # no details, it's a PAM conversation
1144 b.wait_not_visible("#login-error-message")
1145 check_no_processes()
1146 # new host key is accepted and updated in db
1147 # confirmation replaces (not amends) known key
1148 check_store_hostkey(real_hostkey)
1149
1150 # now with correct credentials, does not ask for host key any more
1151 try_login("admin", "foobar")
1152 check_session()
1153 check_store_hostkey(real_hostkey)
1154
1155 # good credentials with bad key
1156 b.eval_js(f"""window.localStorage.setItem('known_hosts', '{{"{my_ip}": "{bad_key}"}}')""")
1157 try_login("admin", "foobar")
1158 b.wait_text("#hostkey-title", f"{my_ip} key changed")
1159 b.wait_in_text("#hostkey-fingerprint", "SHA256:")
1160 b.click("#login-button.pf-m-danger")
1161 check_session()
1162 check_store_hostkey(real_hostkey)
1163
1164 @testlib.skipOstree("No NFS server")
1165 def testNFSHomeDir(self):
1166 m = self.machine
1167
1168 # set up admin's home dir on NFS
1169 self.restore_dir("/srv")
1170 m.execute("mkdir -p /srv/nfshome/admin; chown admin:admin /srv/nfshome/admin")
1171 self.write_file("/etc/exports", "/srv/nfshome 127.0.0.0/24(rw)\n",
1172 post_restore_action="systemctl restart nfs-server")
1173 m.execute("systemctl restart nfs-server")
1174 m.execute("mount 127.0.0.1:/srv/nfshome/admin /home/admin")
1175 self.addCleanup(m.execute, "until umount /home/admin; do sleep 1; done")
1176
1177 self.login_and_go()
1178
1179 self.assertIn("admin", m.execute("loginctl --no-legend list-sessions"))
1180 self.browser.logout()
1181
1182 # cleans up session
1183 m.execute("while loginctl --no-legend list-sessions | grep admin; do sleep 1; done")
1184
1185
1186 @testlib.skipOstree("/etc customization issues?")
1187 @testlib.nondestructive
1188 class TestCustomLogin(testlib.MachineCase):
1189 def testBasic(self) -> None:
1190 m = self.machine
1191 b = self.browser
1192
1193 # Custom login page
1194 static_dir = f"{self.vm_tmpdir}/static"
1195 m.execute(f"printf '[WebService]\nCustomLoginPage = {static_dir}\n' > /etc/cockpit/cockpit.conf")
1196 m.execute(f"mkdir -p {static_dir}")
1197
1198 m.write(f"{static_dir}/login.html", """
1199 <!DOCTYPE html>
1200 <html>
1201
1202 <head>
1203 <title>Custom login page</title>
1204 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1205 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
1206 <meta name="robots" content="noindex" />
1207 <link href="cockpit/static/login.css" type="text/css" rel="stylesheet" />
1208 <script type="text/javascript" src="cockpit/static/login.js" defer></script>
1209 </head>
1210 <body class="login">
1211 <button type="button" id="login">Login</button>
1212 </body>
1213 </html>
1214 """)
1215
1216 m.write(f"{static_dir}/login.js", """
1217 console.log('login page loaded');
1218 const button = document.getElementById('login');
1219 button.addEventListener("click", async function() {
1220 const headers = {
1221 Authorization: "Basic " + window.btoa(window.unescape(encodeURIComponent(("admin:foobar")))),
1222 };
1223
1224 try {
1225 const response = await fetch('/cockpit/login', { method: "GET", headers });
1226 if (!response.ok)
1227 throw new Error(`Response status: ${response.status}`);
1228
1229 const result = await response.json();
1230 window.location.reload(true);
1231 } catch(err) {
1232 console.warn(err);
1233 }
1234 });
1235 """)
1236
1237 m.write(f"{static_dir}/login.css", """
1238 /* canary to test if css loaded */
1239 :root {
1240 --css-loaded: true;
1241 }
1242 """)
1243
1244 # allow cockpit-ws to read static_dir
1245 m.execute(f"if selinuxenabled 2>&1; then chcon -R -t usr_t {static_dir}; fi")
1246
1247 m.start_cockpit()
1248 b.open("/")
1249
1250 b.wait_visible("#login")
1251 self.assertEqual(b.eval_js("getComputedStyle(document.documentElement).getPropertyValue('--css-loaded').trim()"),
1252 "true")
1253 b.wait_js_cond('document.title === "Custom login page"')
1254
1255 b.click("#login")
1256 b.wait_visible('#content')
1257 b.enter_page('/system')
1258 b.wait_visible('.system-information')
1259
1260
1261 if __name__ == '__main__':
1262 testlib.test_main()