1#!/usr/bin/env python3 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.encode('ascii')).decode('ascii') 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 universal_newlines=True) 102 103 msg = proc.communicate()[0] 104 105 if proc.returncode != 0: 106 iotests.notrun('requires password-less sudo access: %s' % msg) 107 108 109def cryptsetup(args, password=None): 110 """Run the cryptsetup command in batch mode""" 111 112 fullargs = ["sudo", "cryptsetup", "-q", "-v"] 113 fullargs.extend(args) 114 115 iotests.log(" ".join(fullargs), filters=[iotests.filter_test_dir]) 116 proc = subprocess.Popen(fullargs, 117 stdin=subprocess.PIPE, 118 stdout=subprocess.PIPE, 119 stderr=subprocess.STDOUT, 120 universal_newlines=True) 121 122 msg = proc.communicate(password)[0] 123 124 if proc.returncode != 0: 125 raise Exception(msg) 126 127 128def cryptsetup_add_password(config, slot): 129 """Add another password to a LUKS key slot""" 130 131 (password, mainslot) = config.first_password() 132 133 pwfile = os.path.join(iotests.test_dir, "passwd.txt") 134 with open(pwfile, "w") as fh: 135 fh.write(config.passwords[slot]) 136 137 try: 138 args = ["luksAddKey", config.image_path(), 139 "--key-slot", slot, 140 "--key-file", "-", 141 "--iter-time", "10", 142 pwfile] 143 144 cryptsetup(args, password) 145 finally: 146 os.unlink(pwfile) 147 148 149def cryptsetup_format(config): 150 """Format a new LUKS volume with cryptsetup, adding the 151 first key slot only""" 152 153 (password, slot) = config.first_password() 154 155 args = ["luksFormat", "--type", "luks1"] 156 cipher = config.cipher + "-" + config.mode + "-" + config.ivgen 157 if config.ivgen_hash is not None: 158 cipher = cipher + ":" + config.ivgen_hash 159 elif config.ivgen == "essiv": 160 cipher = cipher + ":" + "sha256" 161 args.extend(["--cipher", cipher]) 162 if config.mode == "xts": 163 args.extend(["--key-size", str(config.keylen * 2)]) 164 else: 165 args.extend(["--key-size", str(config.keylen)]) 166 if config.hash is not None: 167 args.extend(["--hash", config.hash]) 168 args.extend(["--key-slot", slot]) 169 args.extend(["--key-file", "-"]) 170 args.extend(["--iter-time", "10"]) 171 args.append(config.image_path()) 172 173 cryptsetup(args, password) 174 175 176def chown(config): 177 """Set the ownership of a open LUKS device to this user""" 178 179 path = config.device_path() 180 181 args = ["sudo", "chown", "%d:%d" % (os.getuid(), os.getgid()), path] 182 iotests.log(" ".join(args), filters=[iotests.filter_chown]) 183 proc = subprocess.Popen(args, 184 stdin=subprocess.PIPE, 185 stdout=subprocess.PIPE, 186 stderr=subprocess.STDOUT) 187 188 msg = proc.communicate()[0] 189 190 if proc.returncode != 0: 191 raise Exception(msg) 192 193 194def cryptsetup_open(config): 195 """Open an image as a LUKS device""" 196 197 (password, slot) = config.first_password() 198 199 args = ["luksOpen", config.image_path(), config.device_name()] 200 201 cryptsetup(args, password) 202 203 204def cryptsetup_close(config): 205 """Close an active LUKS device """ 206 207 args = ["luksClose", config.device_name()] 208 cryptsetup(args) 209 210 211def delete_image(config): 212 """Delete a disk image""" 213 214 try: 215 os.unlink(config.image_path()) 216 iotests.log("unlink %s" % config.image_path(), 217 filters=[iotests.filter_test_dir]) 218 except Exception as e: 219 pass 220 221 222def create_image(config, size_mb): 223 """Create a bare disk image with requested size""" 224 225 delete_image(config) 226 iotests.log("truncate %s --size %dMB" % (config.image_path(), size_mb), 227 filters=[iotests.filter_test_dir]) 228 with open(config.image_path(), "w") as fn: 229 fn.truncate(size_mb * 1024 * 1024) 230 231 232def qemu_img_create(config, size_mb): 233 """Create and format a disk image with LUKS using qemu-img""" 234 235 opts = [ 236 "key-secret=sec0", 237 "iter-time=10", 238 "cipher-alg=%s-%d" % (config.cipher, config.keylen), 239 "cipher-mode=%s" % config.mode, 240 "ivgen-alg=%s" % config.ivgen, 241 "hash-alg=%s" % config.hash, 242 ] 243 if config.ivgen_hash is not None: 244 opts.append("ivgen-hash-alg=%s" % config.ivgen_hash) 245 246 args = ["create", "-f", "luks", 247 "--object", 248 ("secret,id=sec0,data=%s,format=base64" % 249 config.first_password_base64()), 250 "-o", ",".join(opts), 251 config.image_path(), 252 "%dM" % size_mb] 253 254 iotests.log("qemu-img " + " ".join(args), filters=[iotests.filter_test_dir]) 255 iotests.log(iotests.qemu_img_pipe(*args), filters=[iotests.filter_test_dir]) 256 257def qemu_io_image_args(config, dev=False): 258 """Get the args for access an image or device with qemu-io""" 259 260 if dev: 261 return [ 262 "--image-opts", 263 "driver=host_device,filename=%s" % config.device_path()] 264 else: 265 return [ 266 "--object", 267 ("secret,id=sec0,data=%s,format=base64" % 268 config.first_password_base64()), 269 "--image-opts", 270 ("driver=luks,key-secret=sec0,file.filename=%s" % 271 config.image_path())] 272 273def qemu_io_write_pattern(config, pattern, offset_mb, size_mb, dev=False): 274 """Write a pattern of data to a LUKS image or device""" 275 276 if dev: 277 chown(config) 278 args = ["-c", "write -P 0x%x %dM %dM" % (pattern, offset_mb, size_mb)] 279 args.extend(qemu_io_image_args(config, dev)) 280 iotests.log("qemu-io " + " ".join(args), filters=[iotests.filter_test_dir]) 281 iotests.log(iotests.qemu_io(*args), filters=[iotests.filter_test_dir, 282 iotests.filter_qemu_io]) 283 284 285def qemu_io_read_pattern(config, pattern, offset_mb, size_mb, dev=False): 286 """Read a pattern of data to a LUKS image or device""" 287 288 if dev: 289 chown(config) 290 args = ["-c", "read -P 0x%x %dM %dM" % (pattern, offset_mb, size_mb)] 291 args.extend(qemu_io_image_args(config, dev)) 292 iotests.log("qemu-io " + " ".join(args), filters=[iotests.filter_test_dir]) 293 iotests.log(iotests.qemu_io(*args), filters=[iotests.filter_test_dir, 294 iotests.filter_qemu_io]) 295 296 297def test_once(config, qemu_img=False): 298 """Run the test with a desired LUKS configuration. Can either 299 use qemu-img for creating the initial volume, or cryptsetup, 300 in order to test interoperability in both directions""" 301 302 iotests.log("# ================= %s %s =================" % ( 303 "qemu-img" if qemu_img else "dm-crypt", config)) 304 305 oneKB = 1024 306 oneMB = oneKB * 1024 307 oneGB = oneMB * 1024 308 oneTB = oneGB * 1024 309 310 # 4 TB, so that we pass the 32-bit sector number boundary. 311 # Important for testing correctness of some IV generators 312 # The files are sparse, so not actually using this much space 313 image_size = 4 * oneTB 314 if qemu_img: 315 iotests.log("# Create image") 316 qemu_img_create(config, image_size // oneMB) 317 else: 318 iotests.log("# Create image") 319 create_image(config, image_size // oneMB) 320 321 lowOffsetMB = 100 322 highOffsetMB = 3 * oneTB // oneMB 323 324 try: 325 if not qemu_img: 326 iotests.log("# Format image") 327 cryptsetup_format(config) 328 329 for slot in config.active_slots()[1:]: 330 iotests.log("# Add password slot %s" % slot) 331 cryptsetup_add_password(config, slot) 332 333 # First we'll open the image using cryptsetup and write a 334 # known pattern of data that we'll then verify with QEMU 335 336 iotests.log("# Open dev") 337 cryptsetup_open(config) 338 339 try: 340 iotests.log("# Write test pattern 0xa7") 341 qemu_io_write_pattern(config, 0xa7, lowOffsetMB, 10, dev=True) 342 iotests.log("# Write test pattern 0x13") 343 qemu_io_write_pattern(config, 0x13, highOffsetMB, 10, dev=True) 344 finally: 345 iotests.log("# Close dev") 346 cryptsetup_close(config) 347 348 # Ok, now we're using QEMU to verify the pattern just 349 # written via dm-crypt 350 351 iotests.log("# Read test pattern 0xa7") 352 qemu_io_read_pattern(config, 0xa7, lowOffsetMB, 10, dev=False) 353 iotests.log("# Read test pattern 0x13") 354 qemu_io_read_pattern(config, 0x13, highOffsetMB, 10, dev=False) 355 356 357 # Write a new pattern to the image, which we'll later 358 # verify with dm-crypt 359 iotests.log("# Write test pattern 0x91") 360 qemu_io_write_pattern(config, 0x91, lowOffsetMB, 10, dev=False) 361 iotests.log("# Write test pattern 0x5e") 362 qemu_io_write_pattern(config, 0x5e, highOffsetMB, 10, dev=False) 363 364 365 # Now we're opening the image with dm-crypt once more 366 # and verifying what QEMU wrote, completing the circle 367 iotests.log("# Open dev") 368 cryptsetup_open(config) 369 370 try: 371 iotests.log("# Read test pattern 0x91") 372 qemu_io_read_pattern(config, 0x91, lowOffsetMB, 10, dev=True) 373 iotests.log("# Read test pattern 0x5e") 374 qemu_io_read_pattern(config, 0x5e, highOffsetMB, 10, dev=True) 375 finally: 376 iotests.log("# Close dev") 377 cryptsetup_close(config) 378 finally: 379 iotests.log("# Delete image") 380 delete_image(config) 381 print() 382 383 384# Obviously we only work with the luks image format 385iotests.script_initialize(supported_fmts=['luks']) 386 387# We need sudo in order to run cryptsetup to create 388# dm-crypt devices. This is safe to use on any 389# machine, since all dm-crypt devices are backed 390# by newly created plain files, and have a dm-crypt 391# name prefix of 'qiotest' to avoid clashing with 392# user LUKS volumes 393verify_passwordless_sudo() 394 395 396# If we look at all permutations of cipher, key size, 397# mode, ivgen, hash, there are ~1000 possible configs. 398# 399# We certainly don't want/need to test every permutation 400# to get good validation of interoperability between QEMU 401# and dm-crypt/cryptsetup. 402# 403# The configs below are a representative set that aim to 404# exercise each axis of configurability. 405# 406configs = [ 407 # A common LUKS default 408 LUKSConfig("aes-256-xts-plain64-sha1", 409 "aes", 256, "xts", "plain64", None, "sha1"), 410 411 412 # LUKS default but diff ciphers 413 LUKSConfig("twofish-256-xts-plain64-sha1", 414 "twofish", 256, "xts", "plain64", None, "sha1"), 415 LUKSConfig("serpent-256-xts-plain64-sha1", 416 "serpent", 256, "xts", "plain64", None, "sha1"), 417 # Should really be xts, but kernel doesn't support xts+cast5 418 # nor does it do essiv+cast5 419 LUKSConfig("cast5-128-cbc-plain64-sha1", 420 "cast5", 128, "cbc", "plain64", None, "sha1"), 421 LUKSConfig("cast6-256-xts-plain64-sha1", 422 "cast6", 256, "xts", "plain64", None, "sha1"), 423 424 425 # LUKS default but diff modes / ivgens 426 LUKSConfig("aes-256-cbc-plain-sha1", 427 "aes", 256, "cbc", "plain", None, "sha1"), 428 LUKSConfig("aes-256-cbc-plain64-sha1", 429 "aes", 256, "cbc", "plain64", None, "sha1"), 430 LUKSConfig("aes-256-cbc-essiv-sha256-sha1", 431 "aes", 256, "cbc", "essiv", "sha256", "sha1"), 432 LUKSConfig("aes-256-xts-essiv-sha256-sha1", 433 "aes", 256, "xts", "essiv", "sha256", "sha1"), 434 435 436 # LUKS default but smaller key sizes 437 LUKSConfig("aes-128-xts-plain64-sha256-sha1", 438 "aes", 128, "xts", "plain64", None, "sha1"), 439 LUKSConfig("aes-192-xts-plain64-sha256-sha1", 440 "aes", 192, "xts", "plain64", None, "sha1"), 441 442 LUKSConfig("twofish-128-xts-plain64-sha1", 443 "twofish", 128, "xts", "plain64", None, "sha1"), 444 LUKSConfig("twofish-192-xts-plain64-sha1", 445 "twofish", 192, "xts", "plain64", None, "sha1"), 446 447 LUKSConfig("serpent-128-xts-plain64-sha1", 448 "serpent", 128, "xts", "plain64", None, "sha1"), 449 LUKSConfig("serpent-192-xts-plain64-sha1", 450 "serpent", 192, "xts", "plain64", None, "sha1"), 451 452 LUKSConfig("cast6-128-xts-plain64-sha1", 453 "cast6", 128, "xts", "plain", None, "sha1"), 454 LUKSConfig("cast6-192-xts-plain64-sha1", 455 "cast6", 192, "xts", "plain64", None, "sha1"), 456 457 458 # LUKS default but diff hash 459 LUKSConfig("aes-256-xts-plain64-sha224", 460 "aes", 256, "xts", "plain64", None, "sha224"), 461 LUKSConfig("aes-256-xts-plain64-sha256", 462 "aes", 256, "xts", "plain64", None, "sha256"), 463 LUKSConfig("aes-256-xts-plain64-sha384", 464 "aes", 256, "xts", "plain64", None, "sha384"), 465 LUKSConfig("aes-256-xts-plain64-sha512", 466 "aes", 256, "xts", "plain64", None, "sha512"), 467 LUKSConfig("aes-256-xts-plain64-ripemd160", 468 "aes", 256, "xts", "plain64", None, "ripemd160"), 469 470 # Password in slot 3 471 LUKSConfig("aes-256-xts-plain-sha1-pwslot3", 472 "aes", 256, "xts", "plain", None, "sha1", 473 passwords={ 474 "3": "slot3", 475 }), 476 477 # Passwords in every slot 478 LUKSConfig("aes-256-xts-plain-sha1-pwallslots", 479 "aes", 256, "xts", "plain", None, "sha1", 480 passwords={ 481 "0": "slot1", 482 "1": "slot1", 483 "2": "slot2", 484 "3": "slot3", 485 "4": "slot4", 486 "5": "slot5", 487 "6": "slot6", 488 "7": "slot7", 489 }), 490 491 # Check handling of default hash alg (sha256) with essiv 492 LUKSConfig("aes-256-cbc-essiv-auto-sha1", 493 "aes", 256, "cbc", "essiv", None, "sha1"), 494 495 # Check that a useless hash provided for 'plain64' iv gen 496 # is ignored and no error raised 497 LUKSConfig("aes-256-cbc-plain64-sha256-sha1", 498 "aes", 256, "cbc", "plain64", "sha256", "sha1"), 499 500] 501 502blacklist = [ 503 # We don't have a cast-6 cipher impl for QEMU yet 504 "cast6-256-xts-plain64-sha1", 505 "cast6-128-xts-plain64-sha1", 506 "cast6-192-xts-plain64-sha1", 507 508 # GCrypt doesn't support Twofish with 192 bit key 509 "twofish-192-xts-plain64-sha1", 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