Debian Codegraph @

test/verify/check-shell-keys

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) 2015 Red Hat, Inc.
5 # SPDX-License-Identifier: LGPL-2.1-or-later
6
7
8 import dialoglib
9 import testlib
10
11 FP_SHA256 = "SHA256:iyVAl4Z8riL9Jg4fV9Wv/6cbqebdDtsBEMkojNLLYX8"
12 KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEAkRTvQCSEZNPXpA5bP82ilQn3TMeQ6z2NO3O0UwY9z test-name"
13
14
15 @testlib.nondestructive
16 class TestKeys(testlib.MachineCase):
17 def testAuthorizedKeys(self):
18 m = self.machine
19 b = self.browser
20
21 # Create a user without any role
22 m.execute("useradd user -s /bin/bash -m -c User")
23 m.execute("echo user:foobar | chpasswd")
24
25 def login(user):
26 self.login_and_go("/users#/" + user, user=user, superuser=False)
27 b.wait_text("#account-user-name", user)
28
29 def add_key(key, fp_sh256, comment):
30 b.click('#authorized-key-add')
31 b.wait_visible("#add-authorized-key-dialog")
32 b.wait_val("#authorized-keys-text", "")
33 b.set_input_text("#authorized-keys-text", key)
34 b.click("#add-authorized-key-dialog button.apply")
35 b.wait_not_present("#add-authorized-key-dialog")
36
37 b.wait_in_text("#account-authorized-keys-list", comment)
38
39 b.wait_not_in_text("#account-authorized-keys-list", "no authorized public keys")
40 text = b.text("#account-authorized-keys-list")
41 self.assertIn(fp_sh256, text)
42
43 # no keys
44 login("user")
45 b.wait_in_text("#account-authorized-keys", "no authorized public keys")
46
47 # add bad
48 b.click('#authorized-key-add')
49 b.wait_visible("#add-authorized-key-dialog")
50 b.wait_val("#authorized-keys-text", "")
51 b.set_input_text("#authorized-keys-text", "bad")
52 b.click("#add-authorized-key-dialog button.apply")
53 b.wait_in_text("#add-authorized-key-dialog", "The key you provided was not valid")
54 b.click("#add-authorized-key-dialog button.cancel")
55
56 # add good
57 add_key(KEY, FP_SHA256, "test-name")
58 b.wait_count("#account-authorized-keys-list tr", 1)
59
60 # remove key on mobile, on mobile we show a kebab menu
61 b.set_layout("mobile")
62 b.click("#account-authorized-keys button.pf-v6-c-menu-toggle")
63 b.click("button.pf-v6-c-menu__item")
64 b.wait_count("#account-authorized-keys-list tr", 0)
65 b.set_layout("desktop")
66
67 # add good
68 add_key(KEY, FP_SHA256, "test-name")
69
70 # Try see admin
71 b.go("#/admin")
72 b.wait_text("#account-user-name", "admin")
73
74 # Not allowed, except on Ubuntu, where we can find out that ~/.ssh doesn't exist, which is shown as "no keys".
75 if "ubuntu" not in m.image and "debian" not in m.image:
76 b.wait_in_text("#account-authorized-keys", "You do not have permission")
77
78 b.logout()
79
80 # delete whole ssh to start fresh
81 m.execute("rm -rf /home/user/.ssh")
82 self.assertNotIn(".ssh", m.execute("ls /home/user"))
83
84 # Log in as admin
85 login("admin")
86 b.go("#/user")
87
88 if "ubuntu" not in m.image and "debian" not in m.image:
89 b.wait_in_text("#account-authorized-keys",
90 "You do not have permission to view the authorized public keys for this account.")
91
92 b.become_superuser()
93
94 b.wait_in_text("#account-authorized-keys", "no authorized public keys")
95
96 def check_perms():
97 perms = m.execute("getfacl -a /home/user/.ssh")
98 self.assertIn("owner: user", perms)
99
100 perms = m.execute("getfacl -a /home/user/.ssh/authorized_keys")
101 self.assertIn("owner: user", perms)
102 self.assertIn("user::rw-", perms)
103 self.assertIn("group::---", perms)
104 self.assertIn("other::---", perms)
105
106 # Adding keys sets permissions properly
107 b.wait_text("#account-user-name", "user")
108 add_key(KEY, FP_SHA256, "test-name")
109 check_perms()
110
111 b.wait_count("#account-authorized-keys-list tr", 1)
112
113 # Add invalid key directly
114 m.write("/home/user/.ssh/authorized_keys", "\nbad\n", append=True)
115 b.wait_in_text("#account-authorized-keys-list tbody:last-child", "Invalid key")
116 b.wait_count("#account-authorized-keys-list tr", 2)
117
118 # Removing the key
119 b.click("#account-authorized-keys-list tbody:last-child button")
120 b.wait_not_in_text("#account-authorized-keys", "Invalid key")
121 b.wait_count("#account-authorized-keys-list tr", 1)
122 data = m.execute("cat /home/user/.ssh/authorized_keys")
123 self.assertEqual(data, KEY + "\n")
124 # Permissions are still ok
125 check_perms()
126 b.logout()
127
128 # User can still see their keys
129 login("user")
130 b.wait_in_text("#account-authorized-keys-list tbody:first-child", "test-name")
131
132 b.click("#account-authorized-keys-list tbody:first-child button")
133 b.wait_in_text("#account-authorized-keys", "no authorized public keys")
134
135 self.allow_journal_messages('authorized_keys is not a public key file.')
136 self.allow_journal_messages('Missing callback called fullpath = /home/user/.ssh/authorized_keys')
137 self.allow_journal_messages('')
138
139 # Possible workaround - ssh as `admin` and just do `m.execute()`
140 @testlib.skipBrowser("Firefox cannot do `cockpit.spawn`", "firefox")
141 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
142 def testPrivateKeys(self):
143 b = self.browser
144 m = self.machine
145
146 def list_keys():
147 return b.eval_js("cockpit.spawn([ '/bin/sh', '-c', 'ssh-add -l || true' ])")
148
149 def toggleExpandedStateKey(identifier):
150 b.click(f"tr[data-name='{identifier}'] .pf-v6-c-table__toggle > button")
151
152 def waitKeyPresent(identifier, present):
153 if present:
154 b.wait_visible(f"tr[data-name='{identifier}']")
155 else:
156 b.wait_not_present(f"tr[data-name='{identifier}']")
157
158 def waitKeyLoaded(identifier, enabled):
159 b.wait_visible(f"tr[data-name='{identifier}'] input[type=checkbox]" + (":checked" if enabled else ":not(checked)"))
160 b.wait_visible(f"tr[data-name='{identifier}'][data-loaded={'true' if enabled else 'false'}]")
161
162 def toggleKeyState(identifier):
163 b.click(f"tr[data-name='{identifier}'] .pf-v6-c-switch__input")
164
165 def selectTab(identifier, title):
166 b.click(f"tr[data-name='{identifier}'] + tr li > button:contains('{title}')")
167
168 def waitTabActive(identifier, title):
169 b.wait_visible(f"tr[data-name='{identifier}'] + tr li.pf-m-current > button:contains('{title}')")
170
171 def waitKeyRowExpanded(identifier, expanded):
172 if expanded:
173 b.wait_visible(f"tr[data-name='{identifier}'] + tr .ct-listing-panel-body:not([hidden])")
174 else:
175 b.wait_not_visible(f"tr[data-name='{identifier}'] + tr")
176
177 def waitKeyDetail(identifier: str, field: str, value: str) -> None:
178 b.wait_in_text(f"tr[data-name='{identifier}'] + tr .ct-listing-panel-body [data-name='{field}']", value)
179
180 def getKeyDetail(identifier: str, field: str) -> str:
181 return b.text(f"tr[data-name='{identifier}'] + tr .ct-listing-panel-body [data-name='{field}']")
182
183 # Operating systems where auto loading doesn't work
184 auto_load = not m.ws_container
185
186 if m.image == "arch":
187 self.write_file("/etc/pam.d/cockpit", """
188 auth optional pam_ssh_add.so
189 session optional pam_ssh_add.so
190 """, append=True)
191
192 self.restore_dir("/home/admin")
193
194 # Put all the keys in place
195 m.execute("mkdir -p /home/admin/.ssh")
196 m.upload([
197 "verify/files/ssh/id_rsa",
198 "verify/files/ssh/id_rsa.pub",
199 "verify/files/ssh/id_ed25519",
200 "verify/files/ssh/id_ed25519.pub"
201 ], "/home/admin/.ssh/")
202 m.execute("chmod 600 /home/admin/.ssh/id_*")
203 m.execute("chown -R admin:admin /home/admin/.ssh")
204
205 self.login_and_go()
206
207 id_rsa = "2048 SHA256:SRvBhCmkCEVnJ6ascVH0AoVEbS3nPbowZkNevJnXtgw"
208 id_ed25519 = "256 SHA256:Wd028KYmG3OVLp7dBmdx0gMR7VcarJVIfaTtKqYCmak"
209
210 keys = list_keys()
211 if auto_load:
212 self.assertIn(id_rsa, keys)
213 self.assertNotIn(id_ed25519, keys)
214
215 b.open_session_menu()
216 b.click("#sshkeys")
217
218 # Automatically loaded
219 waitKeyLoaded('id_rsa', enabled=auto_load)
220 toggleExpandedStateKey('id_rsa')
221 waitKeyRowExpanded('id_rsa', expanded=True)
222 waitTabActive('id_rsa', 'Details')
223 waitKeyDetail('id_rsa', 'comment', "test@test")
224 waitKeyDetail('id_rsa', 'type', "RSA")
225 self.assertEqual(getKeyDetail('id_rsa', 'fingerprint'), id_rsa[5:])
226
227 selectTab('id_rsa', 'Public key')
228 b.wait_val("tr[data-name=id_rsa] + tr .pf-v6-c-clipboard-copy input",
229 "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDG4iipTovcMg0xn+089QLNKVGpP"
230 "2Pgq2duxHgAXre2XgA3dZL+kooioGFwBQSEjbWssKy82hKIN/W82/lQtL6krf7JQW"
231 "nT3LZwD5DPsvHFKhOLghbiFzSI0uEL4NFFcZOMo5tGLrM5LsZsaIkkv5QkAE0tHIy"
232 "eYinK6dQ2d8ZsfmgqxHDUQUWnz1T75X9fWQsUugSWI+8xAe0cfa4qZRz/IC+K7DEB"
233 "3x4Ot5pl8FBuydJj/gb+Lwo2Vs27/d87W/0KHCqOHNwaVC8RBb1WcmXRDDetLGH1A"
234 "9m5x7Ip/KU/cyvWWxw8S4VKZkTIcrGUhFYJDnjtE3Axz+D7agtps41t test@test")
235 toggleExpandedStateKey('id_rsa')
236 waitKeyRowExpanded('id_rsa', expanded=False)
237
238 # Load the id_ed25519 key
239 waitKeyLoaded('id_ed25519', enabled=False)
240 toggleKeyState('id_ed25519')
241 b.set_input_text("#id_ed25519-password", "locked")
242 b.click("#id_ed25519-unlock")
243 waitKeyLoaded('id_ed25519', enabled=True)
244
245 # Both keys are now loaded
246 keys = list_keys()
247 if auto_load:
248 self.assertIn(id_rsa, keys)
249 self.assertIn(id_ed25519, keys)
250
251 # Unload the RSA key
252 if auto_load:
253 toggleKeyState('id_rsa')
254 waitKeyLoaded('id_rsa', enabled=False)
255
256 # Only DSA keys now loaded
257 keys = list_keys()
258 self.assertIn(id_ed25519, keys)
259 self.assertNotIn(id_rsa, keys)
260
261 # Change password of DSA key
262 toggleExpandedStateKey('id_ed25519')
263 selectTab('id_ed25519', 'Password')
264 b.set_input_text("#id_ed25519-old-password", "locked")
265 b.set_input_text("#id_ed25519-new-password", "foobar")
266 b.set_input_text("#id_ed25519-confirm-password", "foobar")
267 b.assert_pixels("#credentials-modal", "ssh-keys-dialog", chrome_hack_double_shots=True)
268
269 b.click("#id_ed25519-change-password")
270 b.wait_visible('#credentials-modal .pf-v6-c-helper-text__item.pf-m-success')
271
272 # Log off and log back in, and we should have both loaded automatically
273 if auto_load:
274 b.click("#credentials-modal button[aria-label=Close]")
275 b.wait_not_present("#credentials-modal")
276 b.logout()
277 b.login_and_go()
278 keys = list_keys()
279 self.assertIn(id_rsa, keys)
280 self.assertIn(id_ed25519, keys)
281
282 b.open_session_menu()
283 b.click("#sshkeys")
284 b.wait_visible("#credentials-modal")
285
286 # Add bad keys
287 # generate a new key
288 m.execute("ssh-keygen -t rsa -N '' -f /tmp/new.rsa")
289 self.addCleanup(m.execute, "rm -f /tmp/new.rsa*")
290 m.execute("chown admin:admin /tmp/new.rsa")
291 new_pk = m.execute("cat /tmp/new.rsa.pub").strip().split()[0]
292 m.execute("rm /tmp/new.rsa.pub")
293
294 waitKeyPresent('id_rsa', present=True)
295
296 b.wait_visible("#credential-keys")
297 b.wait_not_present("#ssh-file-add")
298 b.click("#ssh-file-add-custom")
299
300 fc = dialoglib.FileChooserHelpers(b, ".file-chooser")
301
302 # Should open in ~admin/.ssh
303 ssh_dir = m.execute("echo -n ~admin/.ssh")
304 fc.wait_path(ssh_dir)
305
306 # Select something that is not a private key
307 fc.set_path("id_rsa.pub")
308 b.click(fc.apply_button())
309 b.wait_in_text(fc.error(), "Not a valid private key")
310
311 # Select /tmp/new.rsa
312 fc.set_path("/tmp/new.rsa")
313 b.click(fc.apply_button())
314
315 # OpenSSH 7.8 and up has a new default key format where
316 # keys are marked as "agent_only", thereby limiting functionality
317 keys = list_keys()
318 keys_length = 3 if auto_load else 2
319 # Keys are like: 256 SHA256:x6S6fxMuEyqhpwNRAIK7ms6bZDY6xK9wzdDr2kCaWVY id_ed25519 (ED25519)
320 # We need the id_ed25519 part, (name or comment)
321 new_key = keys.splitlines()[keys_length - 1].split(' ')[2]
322 toggleKeyState(new_key)
323
324 toggleExpandedStateKey(new_key)
325 waitKeyRowExpanded(new_key, expanded=True)
326 waitTabActive(new_key, 'Details')
327 waitKeyDetail(new_key, 'type', 'RSA')
328 self.assertNotEqual(getKeyDetail(new_key, "fingerprint"), "")
329 selectTab(new_key, 'Public key')
330 self.assertTrue(b.val(f"tr[data-name='{new_key}'] + tr .pf-v6-c-clipboard-copy input").startswith(new_pk))
331
332 # OpenSSH 7.8 and up has a new default key format where
333 # keys are marked as "agent_only", thereby limiting functionality
334 # "agent_only" keys cannot be turned off, or have their passwords changed
335 waitKeyLoaded(new_key, enabled=True)
336
337 # Test adding key with passphrase
338 m.execute("ssh-keygen -t rsa -N 'foobar' -f /tmp/new_with_passphrase.rsa")
339 self.addCleanup(m.execute, "rm -f /tmp/new_with_passphrase.rsa*")
340 m.execute("chown admin:admin /tmp/new_with_passphrase.rsa")
341 m.execute("rm /tmp/new_with_passphrase.rsa.pub")
342
343 b.click("#ssh-file-add-custom")
344 fc.set_path("/tmp/new_with_passphrase.rsa")
345 b.click(fc.apply_button())
346
347 b.wait_visible("h1:contains('Unlock key /tmp/new_with_passphrase.rsa')")
348 b.set_input_text("#\\/tmp\\/new_with_passphrase\\.rsa-password", "foobar")
349 b.click("button:contains('Unlock')")
350 b.wait_not_present("h1:contains('Unlock key /tmp/new_with_passphrase.rsa')")
351 b.wait_count("#credential-keys tbody", 4)
352
353 b.click("#credentials-modal button[aria-label=Close]")
354 b.wait_not_present("#credentials-modal")
355
356
357 if __name__ == '__main__':
358 testlib.test_main()