xref: /openbmc/qemu/tests/qemu-iotests/296 (revision a68694cd)
1#!/usr/bin/env python3
2#
3# Test case for encryption key management versus image sharing
4#
5# Copyright (C) 2019 Red Hat, Inc.
6#
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program.  If not, see <http://www.gnu.org/licenses/>.
19#
20
21import iotests
22import os
23import time
24import json
25
26test_img = os.path.join(iotests.test_dir, 'test.img')
27
28class Secret:
29    def __init__(self, index):
30        self._id = "keysec" + str(index)
31        # you are not supposed to see the password...
32        self._secret = "hunter" + str(index)
33
34    def id(self):
35        return self._id
36
37    def secret(self):
38        return self._secret
39
40    def to_cmdline_object(self):
41        return  [ "secret,id=" + self._id + ",data=" + self._secret]
42
43    def to_qmp_object(self):
44        return { "qom_type" : "secret", "id": self.id(),
45                 "props": { "data": self.secret() } }
46
47################################################################################
48
49class EncryptionSetupTestCase(iotests.QMPTestCase):
50
51    # test case startup
52    def setUp(self):
53
54        # start the VMs
55        self.vm1 = iotests.VM(path_suffix = 'VM1')
56        self.vm2 = iotests.VM(path_suffix = 'VM2')
57        self.vm1.launch()
58        self.vm2.launch()
59
60        # create the secrets and load 'em into the VMs
61        self.secrets = [ Secret(i) for i in range(0, 4) ]
62        for secret in self.secrets:
63            result = self.vm1.qmp("object-add", **secret.to_qmp_object())
64            self.assert_qmp(result, 'return', {})
65            result = self.vm2.qmp("object-add", **secret.to_qmp_object())
66            self.assert_qmp(result, 'return', {})
67
68    # test case shutdown
69    def tearDown(self):
70        # stop the VM
71        self.vm1.shutdown()
72        self.vm2.shutdown()
73
74    ###########################################################################
75    # create the encrypted block device using qemu-img
76    def createImg(self, file, secret):
77
78        output = iotests.qemu_img_pipe(
79            'create',
80            '--object', *secret.to_cmdline_object(),
81            '-f', iotests.imgfmt,
82            '-o', 'key-secret=' + secret.id(),
83            '-o', 'iter-time=10',
84            file,
85            '1M')
86
87        iotests.log(output, filters=[iotests.filter_test_dir])
88
89    # attempts to add a key using qemu-img
90    def addKey(self, file, secret, new_secret):
91
92        image_options = {
93            'key-secret' : secret.id(),
94            'driver' : iotests.imgfmt,
95            'file' : {
96                'driver':'file',
97                'filename': file,
98                }
99            }
100
101        output = iotests.qemu_img_pipe(
102            'amend',
103            '--object', *secret.to_cmdline_object(),
104            '--object', *new_secret.to_cmdline_object(),
105
106            '-o', 'state=active',
107            '-o', 'new-secret=' + new_secret.id(),
108            '-o', 'iter-time=10',
109
110            "json:" + json.dumps(image_options)
111            )
112
113        iotests.log(output, filters=[iotests.filter_test_dir])
114
115    ###########################################################################
116    # open an encrypted block device
117    def openImageQmp(self, vm, id, file, secret,
118                     readOnly = False, reOpen = False):
119
120        command = 'x-blockdev-reopen' if reOpen else 'blockdev-add'
121
122        result = vm.qmp(command, **
123            {
124                'driver': iotests.imgfmt,
125                'node-name': id,
126                'read-only': readOnly,
127                'key-secret' : secret.id(),
128                'file': {
129                    'driver': 'file',
130                    'filename': test_img,
131                }
132            }
133        )
134        self.assert_qmp(result, 'return', {})
135
136
137    ###########################################################################
138    # add virtio-blk consumer for a block device
139    def addImageUser(self, vm, id, disk_id, share_rw=False):
140        result = vm.qmp('device_add', **
141            {
142                'driver': 'virtio-blk',
143                'id': id,
144                'drive': disk_id,
145                'share-rw' : share_rw
146            }
147        )
148
149        iotests.log(result)
150
151    # close the encrypted block device
152    def closeImageQmp(self, vm, id):
153        result = vm.qmp('blockdev-del', **{ 'node-name': id })
154        self.assert_qmp(result, 'return', {})
155
156    ###########################################################################
157
158    # add a key to an encrypted block device
159    def addKeyQmp(self, vm, id, new_secret):
160
161        args = {
162            'node-name': id,
163            'job-id' : 'job0',
164            'options' : {
165                'state'     : 'active',
166                'driver'    : iotests.imgfmt,
167                'new-secret': new_secret.id(),
168                'iter-time' : 10
169            },
170        }
171
172        result = vm.qmp('x-blockdev-amend', **args)
173        assert result['return'] == {}
174        vm.run_job('job0')
175
176    # test that when the image opened by two qemu processes,
177    # neither of them can update the encryption keys
178    def test1(self):
179        self.createImg(test_img, self.secrets[0]);
180
181        # VM1 opens the image and adds a key
182        self.openImageQmp(self.vm1, "testdev", test_img, self.secrets[0])
183        self.addKeyQmp(self.vm1, "testdev", new_secret = self.secrets[1])
184
185
186        # VM2 opens the image
187        self.openImageQmp(self.vm2, "testdev", test_img, self.secrets[0])
188
189
190        # neither VMs now should be able to add a key
191        self.addKeyQmp(self.vm1, "testdev", new_secret = self.secrets[2])
192        self.addKeyQmp(self.vm2, "testdev", new_secret = self.secrets[2])
193
194
195        # VM 1 closes the image
196        self.closeImageQmp(self.vm1, "testdev")
197
198
199        # now VM2 can add the key
200        self.addKeyQmp(self.vm2, "testdev", new_secret = self.secrets[2])
201
202
203        # qemu-img should also not be able to add a key
204        self.addKey(test_img, self.secrets[0], self.secrets[2])
205
206        # cleanup
207        self.closeImageQmp(self.vm2, "testdev")
208        os.remove(test_img)
209
210
211    # test that when the image opened by two qemu processes,
212    # even if first VM opens it read-only, the second can't update encryption
213    # keys
214    def test2(self):
215        self.createImg(test_img, self.secrets[0]);
216
217        # VM1 opens the image readonly
218        self.openImageQmp(self.vm1, "testdev", test_img, self.secrets[0],
219                          readOnly = True)
220
221        # VM2 opens the image
222        self.openImageQmp(self.vm2, "testdev", test_img, self.secrets[0])
223
224        # VM1 can't add a key since image is readonly
225        self.addKeyQmp(self.vm1, "testdev", new_secret = self.secrets[2])
226
227        # VM2 can't add a key since VM is has the image opened
228        self.addKeyQmp(self.vm2, "testdev", new_secret = self.secrets[2])
229
230
231        #VM1 reopens the image read-write
232        self.openImageQmp(self.vm1, "testdev", test_img, self.secrets[0],
233                          reOpen = True, readOnly = False)
234
235        # VM1 still can't add the key
236        self.addKeyQmp(self.vm1, "testdev", new_secret = self.secrets[2])
237
238        # VM2 gets away
239        self.closeImageQmp(self.vm2, "testdev")
240
241        # VM1 now can add the key
242        self.addKeyQmp(self.vm1, "testdev", new_secret = self.secrets[2])
243
244        self.closeImageQmp(self.vm1, "testdev")
245        os.remove(test_img)
246
247    # test that two VMs can't open the same luks image by default
248    # and attach it to a guest device
249    def test3(self):
250        self.createImg(test_img, self.secrets[0]);
251
252        self.openImageQmp(self.vm1, "testdev", test_img, self.secrets[0])
253        self.addImageUser(self.vm1, "testctrl", "testdev")
254
255        self.openImageQmp(self.vm2, "testdev", test_img, self.secrets[0])
256        self.addImageUser(self.vm2, "testctrl", "testdev")
257
258
259    # test that two VMs can attach the same luks image to a guest device,
260    # if both use share-rw=on
261    def test4(self):
262        self.createImg(test_img, self.secrets[0]);
263
264        self.openImageQmp(self.vm1, "testdev", test_img, self.secrets[0])
265        self.addImageUser(self.vm1, "testctrl", "testdev", share_rw=True)
266
267        self.openImageQmp(self.vm2, "testdev", test_img, self.secrets[0])
268        self.addImageUser(self.vm2, "testctrl", "testdev", share_rw=True)
269
270
271
272if __name__ == '__main__':
273    # support only raw luks since luks encrypted qcow2 is a proper
274    # format driver which doesn't allow any sharing
275    iotests.activate_logging()
276    iotests.main(supported_fmts = ['luks'])
277