migration: API to clear bits of guest free pages from the dirty bitmap
[qemu/ar7.git] / tests / qemu-iotests / 149
blob4f363f295f83103edbed153b9586c2560c5b3c56
1 #!/usr/bin/env python
3 # Copyright (C) 2016 Red Hat, Inc.
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.
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.
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/>.
18 # Creator/Owner: Daniel P. Berrange <berrange@redhat.com>
20 # Exercise the QEMU 'luks' block driver to validate interoperability
21 # with the Linux dm-crypt + cryptsetup implementation
23 from __future__ import print_function
24 import subprocess
25 import os
26 import os.path
28 import base64
30 import iotests
33 class LUKSConfig(object):
34 """Represent configuration parameters for a single LUKS
35 setup to be tested"""
37 def __init__(self, name, cipher, keylen, mode, ivgen,
38 ivgen_hash, hash, password=None, passwords=None):
40 self.name = name
41 self.cipher = cipher
42 self.keylen = keylen
43 self.mode = mode
44 self.ivgen = ivgen
45 self.ivgen_hash = ivgen_hash
46 self.hash = hash
48 if passwords is not None:
49 self.passwords = passwords
50 else:
51 self.passwords = {}
53 if password is None:
54 self.passwords["0"] = "123456"
55 else:
56 self.passwords["0"] = password
58 def __repr__(self):
59 return self.name
61 def image_name(self):
62 return "luks-%s.img" % self.name
64 def image_path(self):
65 return os.path.join(iotests.test_dir, self.image_name())
67 def device_name(self):
68 return "qiotest-145-%s" % self.name
70 def device_path(self):
71 return "/dev/mapper/" + self.device_name()
73 def first_password(self):
74 for i in range(8):
75 slot = str(i)
76 if slot in self.passwords:
77 return (self.passwords[slot], slot)
78 raise Exception("No password found")
80 def first_password_base64(self):
81 (pw, slot) = self.first_password()
82 return base64.b64encode(pw.encode('ascii')).decode('ascii')
84 def active_slots(self):
85 slots = []
86 for i in range(8):
87 slot = str(i)
88 if slot in self.passwords:
89 slots.append(slot)
90 return slots
92 def verify_passwordless_sudo():
93 """Check whether sudo is configured to allow
94 password-less access to commands"""
96 args = ["sudo", "-n", "/bin/true"]
98 proc = subprocess.Popen(args,
99 stdin=subprocess.PIPE,
100 stdout=subprocess.PIPE,
101 stderr=subprocess.STDOUT,
102 universal_newlines=True)
104 msg = proc.communicate()[0]
106 if proc.returncode != 0:
107 iotests.notrun('requires password-less sudo access: %s' % msg)
110 def cryptsetup(args, password=None):
111 """Run the cryptsetup command in batch mode"""
113 fullargs = ["sudo", "cryptsetup", "-q", "-v"]
114 fullargs.extend(args)
116 iotests.log(" ".join(fullargs), filters=[iotests.filter_test_dir])
117 proc = subprocess.Popen(fullargs,
118 stdin=subprocess.PIPE,
119 stdout=subprocess.PIPE,
120 stderr=subprocess.STDOUT,
121 universal_newlines=True)
123 msg = proc.communicate(password)[0]
125 if proc.returncode != 0:
126 raise Exception(msg)
129 def cryptsetup_add_password(config, slot):
130 """Add another password to a LUKS key slot"""
132 (password, mainslot) = config.first_password()
134 pwfile = os.path.join(iotests.test_dir, "passwd.txt")
135 with open(pwfile, "w") as fh:
136 fh.write(config.passwords[slot])
138 try:
139 args = ["luksAddKey", config.image_path(),
140 "--key-slot", slot,
141 "--key-file", "-",
142 "--iter-time", "10",
143 pwfile]
145 cryptsetup(args, password)
146 finally:
147 os.unlink(pwfile)
150 def cryptsetup_format(config):
151 """Format a new LUKS volume with cryptsetup, adding the
152 first key slot only"""
154 (password, slot) = config.first_password()
156 args = ["luksFormat"]
157 cipher = config.cipher + "-" + config.mode + "-" + config.ivgen
158 if config.ivgen_hash is not None:
159 cipher = cipher + ":" + config.ivgen_hash
160 elif config.ivgen == "essiv":
161 cipher = cipher + ":" + "sha256"
162 args.extend(["--cipher", cipher])
163 if config.mode == "xts":
164 args.extend(["--key-size", str(config.keylen * 2)])
165 else:
166 args.extend(["--key-size", str(config.keylen)])
167 if config.hash is not None:
168 args.extend(["--hash", config.hash])
169 args.extend(["--key-slot", slot])
170 args.extend(["--key-file", "-"])
171 args.extend(["--iter-time", "10"])
172 args.append(config.image_path())
174 cryptsetup(args, password)
177 def chown(config):
178 """Set the ownership of a open LUKS device to this user"""
180 path = config.device_path()
182 args = ["sudo", "chown", "%d:%d" % (os.getuid(), os.getgid()), path]
183 iotests.log(" ".join(args), filters=[iotests.filter_chown])
184 proc = subprocess.Popen(args,
185 stdin=subprocess.PIPE,
186 stdout=subprocess.PIPE,
187 stderr=subprocess.STDOUT)
189 msg = proc.communicate()[0]
191 if proc.returncode != 0:
192 raise Exception(msg)
195 def cryptsetup_open(config):
196 """Open an image as a LUKS device"""
198 (password, slot) = config.first_password()
200 args = ["luksOpen", config.image_path(), config.device_name()]
202 cryptsetup(args, password)
205 def cryptsetup_close(config):
206 """Close an active LUKS device """
208 args = ["luksClose", config.device_name()]
209 cryptsetup(args)
212 def delete_image(config):
213 """Delete a disk image"""
215 try:
216 os.unlink(config.image_path())
217 iotests.log("unlink %s" % config.image_path(),
218 filters=[iotests.filter_test_dir])
219 except Exception as e:
220 pass
223 def create_image(config, size_mb):
224 """Create a bare disk image with requested size"""
226 delete_image(config)
227 iotests.log("truncate %s --size %dMB" % (config.image_path(), size_mb),
228 filters=[iotests.filter_test_dir])
229 with open(config.image_path(), "w") as fn:
230 fn.truncate(size_mb * 1024 * 1024)
233 def qemu_img_create(config, size_mb):
234 """Create and format a disk image with LUKS using qemu-img"""
236 opts = [
237 "key-secret=sec0",
238 "iter-time=10",
239 "cipher-alg=%s-%d" % (config.cipher, config.keylen),
240 "cipher-mode=%s" % config.mode,
241 "ivgen-alg=%s" % config.ivgen,
242 "hash-alg=%s" % config.hash,
244 if config.ivgen_hash is not None:
245 opts.append("ivgen-hash-alg=%s" % config.ivgen_hash)
247 args = ["create", "-f", "luks",
248 "--object",
249 ("secret,id=sec0,data=%s,format=base64" %
250 config.first_password_base64()),
251 "-o", ",".join(opts),
252 config.image_path(),
253 "%dM" % size_mb]
255 iotests.log("qemu-img " + " ".join(args), filters=[iotests.filter_test_dir])
256 iotests.log(iotests.qemu_img_pipe(*args), filters=[iotests.filter_test_dir])
258 def qemu_io_image_args(config, dev=False):
259 """Get the args for access an image or device with qemu-io"""
261 if dev:
262 return [
263 "--image-opts",
264 "driver=host_device,filename=%s" % config.device_path()]
265 else:
266 return [
267 "--object",
268 ("secret,id=sec0,data=%s,format=base64" %
269 config.first_password_base64()),
270 "--image-opts",
271 ("driver=luks,key-secret=sec0,file.filename=%s" %
272 config.image_path())]
274 def qemu_io_write_pattern(config, pattern, offset_mb, size_mb, dev=False):
275 """Write a pattern of data to a LUKS image or device"""
277 if dev:
278 chown(config)
279 args = ["-c", "write -P 0x%x %dM %dM" % (pattern, offset_mb, size_mb)]
280 args.extend(qemu_io_image_args(config, dev))
281 iotests.log("qemu-io " + " ".join(args), filters=[iotests.filter_test_dir])
282 iotests.log(iotests.qemu_io(*args), filters=[iotests.filter_test_dir,
283 iotests.filter_qemu_io])
286 def qemu_io_read_pattern(config, pattern, offset_mb, size_mb, dev=False):
287 """Read a pattern of data to a LUKS image or device"""
289 if dev:
290 chown(config)
291 args = ["-c", "read -P 0x%x %dM %dM" % (pattern, offset_mb, size_mb)]
292 args.extend(qemu_io_image_args(config, dev))
293 iotests.log("qemu-io " + " ".join(args), filters=[iotests.filter_test_dir])
294 iotests.log(iotests.qemu_io(*args), filters=[iotests.filter_test_dir,
295 iotests.filter_qemu_io])
298 def test_once(config, qemu_img=False):
299 """Run the test with a desired LUKS configuration. Can either
300 use qemu-img for creating the initial volume, or cryptsetup,
301 in order to test interoperability in both directions"""
303 iotests.log("# ================= %s %s =================" % (
304 "qemu-img" if qemu_img else "dm-crypt", config))
306 oneKB = 1024
307 oneMB = oneKB * 1024
308 oneGB = oneMB * 1024
309 oneTB = oneGB * 1024
311 # 4 TB, so that we pass the 32-bit sector number boundary.
312 # Important for testing correctness of some IV generators
313 # The files are sparse, so not actually using this much space
314 image_size = 4 * oneTB
315 if qemu_img:
316 iotests.log("# Create image")
317 qemu_img_create(config, image_size // oneMB)
318 else:
319 iotests.log("# Create image")
320 create_image(config, image_size // oneMB)
322 lowOffsetMB = 100
323 highOffsetMB = 3 * oneTB // oneMB
325 try:
326 if not qemu_img:
327 iotests.log("# Format image")
328 cryptsetup_format(config)
330 for slot in config.active_slots()[1:]:
331 iotests.log("# Add password slot %s" % slot)
332 cryptsetup_add_password(config, slot)
334 # First we'll open the image using cryptsetup and write a
335 # known pattern of data that we'll then verify with QEMU
337 iotests.log("# Open dev")
338 cryptsetup_open(config)
340 try:
341 iotests.log("# Write test pattern 0xa7")
342 qemu_io_write_pattern(config, 0xa7, lowOffsetMB, 10, dev=True)
343 iotests.log("# Write test pattern 0x13")
344 qemu_io_write_pattern(config, 0x13, highOffsetMB, 10, dev=True)
345 finally:
346 iotests.log("# Close dev")
347 cryptsetup_close(config)
349 # Ok, now we're using QEMU to verify the pattern just
350 # written via dm-crypt
352 iotests.log("# Read test pattern 0xa7")
353 qemu_io_read_pattern(config, 0xa7, lowOffsetMB, 10, dev=False)
354 iotests.log("# Read test pattern 0x13")
355 qemu_io_read_pattern(config, 0x13, highOffsetMB, 10, dev=False)
358 # Write a new pattern to the image, which we'll later
359 # verify with dm-crypt
360 iotests.log("# Write test pattern 0x91")
361 qemu_io_write_pattern(config, 0x91, lowOffsetMB, 10, dev=False)
362 iotests.log("# Write test pattern 0x5e")
363 qemu_io_write_pattern(config, 0x5e, highOffsetMB, 10, dev=False)
366 # Now we're opening the image with dm-crypt once more
367 # and verifying what QEMU wrote, completing the circle
368 iotests.log("# Open dev")
369 cryptsetup_open(config)
371 try:
372 iotests.log("# Read test pattern 0x91")
373 qemu_io_read_pattern(config, 0x91, lowOffsetMB, 10, dev=True)
374 iotests.log("# Read test pattern 0x5e")
375 qemu_io_read_pattern(config, 0x5e, highOffsetMB, 10, dev=True)
376 finally:
377 iotests.log("# Close dev")
378 cryptsetup_close(config)
379 finally:
380 iotests.log("# Delete image")
381 delete_image(config)
382 print()
385 # Obviously we only work with the luks image format
386 iotests.verify_image_format(supported_fmts=['luks'])
387 iotests.verify_platform()
389 # We need sudo in order to run cryptsetup to create
390 # dm-crypt devices. This is safe to use on any
391 # machine, since all dm-crypt devices are backed
392 # by newly created plain files, and have a dm-crypt
393 # name prefix of 'qiotest' to avoid clashing with
394 # user LUKS volumes
395 verify_passwordless_sudo()
398 # If we look at all permutations of cipher, key size,
399 # mode, ivgen, hash, there are ~1000 possible configs.
401 # We certainly don't want/need to test every permutation
402 # to get good validation of interoperability between QEMU
403 # and dm-crypt/cryptsetup.
405 # The configs below are a representative set that aim to
406 # exercise each axis of configurability.
408 configs = [
409 # A common LUKS default
410 LUKSConfig("aes-256-xts-plain64-sha1",
411 "aes", 256, "xts", "plain64", None, "sha1"),
414 # LUKS default but diff ciphers
415 LUKSConfig("twofish-256-xts-plain64-sha1",
416 "twofish", 256, "xts", "plain64", None, "sha1"),
417 LUKSConfig("serpent-256-xts-plain64-sha1",
418 "serpent", 256, "xts", "plain64", None, "sha1"),
419 # Should really be xts, but kernel doesn't support xts+cast5
420 # nor does it do essiv+cast5
421 LUKSConfig("cast5-128-cbc-plain64-sha1",
422 "cast5", 128, "cbc", "plain64", None, "sha1"),
423 LUKSConfig("cast6-256-xts-plain64-sha1",
424 "cast6", 256, "xts", "plain64", None, "sha1"),
427 # LUKS default but diff modes / ivgens
428 LUKSConfig("aes-256-cbc-plain-sha1",
429 "aes", 256, "cbc", "plain", None, "sha1"),
430 LUKSConfig("aes-256-cbc-plain64-sha1",
431 "aes", 256, "cbc", "plain64", None, "sha1"),
432 LUKSConfig("aes-256-cbc-essiv-sha256-sha1",
433 "aes", 256, "cbc", "essiv", "sha256", "sha1"),
434 LUKSConfig("aes-256-xts-essiv-sha256-sha1",
435 "aes", 256, "xts", "essiv", "sha256", "sha1"),
438 # LUKS default but smaller key sizes
439 LUKSConfig("aes-128-xts-plain64-sha256-sha1",
440 "aes", 128, "xts", "plain64", None, "sha1"),
441 LUKSConfig("aes-192-xts-plain64-sha256-sha1",
442 "aes", 192, "xts", "plain64", None, "sha1"),
444 LUKSConfig("twofish-128-xts-plain64-sha1",
445 "twofish", 128, "xts", "plain64", None, "sha1"),
446 LUKSConfig("twofish-192-xts-plain64-sha1",
447 "twofish", 192, "xts", "plain64", None, "sha1"),
449 LUKSConfig("serpent-128-xts-plain64-sha1",
450 "serpent", 128, "xts", "plain64", None, "sha1"),
451 LUKSConfig("serpent-192-xts-plain64-sha1",
452 "serpent", 192, "xts", "plain64", None, "sha1"),
454 LUKSConfig("cast6-128-xts-plain64-sha1",
455 "cast6", 128, "xts", "plain", None, "sha1"),
456 LUKSConfig("cast6-192-xts-plain64-sha1",
457 "cast6", 192, "xts", "plain64", None, "sha1"),
460 # LUKS default but diff hash
461 LUKSConfig("aes-256-xts-plain64-sha224",
462 "aes", 256, "xts", "plain64", None, "sha224"),
463 LUKSConfig("aes-256-xts-plain64-sha256",
464 "aes", 256, "xts", "plain64", None, "sha256"),
465 LUKSConfig("aes-256-xts-plain64-sha384",
466 "aes", 256, "xts", "plain64", None, "sha384"),
467 LUKSConfig("aes-256-xts-plain64-sha512",
468 "aes", 256, "xts", "plain64", None, "sha512"),
469 LUKSConfig("aes-256-xts-plain64-ripemd160",
470 "aes", 256, "xts", "plain64", None, "ripemd160"),
472 # Password in slot 3
473 LUKSConfig("aes-256-xts-plain-sha1-pwslot3",
474 "aes", 256, "xts", "plain", None, "sha1",
475 passwords={
476 "3": "slot3",
479 # Passwords in every slot
480 LUKSConfig("aes-256-xts-plain-sha1-pwallslots",
481 "aes", 256, "xts", "plain", None, "sha1",
482 passwords={
483 "0": "slot1",
484 "1": "slot1",
485 "2": "slot2",
486 "3": "slot3",
487 "4": "slot4",
488 "5": "slot5",
489 "6": "slot6",
490 "7": "slot7",
493 # Check handling of default hash alg (sha256) with essiv
494 LUKSConfig("aes-256-cbc-essiv-auto-sha1",
495 "aes", 256, "cbc", "essiv", None, "sha1"),
497 # Check that a useless hash provided for 'plain64' iv gen
498 # is ignored and no error raised
499 LUKSConfig("aes-256-cbc-plain64-sha256-sha1",
500 "aes", 256, "cbc", "plain64", "sha256", "sha1"),
504 blacklist = [
505 # We don't have a cast-6 cipher impl for QEMU yet
506 "cast6-256-xts-plain64-sha1",
507 "cast6-128-xts-plain64-sha1",
508 "cast6-192-xts-plain64-sha1",
510 # GCrypt doesn't support Twofish with 192 bit key
511 "twofish-192-xts-plain64-sha1",
514 whitelist = []
515 if "LUKS_CONFIG" in os.environ:
516 whitelist = os.environ["LUKS_CONFIG"].split(",")
518 for config in configs:
519 if config.name in blacklist:
520 iotests.log("Skipping %s in blacklist" % config.name)
521 continue
523 if len(whitelist) > 0 and config.name not in whitelist:
524 iotests.log("Skipping %s not in whitelist" % config.name)
525 continue
527 test_once(config, qemu_img=False)
529 # XXX we should support setting passwords in a non-0
530 # key slot with 'qemu-img create' in future
531 (pw, slot) = config.first_password()
532 if slot == "0":
533 test_once(config, qemu_img=True)