File: check-shell-keys

package info (click to toggle)
cockpit 355-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 311,568 kB
  • sloc: javascript: 774,787; python: 40,655; ansic: 35,157; cpp: 11,141; sh: 3,512; makefile: 580; xml: 261
file content (368 lines) | stat: -rwxr-xr-x 15,613 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
#!/usr/bin/python3 -cimport os, sys; os.execv(os.path.dirname(sys.argv[1]) + "/../common/pywrap", sys.argv)

# This file is part of Cockpit.
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Cockpit is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Cockpit is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Cockpit; If not, see <https://www.gnu.org/licenses/>.

import testlib

FP_SHA256 = "SHA256:iyVAl4Z8riL9Jg4fV9Wv/6cbqebdDtsBEMkojNLLYX8"
KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEAkRTvQCSEZNPXpA5bP82ilQn3TMeQ6z2NO3O0UwY9z test-name"


@testlib.nondestructive
class TestKeys(testlib.MachineCase):
    def testAuthorizedKeys(self):
        m = self.machine
        b = self.browser

        # Create a user without any role
        m.execute("useradd user -s /bin/bash -m -c User")
        m.execute("echo user:foobar | chpasswd")

        def login(user):
            self.login_and_go("/users#/" + user, user=user, superuser=False)
            b.wait_text("#account-user-name", user)

        def add_key(key, fp_sh256, comment):
            b.click('#authorized-key-add')
            b.wait_visible("#add-authorized-key-dialog")
            b.wait_val("#authorized-keys-text", "")
            b.set_input_text("#authorized-keys-text", key)
            b.click("#add-authorized-key-dialog button.apply")
            b.wait_not_present("#add-authorized-key-dialog")

            b.wait_in_text("#account-authorized-keys-list", comment)

            b.wait_not_in_text("#account-authorized-keys-list", "no authorized public keys")
            text = b.text("#account-authorized-keys-list")
            self.assertIn(fp_sh256, text)

        # no keys
        login("user")
        b.wait_in_text("#account-authorized-keys", "no authorized public keys")

        # add bad
        b.click('#authorized-key-add')
        b.wait_visible("#add-authorized-key-dialog")
        b.wait_val("#authorized-keys-text", "")
        b.set_input_text("#authorized-keys-text", "bad")
        b.click("#add-authorized-key-dialog button.apply")
        b.wait_in_text("#add-authorized-key-dialog", "The key you provided was not valid")
        b.click("#add-authorized-key-dialog button.cancel")

        # add good
        add_key(KEY, FP_SHA256, "test-name")
        b.wait_count("#account-authorized-keys-list tr", 1)

        # remove key on mobile, on mobile we show a kebab menu
        b.set_layout("mobile")
        b.click("#account-authorized-keys button.pf-v6-c-menu-toggle")
        b.click("button.pf-v6-c-menu__item")
        b.wait_count("#account-authorized-keys-list tr", 0)
        b.set_layout("desktop")

        # add good
        add_key(KEY, FP_SHA256, "test-name")

        # Try see admin
        b.go("#/admin")
        b.wait_text("#account-user-name", "admin")

        # Not allowed, except on Ubuntu, where we can find out that ~/.ssh doesn't exist, which is shown as "no keys".
        if "ubuntu" not in m.image and "debian" not in m.image:
            b.wait_in_text("#account-authorized-keys", "You do not have permission")

        b.logout()

        # delete whole ssh to start fresh
        m.execute("rm -rf /home/user/.ssh")
        self.assertNotIn(".ssh", m.execute("ls /home/user"))

        # Log in as admin
        login("admin")
        b.go("#/user")

        if "ubuntu" not in m.image and "debian" not in m.image:
            b.wait_in_text("#account-authorized-keys",
                           "You do not have permission to view the authorized public keys for this account.")

        b.become_superuser()

        b.wait_in_text("#account-authorized-keys", "no authorized public keys")

        def check_perms():
            perms = m.execute("getfacl -a /home/user/.ssh")
            self.assertIn("owner: user", perms)

            perms = m.execute("getfacl -a /home/user/.ssh/authorized_keys")
            self.assertIn("owner: user", perms)
            self.assertIn("user::rw-", perms)
            self.assertIn("group::---", perms)
            self.assertIn("other::---", perms)

        # Adding keys sets permissions properly
        b.wait_text("#account-user-name", "user")
        add_key(KEY, FP_SHA256, "test-name")
        check_perms()

        b.wait_count("#account-authorized-keys-list tr", 1)

        # Add invalid key directly
        m.write("/home/user/.ssh/authorized_keys", "\nbad\n", append=True)
        b.wait_in_text("#account-authorized-keys-list tbody:last-child", "Invalid key")
        b.wait_count("#account-authorized-keys-list tr", 2)

        # Removing the key
        b.click("#account-authorized-keys-list tbody:last-child button")
        b.wait_not_in_text("#account-authorized-keys", "Invalid key")
        b.wait_count("#account-authorized-keys-list tr", 1)
        data = m.execute("cat /home/user/.ssh/authorized_keys")
        self.assertEqual(data, KEY + "\n")
        # Permissions are still ok
        check_perms()
        b.logout()

        # User can still see their keys
        login("user")
        b.wait_in_text("#account-authorized-keys-list tbody:first-child", "test-name")

        b.click("#account-authorized-keys-list tbody:first-child button")
        b.wait_in_text("#account-authorized-keys", "no authorized public keys")

        self.allow_journal_messages('authorized_keys is not a public key file.')
        self.allow_journal_messages('Missing callback called fullpath = /home/user/.ssh/authorized_keys')
        self.allow_journal_messages('')

    # Possible workaround - ssh as `admin` and just do `m.execute()`
    @testlib.skipBrowser("Firefox cannot do `cockpit.spawn`", "firefox")
    def testPrivateKeys(self):
        b = self.browser
        m = self.machine

        def list_keys():
            return b.eval_js("cockpit.spawn([ '/bin/sh', '-c', 'ssh-add -l || true' ])")

        def toggleExpandedStateKey(identifier):
            b.click(f"tr[data-name='{identifier}'] .pf-v6-c-table__toggle > button")

        def waitKeyPresent(identifier, present):
            if present:
                b.wait_visible(f"tr[data-name='{identifier}']")
            else:
                b.wait_not_present(f"tr[data-name='{identifier}']")

        def waitKeyLoaded(identifier, enabled):
            b.wait_visible(f"tr[data-name='{identifier}'] input[type=checkbox]" + (":checked" if enabled else ":not(checked)"))
            b.wait_visible(f"tr[data-name='{identifier}'][data-loaded={'true' if enabled else 'false'}]")

        def toggleKeyState(identifier):
            b.click(f"tr[data-name='{identifier}'] .pf-v6-c-switch__input")

        def selectTab(identifier, title):
            b.click(f"tr[data-name='{identifier}'] + tr li > button:contains('{title}')")

        def waitTabActive(identifier, title):
            b.wait_visible(f"tr[data-name='{identifier}'] + tr li.pf-m-current > button:contains('{title}')")

        def waitKeyRowExpanded(identifier, expanded):
            if expanded:
                b.wait_visible(f"tr[data-name='{identifier}'] + tr .ct-listing-panel-body:not([hidden])")
            else:
                b.wait_not_visible(f"tr[data-name='{identifier}'] + tr")

        def waitKeyDetail(identifier: str, field: str, value: str) -> None:
            b.wait_in_text(f"tr[data-name='{identifier}'] + tr .ct-listing-panel-body [data-name='{field}']", value)

        def getKeyDetail(identifier: str, field: str) -> str:
            return b.text(f"tr[data-name='{identifier}'] + tr .ct-listing-panel-body [data-name='{field}']")

        # Operating systems where auto loading doesn't work
        auto_load = not m.ws_container

        if m.image == "arch":
            self.write_file("/etc/pam.d/cockpit", """
auth       optional     pam_ssh_add.so
session    optional     pam_ssh_add.so
""", append=True)

        self.restore_dir("/home/admin")

        # Put all the keys in place
        m.execute("mkdir -p /home/admin/.ssh")
        m.upload([
            "verify/files/ssh/id_rsa",
            "verify/files/ssh/id_rsa.pub",
            "verify/files/ssh/id_ed25519",
            "verify/files/ssh/id_ed25519.pub"
        ], "/home/admin/.ssh/")
        m.execute("chmod 600 /home/admin/.ssh/id_*")
        m.execute("chown -R admin:admin /home/admin/.ssh")

        self.login_and_go()

        id_rsa = "2048 SHA256:SRvBhCmkCEVnJ6ascVH0AoVEbS3nPbowZkNevJnXtgw"
        id_ed25519 = "256 SHA256:Wd028KYmG3OVLp7dBmdx0gMR7VcarJVIfaTtKqYCmak"

        keys = list_keys()
        if auto_load:
            self.assertIn(id_rsa, keys)
        self.assertNotIn(id_ed25519, keys)

        b.open_session_menu()
        b.click("#sshkeys")

        # Automatically loaded
        waitKeyLoaded('id_rsa', enabled=auto_load)
        toggleExpandedStateKey('id_rsa')
        waitKeyRowExpanded('id_rsa', expanded=True)
        waitTabActive('id_rsa', 'Details')
        waitKeyDetail('id_rsa', 'comment', "test@test")
        waitKeyDetail('id_rsa', 'type', "RSA")
        self.assertEqual(getKeyDetail('id_rsa', 'fingerprint'), id_rsa[5:])

        selectTab('id_rsa', 'Public key')
        b.wait_val("tr[data-name=id_rsa] + tr .pf-v6-c-clipboard-copy input",
                   "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDG4iipTovcMg0xn+089QLNKVGpP"
                   "2Pgq2duxHgAXre2XgA3dZL+kooioGFwBQSEjbWssKy82hKIN/W82/lQtL6krf7JQW"
                   "nT3LZwD5DPsvHFKhOLghbiFzSI0uEL4NFFcZOMo5tGLrM5LsZsaIkkv5QkAE0tHIy"
                   "eYinK6dQ2d8ZsfmgqxHDUQUWnz1T75X9fWQsUugSWI+8xAe0cfa4qZRz/IC+K7DEB"
                   "3x4Ot5pl8FBuydJj/gb+Lwo2Vs27/d87W/0KHCqOHNwaVC8RBb1WcmXRDDetLGH1A"
                   "9m5x7Ip/KU/cyvWWxw8S4VKZkTIcrGUhFYJDnjtE3Axz+D7agtps41t test@test")
        toggleExpandedStateKey('id_rsa')
        waitKeyRowExpanded('id_rsa', expanded=False)

        # Load the id_ed25519 key
        waitKeyLoaded('id_ed25519', enabled=False)
        toggleKeyState('id_ed25519')
        b.set_input_text("#id_ed25519-password", "locked")
        b.click("#id_ed25519-unlock")
        waitKeyLoaded('id_ed25519', enabled=True)

        # Both keys are now loaded
        keys = list_keys()
        if auto_load:
            self.assertIn(id_rsa, keys)
        self.assertIn(id_ed25519, keys)

        # Unload the RSA key
        if auto_load:
            toggleKeyState('id_rsa')
            waitKeyLoaded('id_rsa', enabled=False)

        # Only DSA keys now loaded
        keys = list_keys()
        self.assertIn(id_ed25519, keys)
        self.assertNotIn(id_rsa, keys)

        # Change password of DSA key
        toggleExpandedStateKey('id_ed25519')
        selectTab('id_ed25519', 'Password')
        b.set_input_text("#id_ed25519-old-password", "locked")
        b.set_input_text("#id_ed25519-new-password", "foobar")
        b.set_input_text("#id_ed25519-confirm-password", "foobar")
        b.assert_pixels("#credentials-modal", "ssh-keys-dialog", chrome_hack_double_shots=True)

        b.click("#id_ed25519-change-password")
        b.wait_visible('#credentials-modal .pf-v6-c-helper-text__item.pf-m-success')

        # Log off and log back in, and we should have both loaded automatically
        if auto_load:
            b.click("#credentials-modal button[aria-label=Close]")
            b.wait_not_present("#credentials-modal")
            b.logout()
            b.login_and_go()
            keys = list_keys()
            self.assertIn(id_rsa, keys)
            self.assertIn(id_ed25519, keys)

            b.open_session_menu()
            b.click("#sshkeys")
            b.wait_visible("#credentials-modal")

        # Add bad keys
        # generate a new key
        m.execute("ssh-keygen -t rsa -N '' -f /tmp/new.rsa")
        self.addCleanup(m.execute, "rm -f /tmp/new.rsa*")
        m.execute("chown admin:admin /tmp/new.rsa")
        new_pk = m.execute("cat /tmp/new.rsa.pub").strip().split()[0]
        m.execute("rm /tmp/new.rsa.pub")

        waitKeyPresent('id_rsa', present=True)

        b.wait_visible("#credential-keys")
        b.wait_not_present("#ssh-file-add")
        b.click("#ssh-file-add-custom")
        b.set_file_autocomplete_val("#ssh-file-add-key", "/etc/")
        b.click("#ssh-file-add")
        b.wait_text("#credentials-modal .pf-m-error > .pf-v6-c-helper-text__item-text", "Not a valid private key")

        b.set_input_text("#credentials-modal .pf-v6-c-menu-toggle input", "/var/test/")
        b.wait_in_text(".pf-v6-c-menu__list-item.pf-m-aria-disabled", "No such file or directory")
        b.focus("#credentials-modal .pf-v6-c-menu-toggle input")
        b.key("Backspace", 5)
        b.wait_visible(".pf-v6-c-menu__list-item.directory:contains('/var/lib/')")
        b.click("#credentials-modal .pf-v6-c-menu-toggle button[aria-label='Clear input value']")
        b.wait_val("#credentials-modal .pf-v6-c-menu-toggle input", "")

        b.set_file_autocomplete_val("#ssh-file-add-key", "/tmp/new.rsa")
        b.click("#ssh-file-add")
        b.wait_not_present("#ssh-file-add")
        # OpenSSH 7.8 and up has a new default key format where
        # keys are marked as "agent_only", thereby limiting functionality
        keys = list_keys()
        keys_length = 3 if auto_load else 2
        # Keys are like: 256 SHA256:x6S6fxMuEyqhpwNRAIK7ms6bZDY6xK9wzdDr2kCaWVY id_ed25519 (ED25519)
        # We need the id_ed25519 part, (name or comment)
        new_key = keys.splitlines()[keys_length - 1].split(' ')[2]
        toggleKeyState(new_key)

        toggleExpandedStateKey(new_key)
        waitKeyRowExpanded(new_key, expanded=True)
        waitTabActive(new_key, 'Details')
        waitKeyDetail(new_key, 'type', 'RSA')
        self.assertNotEqual(getKeyDetail(new_key, "fingerprint"), "")
        selectTab(new_key, 'Public key')
        self.assertTrue(b.val(f"tr[data-name='{new_key}'] + tr .pf-v6-c-clipboard-copy input").startswith(new_pk))

        # OpenSSH 7.8 and up has a new default key format where
        # keys are marked as "agent_only", thereby limiting functionality
        # "agent_only" keys cannot be turned off, or have their passwords changed
        waitKeyLoaded(new_key, enabled=True)

        # Test adding key with passphrase
        m.execute("ssh-keygen -t rsa -N 'foobar' -f /tmp/new_with_passphrase.rsa")
        self.addCleanup(m.execute, "rm -f /tmp/new_with_passphrase.rsa*")
        m.execute("chown admin:admin /tmp/new_with_passphrase.rsa")
        m.execute("rm /tmp/new_with_passphrase.rsa.pub")

        b.wait_not_present("#ssh-file-add")
        b.click("#ssh-file-add-custom")
        b.set_file_autocomplete_val("#ssh-file-add-key", "/tmp/new_with_passphrase.rsa")
        b.click("#ssh-file-add")
        b.wait_visible("h1:contains('Unlock key /tmp/new_with_passphrase.rsa')")
        b.set_input_text("#\\/tmp\\/new_with_passphrase\\.rsa-password", "foobar")
        b.click("button:contains('Unlock')")
        b.wait_not_present("h1:contains('Unlock key /tmp/new_with_passphrase.rsa')")
        b.wait_not_present("#ssh-file-add")
        b.wait_count("#credential-keys tbody", 4)

        b.click("#credentials-modal button[aria-label=Close]")
        b.wait_not_present("#credentials-modal")


if __name__ == '__main__':
    testlib.test_main()