1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
|
import unittest
import os
import tempfile
import overrides_hack
import secrets
import shutil
import subprocess
import locale
import re
import tarfile
from utils import create_sparse_tempfile, create_lio_device, delete_lio_device, get_avail_locales, requires_locales, run_command, read_file, TestTags, tag_test, required_plugins
import gi
gi.require_version('GLib', '2.0')
gi.require_version('BlockDev', '3.0')
from gi.repository import GLib, BlockDev
PASSWD = "myshinylittlepassword"
PASSWD2 = "myshinylittlepassword2"
PASSWD3 = "myshinylittlepassword3"
def check_cryptsetup_version(version):
try:
succ = BlockDev.utils_check_util_version("cryptsetup", version, "--version", r"cryptsetup ([0-9+\.]+)")
except GLib.GError:
return False
else:
return succ
HAVE_BITLK = check_cryptsetup_version("2.3.0")
HAVE_FVAULT2 = check_cryptsetup_version("2.6.0")
HAVE_OPAL = check_cryptsetup_version("2.7.0")
@required_plugins(("crypto", "loop"))
class CryptoTestCase(unittest.TestCase):
requested_plugins = BlockDev.plugin_specs_from_names(("crypto", "loop"))
_dm_name = "libblockdevTestLUKS"
_sparse_size = 1024**3
_num_devices = 1
loop_devs = []
dev_files = []
@classmethod
def setUpClass(cls):
unittest.TestCase.setUpClass()
cls.avail_locales = get_avail_locales()
if not BlockDev.is_initialized():
BlockDev.init(cls.requested_plugins, None)
else:
BlockDev.reinit(cls.requested_plugins, True, None)
def setUp(self):
self.addCleanup(self._clean_up)
for i in range(self._num_devices):
dev_file = create_sparse_tempfile("crypto_test", self._sparse_size)
self.dev_files.append(dev_file)
try:
loop_dev = create_lio_device(self.dev_files[i])
self.loop_devs.append(loop_dev)
except RuntimeError as e:
raise RuntimeError("Failed to setup loop device for testing: %s" % e)
# make a key file
handle, self.keyfile = tempfile.mkstemp(prefix="libblockdev_test_keyfile", text=False)
os.write(handle, b"nobodyknows")
os.close(handle)
def _clean_up(self):
try:
BlockDev.crypto_luks_close(self._dm_name)
except:
pass
for i in range(self._num_devices):
try:
delete_lio_device(self.loop_devs[i])
except RuntimeError:
# just move on, we can do no better here
pass
os.unlink(self.dev_files[i])
os.unlink(self.keyfile)
self.dev_files.clear()
self.loop_devs.clear()
def _luks_format(self, device, passphrase, keyfile=None, luks_version=BlockDev.CryptoLUKSVersion.LUKS1, fast_pbkdf=False):
if fast_pbkdf:
pbkdf = BlockDev.CryptoLUKSPBKDF(type="pbkdf2", iterations=1000)
extra = BlockDev.CryptoLUKSExtra(pbkdf=pbkdf)
else:
extra = None
ctx = BlockDev.CryptoKeyslotContext(passphrase=passphrase)
BlockDev.crypto_luks_format(device, context=ctx, luks_version=luks_version, extra=extra)
if keyfile:
nctx = BlockDev.CryptoKeyslotContext(keyfile=keyfile)
BlockDev.crypto_luks_add_key(device, ctx, nctx)
def _luks2_format(self, device, passphrase, keyfile=None, fast_pbkdf=False):
return self._luks_format(device, passphrase, keyfile, BlockDev.CryptoLUKSVersion.LUKS2, fast_pbkdf=fast_pbkdf)
def _is_fips_enabled(self):
if not os.path.exists("/proc/sys/crypto/fips_enabled"):
# if the file doesn't exist, we are definitely not in FIPS mode
return False
with open("/proc/sys/crypto/fips_enabled", "r") as f:
enabled = f.read()
return enabled.strip() == "1"
class CryptoNoDevTestCase(CryptoTestCase):
def setUp(self):
# we don't need block devices for this test
pass
@tag_test(TestTags.NOSTORAGE)
def test_plugin_version(self):
self.assertEqual(BlockDev.get_plugin_soname(BlockDev.Plugin.CRYPTO), "libbd_crypto.so.3")
@tag_test(TestTags.NOSTORAGE)
def test_generate_backup_passhprase(self):
"""Verify that backup passphrase generation works as expected"""
exp = r"^([0-9A-Za-z./]{5}-){3}[0-9A-Za-z./]{5}$"
for _i in range(100):
bp = BlockDev.crypto_generate_backup_passphrase()
self.assertRegex(bp, exp)
@tag_test(TestTags.NOSTORAGE)
def test_keyslot_context(self):
"""Verify that keyslot context can be correctly created"""
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
self.assertIsNotNone(ctx)
self.assertEqual(ctx.type, BlockDev.CryptoKeyslotContextType.PASSPHRASE)
ctx = BlockDev.CryptoKeyslotContext(keyfile="keyfile")
self.assertIsNotNone(ctx)
self.assertEqual(ctx.type, BlockDev.CryptoKeyslotContextType.KEYFILE)
ctx = BlockDev.CryptoKeyslotContext(keyring="keyring")
self.assertIsNotNone(ctx)
self.assertEqual(ctx.type, BlockDev.CryptoKeyslotContextType.KEYRING)
ctx = BlockDev.CryptoKeyslotContext(volume_key=[ord(c) for c in PASSWD])
self.assertIsNotNone(ctx)
self.assertEqual(ctx.type, BlockDev.CryptoKeyslotContextType.VOLUME_KEY)
# invalid values and combinations
with self.assertRaisesRegex(ValueError, "Exactly one of .* must be specified"):
BlockDev.CryptoKeyslotContext()
with self.assertRaisesRegex(ValueError, "Exactly one of .* must be specified"):
BlockDev.CryptoKeyslotContext(passphrase=PASSWD, keyfile="keyfile")
class CryptoTestFormat(CryptoTestCase):
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_luks_format(self):
"""Verify that formatting device as LUKS works"""
# the simple case with password
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_format(device=self.loop_devs[0], cipher="aes-xts-plain64",
key_size=0, context=ctx, min_entropy=0,
luks_version=BlockDev.CryptoLUKSVersion.LUKS1,
extra=None)
self.assertTrue(succ)
# just make sure default pbkdf iterations are used with extra=None
_ret, out, err = run_command("cryptsetup luksDump %s" % self.loop_devs[0])
m = re.search(r"MK iterations:\s*(\d+)\s*", out)
if not m or len(m.groups()) != 1:
self.fail("Failed to get pbkdf information from:\n%s %s" % (out, err))
self.assertGreater(int(m.group(1)), 1000)
# create with a keyfile
ctx = BlockDev.CryptoKeyslotContext(keyfile=self.keyfile, keyfile_offset=0, key_size=0)
succ = BlockDev.crypto_luks_format(device=self.loop_devs[0], cipher="aes-xts-plain64",
key_size=0, context=ctx, min_entropy=0,
luks_version=BlockDev.CryptoLUKSVersion.LUKS1,
extra=None)
self.assertTrue(succ)
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_luks2_format(self):
"""Verify that formatting device as LUKS 2 works"""
# the simple case with password
pw_ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_format(self.loop_devs[0], "aes-xts-plain64", 0, pw_ctx, 0)
self.assertTrue(succ)
# create with a keyfile
kf_ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_format(self.loop_devs[0], "aes-xts-plain64", 0, kf_ctx, 0)
self.assertTrue(succ)
# the simple case with password blob
bl_ctx = BlockDev.CryptoKeyslotContext(passphrase=[ord(c) for c in PASSWD])
succ = BlockDev.crypto_luks_format(self.loop_devs[0], "aes-xts-plain64", 0, bl_ctx, 0,
BlockDev.CryptoLUKSVersion.LUKS2, None)
self.assertTrue(succ)
# simple case with extra options
extra = BlockDev.CryptoLUKSExtra(label="blockdevLUKS")
succ = BlockDev.crypto_luks_format(self.loop_devs[0], "aes-xts-plain64", 0, pw_ctx, 0,
BlockDev.CryptoLUKSVersion.LUKS2, extra)
self.assertTrue(succ)
_ret, out, err = run_command("cryptsetup luksDump %s" % self.loop_devs[0])
m = re.search(r"Label:\s*(\S+)\s*", out)
if not m or len(m.groups()) != 1:
self.fail("Failed to get label information from:\n%s %s" % (out, err))
self.assertEqual(m.group(1), "blockdevLUKS")
# different key derivation function
pbkdf = BlockDev.CryptoLUKSPBKDF(type="pbkdf2")
extra = BlockDev.CryptoLUKSExtra(pbkdf=pbkdf)
succ = BlockDev.crypto_luks_format(self.loop_devs[0], "aes-xts-plain64", 0, pw_ctx, 0,
BlockDev.CryptoLUKSVersion.LUKS2, extra)
self.assertTrue(succ)
_ret, out, err = run_command("cryptsetup luksDump %s" % self.loop_devs[0])
m = re.search(r"PBKDF:\s*(\S+)\s*", out)
if not m or len(m.groups()) != 1:
self.fail("Failed to get pbkdf information from:\n%s %s" % (out, err))
self.assertEqual(m.group(1), "pbkdf2")
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_luks1_format_pbkdf_options(self):
"""Verify that formatting device as LUKS 1 with extra PBKDF arguments works"""
# different options for pbkdf2 -- all parameters set
pbkdf = BlockDev.CryptoLUKSPBKDF(type="pbkdf2", iterations=1000)
extra = BlockDev.CryptoLUKSExtra(pbkdf=pbkdf)
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_format(self.loop_devs[0], "aes-xts-plain64", 0, ctx, 0,
BlockDev.CryptoLUKSVersion.LUKS1, extra)
self.assertTrue(succ)
_ret, out, err = run_command("cryptsetup luksDump %s" % self.loop_devs[0])
m = re.search(r"MK iterations:\s*(\d+)\s*", out)
if not m or len(m.groups()) != 1:
self.fail("Failed to get pbkdf information from:\n%s %s" % (out, err))
self.assertEqual(int(m.group(1)), 1000)
# invalid PBKDF
pbkdf = BlockDev.CryptoLUKSPBKDF(type="argon2id")
extra = BlockDev.CryptoLUKSExtra(pbkdf=pbkdf)
with self.assertRaisesRegex(GLib.GError, "Invalid pbkdf specified"):
BlockDev.crypto_luks_format(self.loop_devs[0], "aes-xts-plain64", 0, ctx, 0,
BlockDev.CryptoLUKSVersion.LUKS1, extra)
self.assertTrue(succ)
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_luks2_format_pbkdf_options(self):
"""Verify that formatting device as LUKS 2 works"""
if self._is_fips_enabled():
self.skipTest("FIPS mode is enabled, cannot use argon2, skipping")
# different options for argon2 -- all parameters set
pbkdf = BlockDev.CryptoLUKSPBKDF(type="argon2id", max_memory_kb=100*1024, iterations=10, parallel_threads=1)
extra = BlockDev.CryptoLUKSExtra(pbkdf=pbkdf)
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_format(self.loop_devs[0], "aes-xts-plain64", 0, ctx, 0,
BlockDev.CryptoLUKSVersion.LUKS2, extra)
self.assertTrue(succ)
_ret, out, err = run_command("cryptsetup luksDump %s" % self.loop_devs[0])
m = re.search(r"PBKDF:\s*(\S+)\s*", out)
if not m or len(m.groups()) != 1:
self.fail("Failed to get pbkdf information from:\n%s %s" % (out, err))
self.assertEqual(m.group(1), "argon2id")
m = re.search(r"Memory:\s*(\d+)\s*", out)
if not m or len(m.groups()) != 1:
self.fail("Failed to get pbkdf information from:\n%s %s" % (out, err))
# both iterations and memory is set --> cryptsetup will use exactly max_memory_kb
self.assertEqual(int(m.group(1)), 100*1024)
m = re.search(r"Threads:\s*(\d+)\s*", out)
if not m or len(m.groups()) != 1:
self.fail("Failed to get pbkdf information from:\n%s %s" % (out, err))
self.assertEqual(int(m.group(1)), 1)
m = re.search(r"Time cost:\s*(\d+)\s*", out)
if not m or len(m.groups()) != 1:
self.fail("Failed to get pbkdf information from:\n%s %s" % (out, err))
self.assertEqual(int(m.group(1)), 10)
# different options for argon2 -- only memory set
pbkdf = BlockDev.CryptoLUKSPBKDF(max_memory_kb=100*1024)
extra = BlockDev.CryptoLUKSExtra(pbkdf=pbkdf)
succ = BlockDev.crypto_luks_format(self.loop_devs[0], "aes-xts-plain64", 0, ctx, 0,
BlockDev.CryptoLUKSVersion.LUKS2, extra)
self.assertTrue(succ)
_ret, out, err = run_command("cryptsetup luksDump %s" % self.loop_devs[0])
m = re.search(r"Memory:\s*(\d+)\s*", out)
if not m or len(m.groups()) != 1:
self.fail("Failed to get pbkdf information from:\n%s %s" % (out, err))
# only memory is set -> cryptsetup will run a benchmark and use
# at most max_memory_kb
self.assertLessEqual(int(m.group(1)), 100*1024)
# different options for argon2 -- only miterations set
pbkdf = BlockDev.CryptoLUKSPBKDF(iterations=5)
extra = BlockDev.CryptoLUKSExtra(pbkdf=pbkdf)
succ = BlockDev.crypto_luks_format(self.loop_devs[0], "aes-xts-plain64", 0, ctx, 0,
BlockDev.CryptoLUKSVersion.LUKS2, extra)
self.assertTrue(succ)
_ret, out, err = run_command("cryptsetup luksDump %s" % self.loop_devs[0])
m = re.search(r"Time cost:\s*(\d+)\s*", out)
if not m or len(m.groups()) != 1:
self.fail("Failed to get pbkdf information from:\n%s %s" % (out, err))
self.assertEqual(int(m.group(1)), 5)
def _get_luks1_key_size(self, device):
_ret, out, err = run_command("cryptsetup luksDump %s" % device)
m = re.search(r"MK bits:\s*(\S+)\s*", out)
if not m or len(m.groups()) != 1:
self.fail("Failed to get key size information from:\n%s %s" % (out, err))
key_size = m.group(1)
if not key_size.isnumeric():
self.fail("Failed to get key size information from: %s" % key_size)
return int(key_size)
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_luks_format_key_size(self):
"""Verify that formatting device as LUKS works"""
# aes-xts: key size should default to 512
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_format(self.loop_devs[0], "aes-xts-plain64", 0, ctx, 0)
self.assertTrue(succ)
key_size = self._get_luks1_key_size(self.loop_devs[0])
self.assertEqual(key_size, 512)
# aes-cbc: key size should default to 256
succ = BlockDev.crypto_luks_format(self.loop_devs[0], "aes-cbc-essiv:sha256", 0, ctx, 0)
self.assertTrue(succ)
key_size = self._get_luks1_key_size(self.loop_devs[0])
self.assertEqual(key_size, 256)
# try specifying key size for aes-xts
succ = BlockDev.crypto_luks_format(self.loop_devs[0], "aes-xts-plain64", 256, ctx, 0)
self.assertTrue(succ)
key_size = self._get_luks1_key_size(self.loop_devs[0])
self.assertEqual(key_size, 256)
class CryptoTestResize(CryptoTestCase):
def _get_key_location(self, device):
_ret, out, err = run_command("cryptsetup status %s" % device)
m = re.search(r"\s*key location:\s*(\S+)\s*", out)
if not m or len(m.groups()) != 1:
self.fail("Failed to get key locaton from:\n%s %s" % (out, err))
return m.group(1)
@tag_test(TestTags.SLOW)
def test_luks_resize(self):
"""Verify that resizing LUKS device works"""
# the simple case with password
self._luks_format(self.loop_devs[0], PASSWD, fast_pbkdf=True)
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
# resize to 512 KiB (1024 * 512B sectors)
succ = BlockDev.crypto_luks_resize("libblockdevTestLUKS", 1024)
self.assertTrue(succ)
# resize back to full size
succ = BlockDev.crypto_luks_resize("libblockdevTestLUKS", 0)
self.assertTrue(succ)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
@tag_test(TestTags.SLOW)
def test_luks2_resize(self):
"""Verify that resizing LUKS 2 device works"""
# the simple case with password
self._luks2_format(self.loop_devs[0], PASSWD, self.keyfile, fast_pbkdf=True)
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
# resize without passphrase should fail if key is saved in keyring
if self._get_key_location("libblockdevTestLUKS") == "keyring":
with self.assertRaises(GLib.GError):
BlockDev.crypto_luks_resize("libblockdevTestLUKS", 1024)
# resize to 512 KiB (1024 * 512B sectors)
succ = BlockDev.crypto_luks_resize("libblockdevTestLUKS", 1024, ctx)
self.assertTrue(succ)
# resize back to full size (using the keyfile)
ctx = BlockDev.CryptoKeyslotContext(keyfile=self.keyfile)
succ = BlockDev.crypto_luks_resize("libblockdevTestLUKS", 0, ctx)
self.assertTrue(succ)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
class CryptoTestOpenClose(CryptoTestCase):
def _luks_open_close(self, create_fn):
"""Verify that opening/closing LUKS device works"""
create_fn(self.loop_devs[0], PASSWD, self.keyfile, fast_pbkdf=True)
with self.assertRaises(GLib.GError):
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
BlockDev.crypto_luks_open("/non/existing/device", "libblockdevTestLUKS", ctx, False)
with self.assertRaisesRegex(GLib.GError, r"Device name cannot contain '/' character"):
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdev/TestLUKS", ctx, False)
with self.assertRaisesRegex(GLib.GError, r"Incorrect passphrase"):
ctx = BlockDev.CryptoKeyslotContext(passphrase="wrong-passphrase")
BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
with self.assertRaises(GLib.GError):
ctx = BlockDev.CryptoKeyslotContext(keyfile="wrong-keyfile")
BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
with self.assertRaisesRegex(GLib.GError, "Only .* context types are valid for LUKS open"):
ctx = BlockDev.CryptoKeyslotContext(volume_key=list(secrets.token_bytes(64)))
BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
# use the full /dev/mapper/ path
succ = BlockDev.crypto_luks_close("/dev/mapper/libblockdevTestLUKS")
self.assertTrue(succ)
ctx = BlockDev.CryptoKeyslotContext(keyfile=self.keyfile)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
# use just the LUKS device name
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
ctx = BlockDev.CryptoKeyslotContext(passphrase=[ord(c) for c in PASSWD])
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
succ = BlockDev.crypto_luks_close("/dev/mapper/libblockdevTestLUKS")
self.assertTrue(succ)
# add the passphrase to kernel keyring and try to open with it
succ = BlockDev.crypto_keyring_add_key("myshinylittlekey", [ord(c) for c in PASSWD])
self.assertTrue(succ)
ctx = BlockDev.CryptoKeyslotContext(keyring="myshinylittlekey")
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx)
self.assertTrue(succ)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_luks_open_close(self):
self._luks_open_close(self._luks_format)
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_luks2_open_close(self):
self._luks_open_close(self._luks2_format)
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_luks2_open_close_non_ascii_passphrase(self):
passphrase = "šššššššš"
self._luks2_format(self.loop_devs[0], passphrase, fast_pbkdf=True)
ctx = BlockDev.CryptoKeyslotContext(passphrase=passphrase)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
# lets try with keyfile
with tempfile.NamedTemporaryFile(mode="w") as f:
f.write(passphrase)
f.flush()
ctx = BlockDev.CryptoKeyslotContext(keyfile=f.name)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
# and keyring too
succ = BlockDev.crypto_keyring_add_key("myshinylittlekey", passphrase)
self.assertTrue(succ)
ctx = BlockDev.CryptoKeyslotContext(keyring="myshinylittlekey")
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx)
self.assertTrue(succ)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
class CryptoTestAddRemoveKey(CryptoTestCase):
def _remove_key(self, create_fn):
"""Verify that adding/removing key to/from LUKS device works"""
create_fn(self.loop_devs[0], PASSWD, None, fast_pbkdf=True)
# add key, wrong passphrase
with self.assertRaises(GLib.GError):
ctx = BlockDev.CryptoKeyslotContext(passphrase="wrong-passphrase")
nctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD2)
BlockDev.crypto_luks_add_key(self.loop_devs[0], ctx, nctx)
# add key, correct passphrase
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
nctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD2)
succ = BlockDev.crypto_luks_add_key(self.loop_devs[0], ctx, nctx)
self.assertTrue(succ)
nctx2 = BlockDev.CryptoKeyslotContext(passphrase=PASSWD3)
succ = BlockDev.crypto_luks_add_key(self.loop_devs[0], ctx, nctx2)
self.assertTrue(succ)
nctx3 = BlockDev.CryptoKeyslotContext(keyfile=self.keyfile)
succ = BlockDev.crypto_luks_add_key(self.loop_devs[0], ctx, nctx3)
# remove key, wrong passphrase
with self.assertRaises(GLib.GError):
wctx = BlockDev.CryptoKeyslotContext(passphrase="wrong-passphrase")
BlockDev.crypto_luks_remove_key(self.loop_devs[0], wctx)
# remove key, correct passphrase
succ = BlockDev.crypto_luks_remove_key(self.loop_devs[0], ctx)
self.assertTrue(succ)
succ = BlockDev.crypto_luks_remove_key(self.loop_devs[0], nctx2)
self.assertTrue(succ)
succ = BlockDev.crypto_luks_remove_key(self.loop_devs[0], nctx3)
self.assertTrue(succ)
@tag_test(TestTags.SLOW)
def test_luks_remove_key(self):
self._remove_key(self._luks_format)
@tag_test(TestTags.SLOW)
def test_luks2_remove_key(self):
self._remove_key(self._luks2_format)
class CryptoTestErrorLocale(CryptoTestCase):
def setUp(self):
self._orig_loc = None
CryptoTestCase.setUp(self)
self._orig_loc = ".".join(locale.getdefaultlocale())
def _clean_up(self):
CryptoTestCase._clean_up(self)
if self._orig_loc:
locale.setlocale(locale.LC_ALL, self._orig_loc)
@tag_test(TestTags.SLOW)
@requires_locales({"cs_CZ.UTF-8"})
def test_error_locale_key(self):
"""Verify that the error msg is locale agnostic"""
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_format(self.loop_devs[0], None, 0, ctx, 0)
self.assertTrue(succ)
locale.setlocale(locale.LC_ALL, "cs_CZ.UTF-8")
try:
ctx = BlockDev.CryptoKeyslotContext(passphrase="wrong-passphrase")
BlockDev.crypto_luks_remove_key(self.loop_devs[0], ctx)
except GLib.GError as e:
self.assertIn("Operation not permitted", str(e))
class CryptoTestChangeKey(CryptoTestCase):
def _change_key(self, create_fn):
"""Verify that changing key in LUKS device works"""
create_fn(self.loop_devs[0], PASSWD, None, fast_pbkdf=True)
with self.assertRaisesRegex(GLib.GError, r"No keyslot with given passphrase found."):
ctx = BlockDev.CryptoKeyslotContext(passphrase="wrong-passphrase")
nctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD2)
BlockDev.crypto_luks_change_key(self.loop_devs[0], ctx, nctx)
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
nctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD2)
succ = BlockDev.crypto_luks_change_key(self.loop_devs[0], ctx, nctx)
self.assertTrue(succ)
@tag_test(TestTags.SLOW)
def test_luks_change_key(self):
self._change_key(self._luks_format)
@tag_test(TestTags.SLOW)
def test_luks2_change_key(self):
self._change_key(self._luks2_format)
class CryptoTestLuksStatus(CryptoTestCase):
def _luks_status(self, create_fn):
"""Verify that LUKS device status reporting works"""
with self.assertRaises(GLib.GError):
BlockDev.crypto_luks_status("/non/existing/device")
create_fn(self.loop_devs[0], PASSWD, None, fast_pbkdf=True)
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
# use the full /dev/mapper path
status = BlockDev.crypto_luks_status("/dev/mapper/libblockdevTestLUKS")
self.assertEqual(status, "active")
# use just the LUKS device name
status = BlockDev.crypto_luks_status("libblockdevTestLUKS")
self.assertEqual(status, "active")
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
with self.assertRaises(GLib.GError):
BlockDev.crypto_luks_status("libblockdevTestLUKS")
@tag_test(TestTags.SLOW)
def test_luks_status(self):
self._luks_status(self._luks_format)
@tag_test(TestTags.SLOW)
def test_luks2_status(self):
self._luks_status(self._luks2_format)
class CryptoTestLuksOpenRW(CryptoTestCase):
def _luks_open_rw(self, create_fn):
"""Verify that a LUKS device can be activated as RW as well as RO"""
create_fn(self.loop_devs[0], PASSWD, None, fast_pbkdf=True)
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
# tests that we can write something to the raw LUKS device
succ = BlockDev.utils_exec_and_report_error(["dd", "if=/dev/zero", "of=/dev/mapper/libblockdevTestLUKS", "bs=1M", "count=1"])
self.assertTrue(succ)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
# now try the same with LUKS device opened as RO
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, True)
self.assertTrue(succ)
# tests that we can write something to the raw LUKS device
with self.assertRaises(GLib.GError):
BlockDev.utils_exec_and_report_error(["dd", "if=/dev/zero", "of=/dev/mapper/libblockdevTestLUKS", "bs=1M", "count=1"])
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
@tag_test(TestTags.SLOW)
def test_luks_open_rw(self):
self._luks_open_rw(self._luks_format)
@tag_test(TestTags.SLOW)
def test_luks2_open_rw(self):
self._luks_open_rw(self._luks2_format)
class CryptoTestEscrow(CryptoTestCase):
def setUp(self):
# I am not able to generate a self-signed certificate that would work in FIPS
# so let's just skip this for now
if self._is_fips_enabled():
self.skipTest("Skipping escrow tests in FIPS mode")
super(CryptoTestEscrow, self).setUp()
# Create the certificate used to encrypt the escrow packet and backup passphrase.
# volume_key requires a nss database directory to decrypt any of the
# packet files, and python-nss is python2 only, just do everything with
# shell commands.
self.nss_dir = tempfile.mkdtemp(prefix='libblockdev_test_escrow')
self.addCleanup(shutil.rmtree, self.nss_dir)
subprocess.check_call(['certutil', '-d', self.nss_dir, '--empty-password', '-N'])
# Gather some entropy to keep certutil from asking for input
with tempfile.NamedTemporaryFile() as noise_file:
noise_file.write(os.urandom(20))
noise_file.flush()
subprocess.check_call(['certutil', '-d', self.nss_dir, '-S', '-x', '-n',
'escrow_cert', '-s', 'CN=Escrow Test', '-t', ',,TC', '-z',
noise_file.name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Export the public certificate
handle, self.public_cert = tempfile.mkstemp(prefix='libblockdev_test_escrow')
os.close(handle)
subprocess.check_call(['certutil', '-d', self.nss_dir, '-L', '-n', 'escrow_cert',
'-a', '-o', self.public_cert])
self.addCleanup(os.unlink, self.public_cert)
@tag_test(TestTags.SLOW)
def test_escrow_packet(self):
"""Verify that an escrow packet can be created for a device"""
self._luks_format(self.loop_devs[0], PASSWD, fast_pbkdf=True)
escrow_dir = tempfile.mkdtemp(prefix='libblockdev_test_escrow')
self.addCleanup(shutil.rmtree, escrow_dir)
with open(self.public_cert, 'rb') as cert_file:
succ = BlockDev.crypto_escrow_device(self.loop_devs[0], PASSWD, cert_file.read(),
escrow_dir, None)
self.assertTrue(succ)
# Find the escrow packet
info = BlockDev.crypto_luks_info(self.loop_devs[0])
escrow_packet_file = '%s/%s-escrow' % (escrow_dir, info.uuid)
self.assertTrue(os.path.isfile(escrow_packet_file))
# Use the volume_key utility (see note in setUp about why not python)
# to decrypt the escrow packet and restore access to the volume under
# a new passphrase
# Just use the existing temp directory to output the re-encrypted packet
# PASSWD2 is the passphrase of the new escrow packet
p = subprocess.Popen(['volume_key', '--reencrypt', '-b', '-d', self.nss_dir,
escrow_packet_file, '-o', '%s/escrow-out' % escrow_dir],
stdin=subprocess.PIPE)
p.communicate(input=('%s\0%s\0' % (PASSWD2, PASSWD2)).encode('utf-8'))
if p.returncode != 0:
raise subprocess.CalledProcessError(p.returncode, 'volume_key')
# Restore access to the volume
# PASSWD3 is the new passphrase for the LUKS device
p = subprocess.Popen(['volume_key', '--restore', '-b', self.loop_devs[0],
'%s/escrow-out' % escrow_dir], stdin=subprocess.PIPE)
p.communicate(input=('%s\0%s\0%s\0' % (PASSWD2, PASSWD3, PASSWD3)).encode('utf-8'))
if p.returncode != 0:
raise subprocess.CalledProcessError(p.returncode, 'volume_key')
# Open the volume with the new passphrase
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD3)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], 'libblockdevTestLUKS', ctx)
self.assertTrue(succ)
@tag_test(TestTags.SLOW)
def test_backup_passphrase(self):
"""Verify that a backup passphrase can be created for a device"""
self._luks_format(self.loop_devs[0], PASSWD, fast_pbkdf=True)
escrow_dir = tempfile.mkdtemp(prefix='libblockdev_test_escrow')
self.addCleanup(shutil.rmtree, escrow_dir)
backup_passphrase = BlockDev.crypto_generate_backup_passphrase()
with open(self.public_cert, 'rb') as cert_file:
succ = BlockDev.crypto_escrow_device(self.loop_devs[0], PASSWD, cert_file.read(),
escrow_dir, backup_passphrase)
self.assertTrue(succ)
# Find the backup passphrase
info = BlockDev.crypto_luks_info(self.loop_devs[0])
escrow_backup_passphrase = "%s/%s-escrow-backup-passphrase" % (escrow_dir, info.uuid)
self.assertTrue(os.path.isfile(escrow_backup_passphrase))
# Check that the encrypted file contains what we put in
env = {k: v for k, v in os.environ.items()}
env.update({"LC_ALL": "C"})
passphrase = subprocess.check_output(
['volume_key', '--secrets', '-d', self.nss_dir, escrow_backup_passphrase],
env=env)
passphrase = passphrase.strip().split()[1].decode('ascii')
self.assertEqual(passphrase, backup_passphrase)
# Check that the backup passphrase works
ctx = BlockDev.CryptoKeyslotContext(passphrase=backup_passphrase)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], 'libblockdevTestLUKS', ctx)
self.assertTrue(succ)
class CryptoTestSuspendResume(CryptoTestCase):
def _luks_suspend_resume(self, create_fn):
create_fn(self.loop_devs[0], PASSWD, self.keyfile, fast_pbkdf=True)
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx)
self.assertTrue(succ)
with self.assertRaises(GLib.GError):
BlockDev.crypto_luks_suspend("/non/existing/device")
# use the full /dev/mapper/ path
succ = BlockDev.crypto_luks_suspend("/dev/mapper/libblockdevTestLUKS")
self.assertTrue(succ)
_ret, state, _err = run_command("lsblk -oSTATE -n /dev/mapper/libblockdevTestLUKS")
self.assertEqual(state, "suspended")
with self.assertRaises(GLib.GError):
ctx = BlockDev.CryptoKeyslotContext(passphrase="wrong-passphrase")
BlockDev.crypto_luks_resume("libblockdevTestLUKS", ctx)
with self.assertRaises(GLib.GError):
ctx = BlockDev.CryptoKeyslotContext(keyfile="wrong-keyfile")
BlockDev.crypto_luks_resume("libblockdevTestLUKS", ctx)
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_resume("libblockdevTestLUKS", ctx)
self.assertTrue(succ)
succ = BlockDev.crypto_luks_suspend("/dev/mapper/libblockdevTestLUKS")
self.assertTrue(succ)
ctx = BlockDev.CryptoKeyslotContext(passphrase=[ord(c) for c in PASSWD])
succ = BlockDev.crypto_luks_resume("libblockdevTestLUKS", ctx)
self.assertTrue(succ)
_ret, state, _err = run_command("lsblk -oSTATE -n /dev/mapper/libblockdevTestLUKS")
self.assertEqual(state, "running")
# use just the LUKS device name
succ = BlockDev.crypto_luks_suspend("libblockdevTestLUKS")
self.assertTrue(succ)
_ret, state, _err = run_command("lsblk -oSTATE -n /dev/mapper/libblockdevTestLUKS")
self.assertEqual(state, "suspended")
ctx = BlockDev.CryptoKeyslotContext(keyfile=self.keyfile)
succ = BlockDev.crypto_luks_resume("libblockdevTestLUKS", ctx)
self.assertTrue(succ)
_ret, state, _err = run_command("lsblk -oSTATE -n /dev/mapper/libblockdevTestLUKS")
self.assertEqual(state, "running")
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
@tag_test(TestTags.SLOW)
def test_luks_suspend_resume(self):
"""Verify that suspending/resuming LUKS device works"""
self._luks_suspend_resume(self._luks_format)
@tag_test(TestTags.SLOW)
def test_luks2_suspend_resume(self):
"""Verify that suspending/resuming LUKS 2 device works"""
self._luks_suspend_resume(self._luks2_format)
class CryptoTestKillSlot(CryptoTestCase):
def _luks_kill_slot(self, create_fn):
create_fn(self.loop_devs[0], PASSWD, None, fast_pbkdf=True)
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
nctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD2)
succ = BlockDev.crypto_luks_add_key(self.loop_devs[0], ctx, nctx)
self.assertTrue(succ)
with self.assertRaises(GLib.GError):
BlockDev.crypto_luks_kill_slot("/non/existing/device", -1)
# invalid slot
with self.assertRaises(GLib.GError):
BlockDev.crypto_luks_kill_slot(self.loop_devs[0], -1)
# unused slot
with self.assertRaises(GLib.GError):
BlockDev.crypto_luks_kill_slot(self.loop_devs[0], 2)
# destroy second keyslot
succ = BlockDev.crypto_luks_kill_slot(self.loop_devs[0], 1)
self.assertTrue(succ)
# opening with the second passphrase should fail
with self.assertRaises(GLib.GError):
BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", nctx)
# opening with passphrase should still work
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx)
self.assertTrue(succ)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
@tag_test(TestTags.SLOW)
def test_luks_kill_slot(self):
"""Verify that killing a key slot on LUKS device works"""
self._luks_kill_slot(self._luks_format)
@tag_test(TestTags.SLOW)
def test_luks2_kill_slot(self):
"""Verify that killing a key slot on LUKS 2 device works"""
self._luks_kill_slot(self._luks2_format)
class CryptoTestHeaderBackupRestore(CryptoTestCase):
def setUp(self):
super(CryptoTestHeaderBackupRestore, self).setUp()
self.backup_dir = tempfile.mkdtemp(prefix='libblockdev_test_header')
self.addCleanup(shutil.rmtree, self.backup_dir)
def _luks_header_backup_restore(self, create_fn):
create_fn(self.loop_devs[0], PASSWD, None, fast_pbkdf=True)
backup_file = os.path.join(self.backup_dir, "luks-header.txt")
succ = BlockDev.crypto_luks_header_backup(self.loop_devs[0], backup_file)
self.assertTrue(succ)
self.assertTrue(os.path.isfile(backup_file))
# now completely destroy the luks header
ret, out, err = run_command("cryptsetup erase %s -q && wipefs -a %s" % (self.loop_devs[0], self.loop_devs[0]))
if ret != 0:
self.fail("Failed to erase LUKS header from %s:\n%s %s" % (self.loop_devs[0], out, err))
_ret, fstype, _err = run_command("blkid -p -ovalue -sTYPE %s" % self.loop_devs[0])
self.assertFalse(fstype) # false == empty
# header is destroyed, should not be possible to open
with self.assertRaises(GLib.GError):
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx)
# and restore the header back
succ = BlockDev.crypto_luks_header_restore(self.loop_devs[0], backup_file)
self.assertTrue(succ)
_ret, fstype, _err = run_command("blkid -p -ovalue -sTYPE %s" % self.loop_devs[0])
self.assertEqual(fstype, "crypto_LUKS")
# opening should now work
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx)
self.assertTrue(succ)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
@tag_test(TestTags.SLOW)
def test_luks_header_backup_restore(self):
"""Verify that header backup/restore with LUKS works"""
self._luks_header_backup_restore(self._luks_format)
@tag_test(TestTags.SLOW)
def test_luks2_header_backup_restore(self):
"""Verify that header backup/restore with LUKS2 works"""
self._luks_header_backup_restore(self._luks2_format)
class CryptoTestInfo(CryptoTestCase):
_num_devices = 2
def _verify_luks_info(self, info, version):
self.assertIsNotNone(info)
self.assertEqual(info.version, version)
self.assertEqual(info.cipher, "aes")
self.assertEqual(info.mode, "cbc-essiv:sha256")
self.assertEqual(info.backing_device, self.loop_devs[0])
_ret, uuid, _err = run_command("blkid -p -ovalue -sUUID %s" % self.loop_devs[0])
self.assertEqual(info.uuid, uuid)
ret, out, err = run_command("cryptsetup luksDump %s" % self.loop_devs[0])
if ret != 0:
self.fail("Failed to get LUKS header from %s:\n%s %s" % (self.loop_devs[0], out, err))
if version == BlockDev.CryptoLUKSVersion.LUKS1:
m = re.search(r"Payload offset:\s*([0-9]+)", out)
if m is None:
self.fail("Failed to get LUKS offset information from %s:\n%s %s" % (self.loop_devs[0], out, err))
offset = int(m.group(1)) * 512
else:
m = re.search(r"offset:\s*([0-9]+)\s*\[bytes\]", out)
if m is None:
self.fail("Failed to get LUKS 2 offset information from %s:\n%s %s" % (self.loop_devs[0], out, err))
offset = int(m.group(1))
self.assertEqual(info.metadata_size, offset)
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_luks_info(self):
"""Verify that we can get information about a LUKS device"""
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_format(self.loop_devs[0], "aes-cbc-essiv:sha256", 256, ctx, 0)
self.assertTrue(succ)
info = BlockDev.crypto_luks_info(self.loop_devs[0])
self._verify_luks_info(info, BlockDev.CryptoLUKSVersion.LUKS1)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
info = BlockDev.crypto_luks_info("libblockdevTestLUKS")
self._verify_luks_info(info, BlockDev.CryptoLUKSVersion.LUKS1)
info = BlockDev.crypto_luks_info("/dev/mapper/libblockdevTestLUKS")
self._verify_luks_info(info, BlockDev.CryptoLUKSVersion.LUKS1)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
# test the crypto_device_is_luks function too
is_luks = BlockDev.crypto_device_is_luks(self.loop_devs[0])
self.assertTrue(is_luks)
is_luks = BlockDev.crypto_device_is_luks(self.loop_devs[1])
self.assertFalse(is_luks)
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_luks2_info(self):
"""Verify that we can get information about a LUKS 2 device"""
extra = BlockDev.CryptoLUKSExtra()
extra.sector_size = 4096
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_format(self.loop_devs[0], "aes-cbc-essiv:sha256", 256, ctx, 0,
BlockDev.CryptoLUKSVersion.LUKS2, extra)
self.assertTrue(succ)
info = BlockDev.crypto_luks_info(self.loop_devs[0])
self._verify_luks_info(info, BlockDev.CryptoLUKSVersion.LUKS2)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
info = BlockDev.crypto_luks_info("libblockdevTestLUKS")
self._verify_luks_info(info, BlockDev.CryptoLUKSVersion.LUKS2)
info = BlockDev.crypto_luks_info("/dev/mapper/libblockdevTestLUKS")
self._verify_luks_info(info, BlockDev.CryptoLUKSVersion.LUKS2)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
# test the crypto_device_is_luks function too
is_luks = BlockDev.crypto_device_is_luks(self.loop_devs[0])
self.assertTrue(is_luks)
is_luks = BlockDev.crypto_device_is_luks(self.loop_devs[1])
self.assertFalse(is_luks)
class CryptoTestSetLabelUuid(CryptoTestCase):
label = "aaaaaa"
subsystem = "bbbbbb"
test_uuid = "4d7086c4-a4d3-432f-819e-73da03870df9"
def _test_set_label(self):
succ = BlockDev.crypto_luks_set_label(self.loop_devs[0], self.label, self.subsystem)
self.assertTrue(succ)
info = BlockDev.crypto_luks_info(self.loop_devs[0])
self.assertIsNotNone(info)
self.assertEqual(info.label, self.label)
self.assertEqual(info.subsystem, self.subsystem)
_ret, label, _err = run_command("blkid -p -ovalue -sLABEL %s" % self.loop_devs[0])
self.assertEqual(label, self.label)
_ret, subsystem, _err = run_command("blkid -p -ovalue -sSUBSYSTEM %s" % self.loop_devs[0])
self.assertEqual(subsystem, self.subsystem)
succ = BlockDev.crypto_luks_set_label(self.loop_devs[0], None, None)
self.assertTrue(succ)
info = BlockDev.crypto_luks_info(self.loop_devs[0])
self.assertIsNotNone(info)
self.assertEqual(info.label, "")
self.assertEqual(info.subsystem, "")
_ret, label, _err = run_command("blkid -p -ovalue -sLABEL %s" % self.loop_devs[0])
self.assertEqual(label, "")
_ret, subsystem, _err = run_command("blkid -p -ovalue -sSUBSYSTEM %s" % self.loop_devs[0])
self.assertEqual(subsystem, "")
def _test_set_uuid(self):
succ = BlockDev.crypto_luks_set_uuid(self.loop_devs[0], self.test_uuid)
self.assertTrue(succ)
info = BlockDev.crypto_luks_info(self.loop_devs[0])
self.assertIsNotNone(info)
self.assertEqual(info.uuid, self.test_uuid)
succ = BlockDev.crypto_luks_set_uuid(self.loop_devs[0], None)
self.assertTrue(succ)
info = BlockDev.crypto_luks_info(self.loop_devs[0])
self.assertIsNotNone(info)
self.assertNotEqual(info.uuid, self.test_uuid)
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_luks_set_label_uuid(self):
"""Verify that we can set label and UUID on a LUKS device"""
self._luks_format(self.loop_devs[0], PASSWD, fast_pbkdf=True)
# setting label is not supported on LUKS1
with self.assertRaisesRegex(GLib.GError, r"Label can be set only on LUKS 2"):
BlockDev.crypto_luks_set_label(self.loop_devs[0], self.label, self.subsystem)
info = BlockDev.crypto_luks_info(self.loop_devs[0])
self.assertIsNotNone(info)
self.assertEqual(info.label, "")
self.assertEqual(info.subsystem, "")
# setting UUID is supported on LUKS1
self._test_set_uuid()
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_luks2_set_label_uuid(self):
"""Verify that we can set label and UUID on a LUKS 2 device"""
self._luks2_format(self.loop_devs[0], PASSWD, fast_pbkdf=True)
self._test_set_label()
self._test_set_uuid()
class CryptoTestSetPersistentFlags(CryptoTestCase):
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_luks_set_persistent_flags(self):
"""Verify that we can set flags on a LUKS device"""
self._luks_format(self.loop_devs[0], PASSWD, fast_pbkdf=True)
with self.assertRaisesRegex(GLib.GError, "Persistent flags can be set only on LUKS v2"):
BlockDev.crypto_luks_set_persistent_flags(self.loop_devs[0],
BlockDev.CryptoLUKSPersistentFlags.ALLOW_DISCARDS)
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_luks2_set_persistent_flags(self):
"""Verify that we can set flags on a LUKS 2 device"""
self._luks2_format(self.loop_devs[0], PASSWD, fast_pbkdf=True)
succ = BlockDev.crypto_luks_set_persistent_flags(self.loop_devs[0],
BlockDev.CryptoLUKSPersistentFlags.ALLOW_DISCARDS)
self.assertTrue(succ)
_ret, out, err = run_command("cryptsetup luksDump %s" % self.loop_devs[0])
m = re.search(r"Flags:\s*(\S+)\s*", out)
if not m or len(m.groups()) != 1:
self.fail("Failed to get label information from:\n%s %s" % (out, err))
self.assertEqual(m.group(1), "allow-discards")
class CryptoTestConvert(CryptoTestCase):
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_convert_luks1_to_luks2(self):
"""Verify that we can convert a device from LUKS1 format to LUKS2"""
self._luks_format(self.loop_devs[0], PASSWD, luks_version=BlockDev.CryptoLUKSVersion.LUKS1,
fast_pbkdf=True)
succ = BlockDev.crypto_luks_convert(self.loop_devs[0], BlockDev.CryptoLUKSVersion.LUKS2)
self.assertTrue(succ)
info = BlockDev.crypto_luks_info(self.loop_devs[0])
self.assertIsNotNone(info)
self.assertEqual(info.version, BlockDev.CryptoLUKSVersion.LUKS2)
@tag_test(TestTags.SLOW, TestTags.CORE)
def test_convert_luks1_to_luks2_to_luks1(self):
"""Verify that we can convert a device from LUKS1 format to LUKS2 and back to LUKS1"""
self._luks_format(self.loop_devs[0], PASSWD, luks_version=BlockDev.CryptoLUKSVersion.LUKS1,
fast_pbkdf=True)
# LUKS1 -> LUKS2
succ = BlockDev.crypto_luks_convert(self.loop_devs[0], BlockDev.CryptoLUKSVersion.LUKS2)
self.assertTrue(succ)
info = BlockDev.crypto_luks_info(self.loop_devs[0])
self.assertIsNotNone(info)
self.assertEqual(info.version, BlockDev.CryptoLUKSVersion.LUKS2)
# LUKS2 -> LUKS2 (fail)
with self.assertRaisesRegex(GLib.GError, r"Conversion to the LUKS2 type was requested, but device .* is "
r"already of type: LUKS2"):
BlockDev.crypto_luks_convert(self.loop_devs[0], BlockDev.CryptoLUKSVersion.LUKS2)
info = BlockDev.crypto_luks_info(self.loop_devs[0])
self.assertIsNotNone(info)
self.assertEqual(info.version, BlockDev.CryptoLUKSVersion.LUKS2)
# LUKS2 -> LUKS1
succ = BlockDev.crypto_luks_convert(self.loop_devs[0], BlockDev.CryptoLUKSVersion.LUKS1)
self.assertTrue(succ)
info = BlockDev.crypto_luks_info(self.loop_devs[0])
self.assertIsNotNone(info)
self.assertEqual(info.version, BlockDev.CryptoLUKSVersion.LUKS1)
class CryptoTestLuksSectorSize(CryptoTestCase):
_num_devices = 2
def setUp(self):
if not check_cryptsetup_version("2.4.0"):
self.skipTest("cryptsetup encryption sector size not available, skipping.")
# we need special loop devices for this test case
self.addCleanup(self._clean_up)
self.dev_files.append(create_sparse_tempfile("crypto_test", self._sparse_size))
self.dev_files.append(create_sparse_tempfile("crypto_test", self._sparse_size))
# create a 4k sector loop device
succ, loop = BlockDev.loop_setup(self.dev_files[0], sector_size=4096)
if not succ:
raise RuntimeError("Failed to setup loop device for testing")
self.loop_devs.append("/dev/%s" % loop)
succ, loop = BlockDev.loop_setup(self.dev_files[1])
if not succ:
raise RuntimeError("Failed to setup loop device for testing")
self.loop_devs.append("/dev/%s" % loop)
def _clean_up(self):
try:
BlockDev.crypto_luks_close("libblockdevTestLUKS")
except:
pass
for i in range(self._num_devices):
BlockDev.loop_teardown(self.loop_devs[i])
os.unlink(self.dev_files[i])
self.dev_files.clear()
self.loop_devs.clear()
@tag_test(TestTags.SLOW)
def test_luks2_sector_size_autodetect(self):
"""Verify that we can autodetect 4k drives and set 4k sector size for them"""
# format the 4k loop device, encryption sector size should default to 4096
self._luks2_format(self.loop_devs[0], PASSWD, fast_pbkdf=True)
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
info = BlockDev.crypto_luks_info("libblockdevTestLUKS")
self.assertIsNotNone(info)
self.assertEqual(info.version, BlockDev.CryptoLUKSVersion.LUKS2)
self.assertEqual(info.sector_size, 4096)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
# with the 512 loop device, we should still get 512
self._luks2_format(self.loop_devs[1], PASSWD, fast_pbkdf=True)
succ = BlockDev.crypto_luks_open(self.loop_devs[1], "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
info = BlockDev.crypto_luks_info("libblockdevTestLUKS")
self.assertIsNotNone(info)
self.assertEqual(info.version, BlockDev.CryptoLUKSVersion.LUKS2)
self.assertEqual(info.sector_size, 512)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
class CryptoTestLUKS2Integrity(CryptoTestCase):
@tag_test(TestTags.SLOW)
def test_luks2_integrity(self):
"""Verify that we can get create a LUKS 2 device with integrity"""
if not BlockDev.utils_have_kernel_module("dm-integrity"):
self.skipTest('dm-integrity kernel module not available, skipping.')
extra = BlockDev.CryptoLUKSExtra()
extra.integrity = "hmac(sha256)"
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_format(self.loop_devs[0], "aes-cbc-essiv:sha256", 512, ctx, 0,
BlockDev.CryptoLUKSVersion.LUKS2, extra)
self.assertTrue(succ)
info = BlockDev.crypto_integrity_info(self.loop_devs[0])
self.assertIsNotNone(info)
self.assertEqual(info.algorithm, "hmac(sha256)")
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
info = BlockDev.crypto_integrity_info("libblockdevTestLUKS")
self.assertIsNotNone(info)
self.assertEqual(info.algorithm, "hmac(sha256)")
info = BlockDev.crypto_integrity_info("/dev/mapper/libblockdevTestLUKS")
self.assertIsNotNone(info)
self.assertEqual(info.algorithm, "hmac(sha256)")
# get integrity device dm name
_ret, int_name, _err = run_command('ls /sys/block/%s/holders/' % self.loop_devs[0].split("/")[-1])
self.assertTrue(int_name) # true == not empty
tag_size = read_file("/sys/block/%s/integrity/tag_size" % int_name)
self.assertEqual(info.tag_size, int(tag_size))
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
class CryptoTestLUKSToken(CryptoTestCase):
def _verify_token_info (self, info):
self.assertEqual(len(info), 1)
self.assertEqual(info[0].id, 0)
self.assertEqual(info[0].type, "luks2-keyring")
self.assertEqual(info[0].keyslot, 0)
@tag_test(TestTags.SLOW)
def test_luks2_integrity(self):
"""Verify that we can get information about LUKS2 tokens"""
# the simple case with password
self._luks2_format(self.loop_devs[0], PASSWD, None, fast_pbkdf=True)
info = BlockDev.crypto_luks_token_info(self.loop_devs[0])
self.assertListEqual(info, [])
# add kernel keyring token using cryptsetup
ret, _out, err = run_command("cryptsetup token add --key-description aaaa %s" % self.loop_devs[0])
self.assertEqual(ret, 0, msg="Failed to add token to %s: %s" % (self.loop_devs[0], err))
info = BlockDev.crypto_luks_token_info(self.loop_devs[0])
self._verify_token_info(info)
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD)
succ = BlockDev.crypto_luks_open(self.loop_devs[0], "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
info = BlockDev.crypto_luks_token_info("libblockdevTestLUKS")
self._verify_token_info(info)
info = BlockDev.crypto_luks_token_info("/dev/mapper/libblockdevTestLUKS")
self._verify_token_info(info)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
class CryptoTestTrueCrypt(CryptoTestCase):
# we can't create TrueCrypt/VeraCrypt formats using libblockdev
# so we are using these images from cryptsetup test suite
# https://gitlab.com/cryptsetup/cryptsetup/blob/master/tests/tcrypt-images.tar.bz2
tc_img = "tc-sha512-xts-aes"
vc_img = "vc-sha512-xts-aes"
passphrase = "aaaaaaaaaaaa"
tempdir = None
@classmethod
def setUpClass(cls):
super(CryptoTestTrueCrypt, cls).setUpClass()
cls.tempdir = tempfile.mkdtemp(prefix="bd_test_tcrypt")
images = os.path.join(os.path.dirname(__file__), "truecrypt-images.tar.gz")
with tarfile.open(images, "r") as tar:
tar.extractall(cls.tempdir)
@classmethod
def tearDownClass(cls):
super(CryptoTestTrueCrypt, cls).tearDownClass()
shutil.rmtree(cls.tempdir)
def setUp(self):
self.addCleanup(self._clean_up)
succ, loop = BlockDev.loop_setup(os.path.join(self.tempdir, self.tc_img))
if not succ:
raise RuntimeError("Failed to setup loop device for testing")
self.tc_dev = "/dev/%s" % loop
succ, loop = BlockDev.loop_setup(os.path.join(self.tempdir, self.vc_img))
if not succ:
raise RuntimeError("Failed to setup loop device for testing")
self.vc_dev = "/dev/%s" % loop
def _clean_up(self):
try:
BlockDev.crypto_tc_close("libblockdevTestTC")
except:
pass
succ = BlockDev.loop_teardown(self.tc_dev)
if not succ:
raise RuntimeError("Failed to tear down loop device used for testing")
succ = BlockDev.loop_teardown(self.vc_dev)
if not succ:
raise RuntimeError("Failed to tear down loop device used for testing")
@tag_test(TestTags.NOSTORAGE)
def test_truecrypt_open_close(self):
"""Verify that opening/closing TrueCrypt device works"""
with self.assertRaises(GLib.GError):
ctx = BlockDev.CryptoKeyslotContext(passphrase=self.passphrase)
BlockDev.crypto_tc_open("/non/existing/device", "libblockdevTestTC", ctx)
with self.assertRaises(GLib.GError):
ctx = BlockDev.CryptoKeyslotContext(passphrase="wrong-passphrase")
BlockDev.crypto_tc_open(self.tc_dev, "libblockdevTestTC", ctx)
ctx = BlockDev.CryptoKeyslotContext(passphrase=self.passphrase)
succ = BlockDev.crypto_tc_open(self.tc_dev, "libblockdevTestTC", ctx)
self.assertTrue(succ)
self.assertTrue(os.path.exists("/dev/mapper/libblockdevTestTC"))
succ = BlockDev.crypto_tc_close("libblockdevTestTC")
self.assertTrue(succ)
self.assertFalse(os.path.exists("/dev/mapper/libblockdevTestTC"))
@tag_test(TestTags.NOSTORAGE)
def test_veracrypt_open_close(self):
"""Verify that opening/closing VeraCrypt device works"""
with self.assertRaises(GLib.GError):
ctx = BlockDev.CryptoKeyslotContext(passphrase=self.passphrase)
BlockDev.crypto_tc_open("/non/existing/device", "libblockdevTestTC", ctx)
with self.assertRaises(GLib.GError):
ctx = BlockDev.CryptoKeyslotContext(passphrase="wrong-passphrase")
BlockDev.crypto_tc_open(self.vc_dev, "libblockdevTestTC", ctx)
ctx = BlockDev.CryptoKeyslotContext(passphrase=self.passphrase)
succ = BlockDev.crypto_tc_open(self.vc_dev, "libblockdevTestTC", ctx, veracrypt=True)
self.assertTrue(succ)
self.assertTrue(os.path.exists("/dev/mapper/libblockdevTestTC"))
succ = BlockDev.crypto_tc_close("libblockdevTestTC")
self.assertTrue(succ)
self.assertFalse(os.path.exists("/dev/mapper/libblockdevTestTC"))
@tag_test(TestTags.NOSTORAGE)
def test_seems_encrypted(self):
"""Verify that BlockDev.crypto_device_seems_encrypted works"""
# truecrypt device without header
enc = BlockDev.crypto_device_seems_encrypted(self.tc_dev)
self.assertTrue(enc)
ctx = BlockDev.CryptoKeyslotContext(passphrase=self.passphrase)
succ = BlockDev.crypto_tc_open(self.tc_dev, "libblockdevTestTC", ctx)
self.assertTrue(succ)
# the cleartext device is not encrypted
enc = BlockDev.crypto_device_seems_encrypted("/dev/mapper/libblockdevTestTC")
self.assertFalse(enc)
succ = BlockDev.crypto_tc_close("libblockdevTestTC")
class CryptoTestBitlk(CryptoTestCase):
# we can't create BitLocker formats using libblockdev
# so we are using these images from cryptsetup test suite
# https://gitlab.com/cryptsetup/cryptsetup/blob/master/tests/bitlk-images.tar.xz
bitlk_img = "bitlk-aes-xts-128.img"
passphrase = "anaconda"
tempdir = None
@classmethod
def setUpClass(cls):
super(CryptoTestBitlk, cls).setUpClass()
cls.tempdir = tempfile.mkdtemp(prefix="bd_test_bitlk")
images = os.path.join(os.path.dirname(__file__), "bitlk-images.tar.gz")
with tarfile.open(images, "r") as tar:
tar.extractall(cls.tempdir)
@classmethod
def tearDownClass(cls):
super(CryptoTestBitlk, cls).tearDownClass()
shutil.rmtree(cls.tempdir)
def setUp(self):
self.addCleanup(self._clean_up)
succ, loop = BlockDev.loop_setup(os.path.join(self.tempdir, self.bitlk_img))
if not succ:
raise RuntimeError("Failed to setup loop device for testing")
self.bitlk_dev = "/dev/%s" % loop
def _clean_up(self):
try:
BlockDev.crypto_bitlk_close("libblockdevTestBitlk")
except:
pass
succ = BlockDev.loop_teardown(self.bitlk_dev)
if not succ:
raise RuntimeError("Failed to tear down loop device used for testing")
@unittest.skipUnless(HAVE_BITLK, "BITLK not supported")
def test_bitlk_open_close(self):
"""Verify that opening/closing a BitLocker device works"""
with self.assertRaises(GLib.GError):
ctx = BlockDev.CryptoKeyslotContext(passphrase=self.passphrase)
BlockDev.crypto_bitlk_open("/non/existing/device", "libblockdevTestBitlk", ctx)
with self.assertRaises(GLib.GError):
ctx = BlockDev.CryptoKeyslotContext(passphrase="wrong-passprase")
BlockDev.crypto_bitlk_open(self.bitlk_dev, "libblockdevTestBitlk", ctx)
# info - block device
info = BlockDev.crypto_bitlk_info(self.bitlk_dev)
self.assertIsNotNone(info)
self.assertEqual(info.uuid, "8f595209-f5b9-49a0-85d4-cb8f80258c27")
self.assertEqual(info.cipher, "aes")
self.assertEqual(info.mode, "xts-plain64")
self.assertEqual(info.sector_size, 512)
ctx = BlockDev.CryptoKeyslotContext(passphrase=self.passphrase)
succ = BlockDev.crypto_bitlk_open(self.bitlk_dev, "libblockdevTestBitlk", ctx)
self.assertTrue(succ)
self.assertTrue(os.path.exists("/dev/mapper/libblockdevTestBitlk"))
# info - cleartext device
info = BlockDev.crypto_bitlk_info("libblockdevTestBitlk")
self.assertIsNotNone(info)
self.assertEqual(info.uuid, "8f595209-f5b9-49a0-85d4-cb8f80258c27")
self.assertEqual(info.cipher, "aes")
self.assertEqual(info.mode, "xts-plain64")
self.assertEqual(info.backing_device, self.bitlk_dev)
self.assertEqual(info.sector_size, 512)
info = BlockDev.crypto_bitlk_info("/dev/mapper/libblockdevTestBitlk")
self.assertIsNotNone(info)
succ = BlockDev.crypto_bitlk_close("libblockdevTestBitlk")
self.assertTrue(succ)
self.assertFalse(os.path.exists("/dev/mapper/libblockdevTestBitlk"))
@unittest.skipUnless(HAVE_BITLK, "BITLK not supported")
def test_bitlk_info(self):
"""Verify that we get information about a BitLocker device"""
with self.assertRaises(GLib.GError):
BlockDev.crypto_bitlk_info("/non/existing/device")
# info - block device
info = BlockDev.crypto_bitlk_info(self.bitlk_dev)
self.assertIsNotNone(info)
self.assertEqual(info.uuid, "8f595209-f5b9-49a0-85d4-cb8f80258c27")
self.assertEqual(info.cipher, "aes")
self.assertEqual(info.mode, "xts-plain64")
self.assertEqual(info.sector_size, 512)
ctx = BlockDev.CryptoKeyslotContext(passphrase=self.passphrase)
succ = BlockDev.crypto_bitlk_open(self.bitlk_dev, "libblockdevTestBitlk", ctx)
self.assertTrue(succ)
self.assertTrue(os.path.exists("/dev/mapper/libblockdevTestBitlk"))
# info - cleartext device (name)
info = BlockDev.crypto_bitlk_info("libblockdevTestBitlk")
self.assertIsNotNone(info)
self.assertEqual(info.uuid, "8f595209-f5b9-49a0-85d4-cb8f80258c27")
self.assertEqual(info.cipher, "aes")
self.assertEqual(info.mode, "xts-plain64")
self.assertEqual(info.backing_device, self.bitlk_dev)
self.assertEqual(info.sector_size, 512)
# info - cleartext device (path)
info = BlockDev.crypto_bitlk_info("/dev/mapper/libblockdevTestBitlk")
self.assertIsNotNone(info)
succ = BlockDev.crypto_bitlk_close("libblockdevTestBitlk")
self.assertTrue(succ)
self.assertFalse(os.path.exists("/dev/mapper/libblockdevTestBitlk"))
class CryptoTestFVAULT2(CryptoTestCase):
# we can't create FileVault2 formats using libblockdev
# so we are using these images from cryptsetup test suite
# https://gitlab.com/cryptsetup/cryptsetup/-/blob/master/tests/fvault2-images.tar.xz
fvault2_img = "fvault2.img"
passphrase = "heslo123"
tempdir = None
@classmethod
def setUpClass(cls):
super(CryptoTestFVAULT2, cls).setUpClass()
cls.tempdir = tempfile.mkdtemp(prefix="bd_test_fvault2")
images = os.path.join(os.path.dirname(__file__), "fvault2-images.tar.gz")
with tarfile.open(images, "r") as tar:
tar.extractall(cls.tempdir)
@classmethod
def tearDownClass(cls):
super(CryptoTestFVAULT2, cls).tearDownClass()
shutil.rmtree(cls.tempdir)
def setUp(self):
self.addCleanup(self._clean_up)
succ, loop = BlockDev.loop_setup(os.path.join(self.tempdir, self.fvault2_img))
if not succ:
raise RuntimeError("Failed to setup loop device for testing")
self.fvault2_dev = "/dev/%s" % loop
def _clean_up(self):
try:
BlockDev.crypto_fvault2_close("libblockdevTestFVAULT2")
except:
pass
succ = BlockDev.loop_teardown(self.fvault2_dev)
if not succ:
raise RuntimeError("Failed to tear down loop device used for testing")
@unittest.skipUnless(HAVE_FVAULT2, "FVAULT2 not supported")
def test_fvault2_open_close(self):
"""Verify that opening/closing a FileVault2 device works"""
with self.assertRaises(GLib.GError):
ctx = BlockDev.CryptoKeyslotContext(passphrase=self.passphrase)
BlockDev.crypto_fvault2_open("/non/existing/device", "libblockdevTestFVAULT2", ctx)
with self.assertRaises(GLib.GError):
ctx = BlockDev.CryptoKeyslotContext(passphrase="wrong-passphrase")
BlockDev.crypto_fvault2_open(self.fvault2_dev, "libblockdevTestFVAULT2", ctx)
ctx = BlockDev.CryptoKeyslotContext(passphrase=self.passphrase)
succ = BlockDev.crypto_fvault2_open(self.fvault2_dev, "libblockdevTestFVAULT2", ctx)
self.assertTrue(succ)
self.assertTrue(os.path.exists("/dev/mapper/libblockdevTestFVAULT2"))
succ = BlockDev.crypto_fvault2_close("libblockdevTestFVAULT2")
self.assertTrue(succ)
self.assertFalse(os.path.exists("/dev/mapper/libblockdevTestFVAULT2"))
class CryptoTestIntegrity(CryptoTestCase):
_dm_name = "libblockdevTestIntegrity"
_sparse_size = 100 * 1024**2
def test_integrity(self):
# basic format+open+close test
succ = BlockDev.crypto_integrity_format(self.loop_devs[0], "sha256", False)
self.assertTrue(succ)
succ = BlockDev.crypto_integrity_open(self.loop_devs[0], self._dm_name, "sha256")
self.assertTrue(succ)
self.assertTrue(os.path.exists("/dev/mapper/%s" % self._dm_name))
info = BlockDev.crypto_integrity_info(self._dm_name)
self.assertEqual(info.algorithm, "sha256")
succ = BlockDev.crypto_integrity_close(self._dm_name)
self.assertTrue(succ)
self.assertFalse(os.path.exists("/dev/mapper/%s" % self._dm_name))
# same now with a keyed algorithm
ctx = BlockDev.CryptoKeyslotContext(volume_key=list(secrets.token_bytes(64)))
succ = BlockDev.crypto_integrity_format(self.loop_devs[0], "hmac(sha256)", False, ctx)
self.assertTrue(succ)
succ = BlockDev.crypto_integrity_open(self.loop_devs[0], self._dm_name, "hmac(sha256)", ctx)
self.assertTrue(succ)
self.assertTrue(os.path.exists("/dev/mapper/%s" % self._dm_name))
info = BlockDev.crypto_integrity_info(self._dm_name)
self.assertEqual(info.algorithm, "hmac(sha256)")
succ = BlockDev.crypto_integrity_close(self._dm_name)
self.assertTrue(succ)
self.assertFalse(os.path.exists("/dev/mapper/%s" % self._dm_name))
# same with some custom parameters
extra = BlockDev.CryptoIntegrityExtra(sector_size=4096, interleave_sectors=65536)
succ = BlockDev.crypto_integrity_format(self.loop_devs[0], "crc32c", wipe=False, extra=extra)
self.assertTrue(succ)
succ = BlockDev.crypto_integrity_open(self.loop_devs[0], self._dm_name, "crc32c")
self.assertTrue(succ)
self.assertTrue(os.path.exists("/dev/mapper/%s" % self._dm_name))
info = BlockDev.crypto_integrity_info(self._dm_name)
self.assertEqual(info.algorithm, "crc32c")
self.assertEqual(info.sector_size, 4096)
self.assertEqual(info.interleave_sectors, 65536)
succ = BlockDev.crypto_integrity_close(self._dm_name)
self.assertTrue(succ)
self.assertFalse(os.path.exists("/dev/mapper/%s" % self._dm_name))
# open with flags
succ = BlockDev.crypto_integrity_open(self.loop_devs[0], self._dm_name, "crc32c",
flags=BlockDev.CryptoIntegrityOpenFlags.ALLOW_DISCARDS)
self.assertTrue(succ)
self.assertTrue(os.path.exists("/dev/mapper/%s" % self._dm_name))
# check that discard is enabled for the mapped device
_ret, out, _err = run_command("dmsetup table %s" % self._dm_name)
self.assertIn("allow_discards", out)
succ = BlockDev.crypto_integrity_close(self._dm_name)
self.assertTrue(succ)
self.assertFalse(os.path.exists("/dev/mapper/%s" % self._dm_name))
@tag_test(TestTags.SLOW)
def test_integrity_wipe(self):
# also check that wipe progress reporting works
progress_log = []
def _my_progress_func(_task, _status, completion, msg):
progress_log.append((completion, msg))
succ = BlockDev.utils_init_prog_reporting(_my_progress_func)
self.assertTrue(succ)
self.addCleanup(BlockDev.utils_init_prog_reporting, None)
succ = BlockDev.crypto_integrity_format(self.loop_devs[0], "sha256", True)
self.assertTrue(succ)
# at least one message "Integrity device wipe in progress" should be logged
self.assertTrue(any(prog[1] == "Integrity device wipe in progress" for prog in progress_log))
succ = BlockDev.crypto_integrity_open(self.loop_devs[0], self._dm_name, "sha256")
self.assertTrue(succ)
self.assertTrue(os.path.exists("/dev/mapper/%s" % self._dm_name))
# check the devices was wiped and the checksums recalculated
# (mkfs reads some blocks first so without checksums it would fail)
ret, _out, err = run_command("mkfs.ext2 /dev/mapper/%s " % self._dm_name)
self.assertEqual(ret, 0, msg="Failed to create ext2 filesystem on integrity: %s" % err)
succ = BlockDev.crypto_integrity_close(self._dm_name)
self.assertTrue(succ)
self.assertFalse(os.path.exists("/dev/mapper/%s" % self._dm_name))
class CryptoTestLUKSOpal(CryptoTestCase):
@unittest.skipUnless(HAVE_OPAL, "OPAL not supported")
@tag_test(TestTags.SLOW)
def test_luks_opal_sanity(self):
"""Basic sanity check for LUKS HW-OPAL support"""
with self.assertRaisesRegex(GLib.GError, r"Failed to get opal status for the device"):
BlockDev.crypto_opal_is_supported(self.loop_devs[0])
with self.assertRaisesRegex(GLib.GError, r"OPAL doesn't seem to be supported on"):
BlockDev.crypto_opal_format(self.loop_devs[0], context=BlockDev.CryptoKeyslotContext(passphrase="aaaaa"),
opal_context=BlockDev.CryptoKeyslotContext(passphrase="aaaaa"))
# "normal" LUKS device
self._luks_format(self.loop_devs[0], PASSWD, None)
with self.assertRaisesRegex(GLib.GError, r"isn't a LUKS HW-OPAL device"):
BlockDev.crypto_opal_wipe_device(self.loop_devs[0],
BlockDev.CryptoKeyslotContext(passphrase="aaaaa"))
info = BlockDev.crypto_luks_info(self.loop_devs[0])
self.assertEqual(info.hw_encryption, BlockDev.CryptoLUKSHWEncryptionType.SW_ONLY)
with self.assertRaisesRegex(GLib.GError, r"OPAL doesn't seem to be supported on"):
BlockDev.crypto_opal_reset_device(self.loop_devs[0],
BlockDev.CryptoKeyslotContext(passphrase="aaaaa"))
@unittest.skip("requires special hardware")
@tag_test(TestTags.SLOW)
def test_luks_opal_full(self):
""" Full LUKS HW-OPAL support test"""
# requires a disk that supports OPAL so this test case will be always skipped and
# exists only for manual testing purposes outside CI
DISK = ""
OPAL_PASSWD = "anaconda"
ctx = BlockDev.CryptoKeyslotContext(passphrase=PASSWD) # LUKS passphrase
opal_ctx = BlockDev.CryptoKeyslotContext(passphrase=OPAL_PASSWD) # OPAL admin passphrase
ret = BlockDev.crypto_opal_is_supported(DISK)
self.assertTrue(ret)
# OPAL only
ret = BlockDev.crypto_opal_format(DISK, context=ctx, opal_context=opal_ctx,
hw_encryption=BlockDev.CryptoLUKSHWEncryptionType.OPAL_HW_ONLY)
self.assertTrue(ret)
info = BlockDev.crypto_luks_info(DISK)
self.assertEqual(info.hw_encryption, BlockDev.CryptoLUKSHWEncryptionType.OPAL_HW_ONLY)
self.assertEqual(info.subsystem, "HW-OPAL")
succ = BlockDev.crypto_luks_open(DISK, "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
ret = BlockDev.crypto_opal_wipe_device(DISK, opal_ctx)
self.assertTrue(ret)
# OPAL + dm-crypt
ret = BlockDev.crypto_opal_format(DISK, context=ctx, opal_context=opal_ctx,
hw_encryption=BlockDev.CryptoLUKSHWEncryptionType.OPAL_HW_AND_SW)
self.assertTrue(ret)
info = BlockDev.crypto_luks_info(DISK)
self.assertEqual(info.hw_encryption, BlockDev.CryptoLUKSHWEncryptionType.OPAL_HW_AND_SW)
self.assertEqual(info.subsystem, "HW-OPAL")
succ = BlockDev.crypto_luks_open(DISK, "libblockdevTestLUKS", ctx, False)
self.assertTrue(succ)
succ = BlockDev.crypto_luks_close("libblockdevTestLUKS")
self.assertTrue(succ)
ret = BlockDev.crypto_opal_wipe_device(DISK, opal_ctx)
self.assertTrue(ret)
|