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