xref: /openbmc/qemu/tests/qemu-iotests/149 (revision 4a09d0bb)
1#!/usr/bin/env python
2#
3# Copyright (C) 2016 Red Hat, Inc.
4#
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation; either version 2 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program.  If not, see <http://www.gnu.org/licenses/>.
17#
18# Creator/Owner: Daniel P. Berrange <berrange@redhat.com>
19#
20# Exercise the QEMU 'luks' block driver to validate interoperability
21# with the Linux dm-crypt + cryptsetup implementation
22
23import subprocess
24import os
25import os.path
26
27import base64
28
29import iotests
30
31
32class LUKSConfig(object):
33    """Represent configuration parameters for a single LUKS
34       setup to be tested"""
35
36    def __init__(self, name, cipher, keylen, mode, ivgen,
37                 ivgen_hash, hash, password=None, passwords=None):
38
39        self.name = name
40        self.cipher = cipher
41        self.keylen = keylen
42        self.mode = mode
43        self.ivgen = ivgen
44        self.ivgen_hash = ivgen_hash
45        self.hash = hash
46
47        if passwords is not None:
48            self.passwords = passwords
49        else:
50            self.passwords = {}
51
52            if password is None:
53                self.passwords["0"] = "123456"
54            else:
55                self.passwords["0"] = password
56
57    def __repr__(self):
58        return self.name
59
60    def image_name(self):
61        return "luks-%s.img" % self.name
62
63    def image_path(self):
64        return os.path.join(iotests.test_dir, self.image_name())
65
66    def device_name(self):
67        return "qiotest-145-%s" % self.name
68
69    def device_path(self):
70        return "/dev/mapper/" + self.device_name()
71
72    def first_password(self):
73        for i in range(8):
74            slot = str(i)
75            if slot in self.passwords:
76                return (self.passwords[slot], slot)
77        raise Exception("No password found")
78
79    def first_password_base64(self):
80        (pw, slot) = self.first_password()
81        return base64.b64encode(pw)
82
83    def active_slots(self):
84        slots = []
85        for i in range(8):
86            slot = str(i)
87            if slot in self.passwords:
88                slots.append(slot)
89        return slots
90
91def verify_passwordless_sudo():
92    """Check whether sudo is configured to allow
93       password-less access to commands"""
94
95    args = ["sudo", "-n", "/bin/true"]
96
97    proc = subprocess.Popen(args,
98                            stdin=subprocess.PIPE,
99                            stdout=subprocess.PIPE,
100                            stderr=subprocess.STDOUT)
101
102    msg = proc.communicate()[0]
103
104    if proc.returncode != 0:
105        iotests.notrun('requires password-less sudo access: %s' % msg)
106
107
108def cryptsetup(args, password=None):
109    """Run the cryptsetup command in batch mode"""
110
111    fullargs = ["sudo", "cryptsetup", "-q", "-v"]
112    fullargs.extend(args)
113
114    iotests.log(" ".join(fullargs), filters=[iotests.filter_test_dir])
115    proc = subprocess.Popen(fullargs,
116                            stdin=subprocess.PIPE,
117                            stdout=subprocess.PIPE,
118                            stderr=subprocess.STDOUT)
119
120    msg = proc.communicate(password)[0]
121
122    if proc.returncode != 0:
123        raise Exception(msg)
124
125
126def cryptsetup_add_password(config, slot):
127    """Add another password to a LUKS key slot"""
128
129    (password, mainslot) = config.first_password()
130
131    pwfile = os.path.join(iotests.test_dir, "passwd.txt")
132    with open(pwfile, "w") as fh:
133        fh.write(config.passwords[slot])
134
135    try:
136        args = ["luksAddKey", config.image_path(),
137                "--key-slot", slot,
138                "--key-file", "-",
139                pwfile]
140
141        cryptsetup(args, password)
142    finally:
143        os.unlink(pwfile)
144
145
146def cryptsetup_format(config):
147    """Format a new LUKS volume with cryptsetup, adding the
148    first key slot only"""
149
150    (password, slot) = config.first_password()
151
152    args = ["luksFormat"]
153    cipher = config.cipher + "-" + config.mode + "-" + config.ivgen
154    if config.ivgen_hash is not None:
155        cipher = cipher + ":" + config.ivgen_hash
156    elif config.ivgen == "essiv":
157        cipher = cipher + ":" + "sha256"
158    args.extend(["--cipher", cipher])
159    if config.mode == "xts":
160        args.extend(["--key-size", str(config.keylen * 2)])
161    else:
162        args.extend(["--key-size", str(config.keylen)])
163    if config.hash is not None:
164        args.extend(["--hash", config.hash])
165    args.extend(["--key-slot", slot])
166    args.extend(["--key-file", "-"])
167    args.append(config.image_path())
168
169    cryptsetup(args, password)
170
171
172def chown(config):
173    """Set the ownership of a open LUKS device to this user"""
174
175    path = config.device_path()
176
177    args = ["sudo", "chown", "%d:%d" % (os.getuid(), os.getgid()), path]
178    iotests.log(" ".join(args), filters=[iotests.filter_chown])
179    proc = subprocess.Popen(args,
180                            stdin=subprocess.PIPE,
181                            stdout=subprocess.PIPE,
182                            stderr=subprocess.STDOUT)
183
184    msg = proc.communicate()[0]
185
186    if proc.returncode != 0:
187        raise Exception("Cannot change owner on %s" % path)
188
189
190def cryptsetup_open(config):
191    """Open an image as a LUKS device"""
192
193    (password, slot) = config.first_password()
194
195    args = ["luksOpen", config.image_path(), config.device_name()]
196
197    cryptsetup(args, password)
198
199
200def cryptsetup_close(config):
201    """Close an active LUKS device """
202
203    args = ["luksClose", config.device_name()]
204    cryptsetup(args)
205
206
207def delete_image(config):
208    """Delete a disk image"""
209
210    try:
211        os.unlink(config.image_path())
212        iotests.log("unlink %s" % config.image_path(),
213                    filters=[iotests.filter_test_dir])
214    except Exception as e:
215        pass
216
217
218def create_image(config, size_mb):
219    """Create a bare disk image with requested size"""
220
221    delete_image(config)
222    iotests.log("truncate %s --size %dMB" % (config.image_path(), size_mb),
223                filters=[iotests.filter_test_dir])
224    with open(config.image_path(), "w") as fn:
225        fn.truncate(size_mb * 1024 * 1024)
226
227
228def qemu_img_create(config, size_mb):
229    """Create and format a disk image with LUKS using qemu-img"""
230
231    opts = [
232        "key-secret=sec0",
233        "cipher-alg=%s-%d" % (config.cipher, config.keylen),
234        "cipher-mode=%s" % config.mode,
235        "ivgen-alg=%s" % config.ivgen,
236        "hash-alg=%s" % config.hash,
237    ]
238    if config.ivgen_hash is not None:
239        opts.append("ivgen-hash-alg=%s" % config.ivgen_hash)
240
241    args = ["create", "-f", "luks",
242            "--object",
243            ("secret,id=sec0,data=%s,format=base64" %
244             config.first_password_base64()),
245            "-o", ",".join(opts),
246            config.image_path(),
247            "%dM" % size_mb]
248
249    iotests.log("qemu-img " + " ".join(args), filters=[iotests.filter_test_dir])
250    iotests.log(iotests.qemu_img_pipe(*args), filters=[iotests.filter_test_dir])
251
252def qemu_io_image_args(config, dev=False):
253    """Get the args for access an image or device with qemu-io"""
254
255    if dev:
256        return [
257            "--image-opts",
258            "driver=file,filename=%s" % config.device_path()]
259    else:
260        return [
261            "--object",
262            ("secret,id=sec0,data=%s,format=base64" %
263             config.first_password_base64()),
264            "--image-opts",
265            ("driver=luks,key-secret=sec0,file.filename=%s" %
266             config.image_path())]
267
268def qemu_io_write_pattern(config, pattern, offset_mb, size_mb, dev=False):
269    """Write a pattern of data to a LUKS image or device"""
270
271    args = ["-c", "write -P 0x%x %dM %dM" % (pattern, offset_mb, size_mb)]
272    args.extend(qemu_io_image_args(config, dev))
273    iotests.log("qemu-io " + " ".join(args), filters=[iotests.filter_test_dir])
274    iotests.log(iotests.qemu_io(*args), filters=[iotests.filter_test_dir,
275                                                 iotests.filter_qemu_io])
276
277
278def qemu_io_read_pattern(config, pattern, offset_mb, size_mb, dev=False):
279    """Read a pattern of data to a LUKS image or device"""
280
281    args = ["-c", "read -P 0x%x %dM %dM" % (pattern, offset_mb, size_mb)]
282    args.extend(qemu_io_image_args(config, dev))
283    iotests.log("qemu-io " + " ".join(args), filters=[iotests.filter_test_dir])
284    iotests.log(iotests.qemu_io(*args), filters=[iotests.filter_test_dir,
285                                                 iotests.filter_qemu_io])
286
287
288def test_once(config, qemu_img=False):
289    """Run the test with a desired LUKS configuration. Can either
290       use qemu-img for creating the initial volume, or cryptsetup,
291       in order to test interoperability in both directions"""
292
293    iotests.log("# ================= %s %s =================" % (
294        "qemu-img" if qemu_img else "dm-crypt", config))
295
296    oneKB = 1024
297    oneMB = oneKB * 1024
298    oneGB = oneMB * 1024
299    oneTB = oneGB * 1024
300
301    # 4 TB, so that we pass the 32-bit sector number boundary.
302    # Important for testing correctness of some IV generators
303    # The files are sparse, so not actually using this much space
304    image_size = 4 * oneTB
305    if qemu_img:
306        iotests.log("# Create image")
307        qemu_img_create(config, image_size / oneMB)
308    else:
309        iotests.log("# Create image")
310        create_image(config, image_size / oneMB)
311
312    lowOffsetMB = 100
313    highOffsetMB = 3 * oneTB / oneMB
314
315    try:
316        if not qemu_img:
317            iotests.log("# Format image")
318            cryptsetup_format(config)
319
320            for slot in config.active_slots()[1:]:
321                iotests.log("# Add password slot %s" % slot)
322                cryptsetup_add_password(config, slot)
323
324        # First we'll open the image using cryptsetup and write a
325        # known pattern of data that we'll then verify with QEMU
326
327        iotests.log("# Open dev")
328        cryptsetup_open(config)
329
330        try:
331            iotests.log("# Set dev owner")
332            chown(config)
333
334            iotests.log("# Write test pattern 0xa7")
335            qemu_io_write_pattern(config, 0xa7, lowOffsetMB, 10, dev=True)
336            iotests.log("# Write test pattern 0x13")
337            qemu_io_write_pattern(config, 0x13, highOffsetMB, 10, dev=True)
338        finally:
339            iotests.log("# Close dev")
340            cryptsetup_close(config)
341
342        # Ok, now we're using QEMU to verify the pattern just
343        # written via dm-crypt
344
345        iotests.log("# Read test pattern 0xa7")
346        qemu_io_read_pattern(config, 0xa7, lowOffsetMB, 10, dev=False)
347        iotests.log("# Read test pattern 0x13")
348        qemu_io_read_pattern(config, 0x13, highOffsetMB, 10, dev=False)
349
350
351        # Write a new pattern to the image, which we'll later
352        # verify with dm-crypt
353        iotests.log("# Write test pattern 0x91")
354        qemu_io_write_pattern(config, 0x91, lowOffsetMB, 10, dev=False)
355        iotests.log("# Write test pattern 0x5e")
356        qemu_io_write_pattern(config, 0x5e, highOffsetMB, 10, dev=False)
357
358
359        # Now we're opening the image with dm-crypt once more
360        # and verifying what QEMU wrote, completing the circle
361        iotests.log("# Open dev")
362        cryptsetup_open(config)
363
364        try:
365            iotests.log("# Set dev owner")
366            chown(config)
367
368            iotests.log("# Read test pattern 0x91")
369            qemu_io_read_pattern(config, 0x91, lowOffsetMB, 10, dev=True)
370            iotests.log("# Read test pattern 0x5e")
371            qemu_io_read_pattern(config, 0x5e, highOffsetMB, 10, dev=True)
372        finally:
373            iotests.log("# Close dev")
374            cryptsetup_close(config)
375    finally:
376        iotests.log("# Delete image")
377        delete_image(config)
378        print
379
380
381# Obviously we only work with the luks image format
382iotests.verify_image_format(supported_fmts=['luks'])
383iotests.verify_platform()
384
385# We need sudo in order to run cryptsetup to create
386# dm-crypt devices. This is safe to use on any
387# machine, since all dm-crypt devices are backed
388# by newly created plain files, and have a dm-crypt
389# name prefix of 'qiotest' to avoid clashing with
390# user LUKS volumes
391verify_passwordless_sudo()
392
393
394# If we look at all permutations of cipher, key size,
395# mode, ivgen, hash, there are ~1000 possible configs.
396#
397# We certainly don't want/need to test every permutation
398# to get good validation of interoperability between QEMU
399# and dm-crypt/cryptsetup.
400#
401# The configs below are a representative set that aim to
402# exercise each axis of configurability.
403#
404configs = [
405    # A common LUKS default
406    LUKSConfig("aes-256-xts-plain64-sha1",
407               "aes", 256, "xts", "plain64", None, "sha1"),
408
409
410    # LUKS default but diff ciphers
411    LUKSConfig("twofish-256-xts-plain64-sha1",
412               "twofish", 256, "xts", "plain64", None, "sha1"),
413    LUKSConfig("serpent-256-xts-plain64-sha1",
414               "serpent", 256, "xts", "plain64", None, "sha1"),
415    # Should really be xts, but kernel doesn't support xts+cast5
416    # nor does it do essiv+cast5
417    LUKSConfig("cast5-128-cbc-plain64-sha1",
418               "cast5", 128, "cbc", "plain64", None, "sha1"),
419    LUKSConfig("cast6-256-xts-plain64-sha1",
420               "cast6", 256, "xts", "plain64", None, "sha1"),
421
422
423    # LUKS default but diff modes / ivgens
424    LUKSConfig("aes-256-cbc-plain-sha1",
425               "aes", 256, "cbc", "plain", None, "sha1"),
426    LUKSConfig("aes-256-cbc-plain64-sha1",
427               "aes", 256, "cbc", "plain64", None, "sha1"),
428    LUKSConfig("aes-256-cbc-essiv-sha256-sha1",
429               "aes", 256, "cbc", "essiv", "sha256", "sha1"),
430    LUKSConfig("aes-256-xts-essiv-sha256-sha1",
431               "aes", 256, "xts", "essiv", "sha256", "sha1"),
432
433
434    # LUKS default but smaller key sizes
435    LUKSConfig("aes-128-xts-plain64-sha256-sha1",
436               "aes", 128, "xts", "plain64", None, "sha1"),
437    LUKSConfig("aes-192-xts-plain64-sha256-sha1",
438               "aes", 192, "xts", "plain64", None, "sha1"),
439
440    LUKSConfig("twofish-128-xts-plain64-sha1",
441               "twofish", 128, "xts", "plain64", None, "sha1"),
442    LUKSConfig("twofish-192-xts-plain64-sha1",
443               "twofish", 192, "xts", "plain64", None, "sha1"),
444
445    LUKSConfig("serpent-128-xts-plain64-sha1",
446               "serpent", 128, "xts", "plain64", None, "sha1"),
447    LUKSConfig("serpent-192-xts-plain64-sha1",
448               "serpent", 192, "xts", "plain64", None, "sha1"),
449
450    LUKSConfig("cast6-128-xts-plain64-sha1",
451               "cast6", 128, "xts", "plain", None, "sha1"),
452    LUKSConfig("cast6-192-xts-plain64-sha1",
453               "cast6", 192, "xts", "plain64", None, "sha1"),
454
455
456    # LUKS default but diff hash
457    LUKSConfig("aes-256-xts-plain64-sha256",
458               "aes", 256, "xts", "plain64", None, "sha256"),
459    LUKSConfig("aes-256-xts-plain64-sha512",
460               "aes", 256, "xts", "plain64", None, "sha512"),
461    LUKSConfig("aes-256-xts-plain64-ripemd160",
462               "aes", 256, "xts", "plain64", None, "ripemd160"),
463
464    # Password in slot 3
465    LUKSConfig("aes-256-xts-plain-sha1-pwslot3",
466               "aes", 256, "xts", "plain", None, "sha1",
467               passwords={
468                   "3": "slot3",
469               }),
470
471    # Passwords in every slot
472    LUKSConfig("aes-256-xts-plain-sha1-pwallslots",
473               "aes", 256, "xts", "plain", None, "sha1",
474               passwords={
475                   "0": "slot1",
476                   "1": "slot1",
477                   "2": "slot2",
478                   "3": "slot3",
479                   "4": "slot4",
480                   "5": "slot5",
481                   "6": "slot6",
482                   "7": "slot7",
483               }),
484
485    # Check handling of default hash alg (sha256) with essiv
486    LUKSConfig("aes-256-cbc-essiv-auto-sha1",
487               "aes", 256, "cbc", "essiv", None, "sha1"),
488
489    # Check that a useless hash provided for 'plain64' iv gen
490    # is ignored and no error raised
491    LUKSConfig("aes-256-cbc-plain64-sha256-sha1",
492               "aes", 256, "cbc", "plain64", "sha256", "sha1"),
493
494]
495
496blacklist = [
497    # We don't have a cast-6 cipher impl for QEMU yet
498    "cast6-256-xts-plain64-sha1",
499    "cast6-128-xts-plain64-sha1",
500    "cast6-192-xts-plain64-sha1",
501
502    # GCrypt doesn't support Twofish with 192 bit key
503    "twofish-192-xts-plain64-sha1",
504
505    # We don't have sha512 hash wired up yet
506    "aes-256-xts-plain64-sha512",
507
508    # We don't have ripemd160 hash wired up yet
509    "aes-256-xts-plain64-ripemd160",
510]
511
512whitelist = []
513if "LUKS_CONFIG" in os.environ:
514    whitelist = os.environ["LUKS_CONFIG"].split(",")
515
516for config in configs:
517    if config.name in blacklist:
518        iotests.log("Skipping %s in blacklist" % config.name)
519        continue
520
521    if len(whitelist) > 0 and config.name not in whitelist:
522        iotests.log("Skipping %s not in whitelist" % config.name)
523        continue
524
525    test_once(config, qemu_img=False)
526
527    # XXX we should support setting passwords in a non-0
528    # key slot with 'qemu-img create' in future
529    (pw, slot) = config.first_password()
530    if slot == "0":
531        test_once(config, qemu_img=True)
532