bin/tomb
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 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 |
#!/usr/bin/env zsh # # Tomb, the Crypto Undertaker # # A commandline tool to easily operate encryption of secret data # # {{{ License # Copyright (C) 2007-2021 Dyne.org Foundation # # Tomb is designed, written and maintained by Denis Roio <jaromil@dyne.org> # # Please refer to the AUTHORS file for more information. # # This source code is free software; you can redistribute it and/or # modify it under the terms of the GNU Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This source code is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Please refer # to the GNU Public License for more details. # # You should have received a copy of the GNU Public License along with # this source code; if not, , see <https://www.gnu.org/licenses/>. # }}} - License # {{{ Global variables typeset VERSION="2.9.0" typeset DATE="Jan/2021" typeset TOMBEXEC=$0 typeset TMPDIR=${${TMPPREFIX%/*}:-/tmp} # TODO: configure which tmp dir to use from a cli flag # Tomb is using some global variables set by the shell: # TMPPREFIX, UID, GID, PATH, TTY, USERNAME # You can grep 'global variable' to see where they are used. # Keep a reference of the original command line arguments typeset -a OLDARGS for arg in "${(@)argv}"; do OLDARGS+=("$arg"); done # Special command requirements typeset -a DD WIPE PINENTRY DD=(dd) WIPE=(rm -f) PINENTRY=(pinentry) # load zsh regex module zmodload zsh/mapfile zmodload -F zsh/stat b:zstat # make sure variables aren't exported unsetopt allexport # Flag optional commands if available (see _ensure_dependencies()) typeset -i KDF=1 typeset -i STEGHIDE=1 typeset -i CLOAKIFY=1 typeset -i DECLOAKIFY=1 typeset -i SPHINX=1 typeset -i RESIZER=1 typeset -i SWISH=1 typeset -i QRENCODE=1 # Default mount options typeset MOUNTOPTS="rw,noatime,nodev" # Makes glob matching case insensitive unsetopt CASE_MATCH typeset -AH OPTS # Command line options (see main()) # Command context (see _whoami()) typeset -H _USER # Running username typeset -Hi _UID # Running user identifier typeset -Hi _GID # Running user group identifier typeset -H _TTY # Connected input terminal # Tomb context (see is_valid_tomb()) typeset -H TOMBPATH # Full path to the tomb typeset -H TOMBDIR # Directory where the tomb is typeset -H TOMBFILE # File name of the tomb typeset -H TOMBNAME # Name of the tomb # Tomb secrets typeset -H TOMBKEY # Encrypted key contents (see forge_key(), recover_key()) typeset -H TOMBKEYFILE # Key file (ditto) typeset -H TOMBSECRET # Raw deciphered key (see forge_key(), gpg_decrypt()) typeset -H TOMBPASSWORD # Raw tomb passphrase (see gen_key(), ask_key_password()) typeset -H TOMBTMP # Filename of secure temp just created (see _tmp_create()) typeset -aH TOMBTMPFILES # Keep track of temporary files typeset -aH TOMBLOOPDEVS # Keep track of used loop devices typeset -A TOMBFILESSTAT # Keep track of access date attributes typeset _MSG_FD_OVERRIDE # if set, _msg will write to this file descriptor # Make sure sbin is in PATH (man zshparam) path+=( /sbin /usr/sbin ) # For gettext export TEXTDOMAIN=tomb # }}} # {{{ Safety functions # Wrap sudo with a more visible message _sudo() { local msg="[sudo] Enter password for user ::1 user:: to gain superuser privileges" command -v gettext 1>/dev/null 2>/dev/null && msg="$(gettext -s "$msg")" msg=${(S)msg//::1*::/$USER} sudo -p " $msg " ${@} } # Cleanup anything sensitive before exiting. _endgame() { # Restore access time of sensitive files [[ -z $TOMBFILESSTAT ]] || _restore_stat # Prepare some random material to overwrite vars local rr="$RANDOM" while [[ ${#rr} -lt 500 ]]; do rr+="$RANDOM" done # Ensure no information is left in unallocated memory TOMBPATH="$rr"; unset TOMBPATH TOMBDIR="$rr"; unset TOMBDIR TOMBFILE="$rr"; unset TOMBFILE TOMBNAME="$rr"; unset TOMBNAME TOMBKEY="$rr"; unset TOMBKEY TOMBKEYFILE="$rr"; unset TOMBKEYFILE TOMBSECRET="$rr"; unset TOMBSECRET TOMBPASSWORD="$rr"; unset TOMBPASSWORD # Clear temporary files for f in $TOMBTMPFILES; do ${=WIPE} "$f" done unset TOMBTMPFILES # Detach loop devices for l in $TOMBLOOPDEVS; do _sudo losetup -d "$l" done unset TOMBLOOPDEVS } # Trap functions for the _endgame event TRAPINT() { _endgame INT } TRAPEXIT() { _endgame EXIT } TRAPHUP() { _endgame HUP } TRAPQUIT() { _endgame QUIT } TRAPABRT() { _endgame ABORT } TRAPKILL() { _endgame KILL } TRAPPIPE() { _endgame PIPE } TRAPTERM() { _endgame TERM } TRAPSTOP() { _endgame STOP } _cat() { local -a _arr; # read file using mapfile, newline fix _arr=("${(f@)${mapfile[${1}]%$'\n'}}"); print "$_arr" } _is_found() { # returns 0 if binary is found in path [[ -z $1 ]] && return 1 command -v "$1" 1>/dev/null 2>/dev/null return $? } # Track acces and modification time of tomb files. # $1: file to track # date format: seconds since Epoch # stat format: <last access>:<last modified> _track_stat() { local file="$1" local stat=$(stat --format="%X:%Y" "$file") TOMBFILESSTAT+=("$file" "$stat") } # Restore files stats _restore_stat() { local file stat for file stat in "${(@kv)TOMBFILESSTAT}"; do stats=("${(@s.:.)stat}") _verbose "Restoring access and modification time for ::1 file::" $file [[ -z "${stats[1]}" ]] || touch -a --date="@${stats[1]}" "$file" [[ -z "${stats[2]}" ]] || touch -m --date="@${stats[2]}" "$file" done } # Identify the running user # Set global variables _UID, _GID, _TTY, and _USER, either from the # command line, -U, -G, -T, respectively, or from the environment. # Also update USERNAME and HOME to maintain consistency. _whoami() { # Set username from UID or environment _USER=$SUDO_USER [[ -z $_USER ]] && { _USER=$USERNAME } [[ -z $_USER ]] && { _USER=$(id -un) } [[ -z $_USER ]] && { _failure "Failing to identify the user who is calling us" } # Get GID from option -G or the environment option_is_set -G \ && _GID=$(option_value -G) || _GID=$(id -g $_USER) # Get UID from option -U or the environment option_is_set -U \ && _UID=$(option_value -U) || _UID=$(id -u $_USER) _verbose "Identified caller: ::1 username:: (::2 UID:::::3 GID::)" $_USER $_UID $_GID # Update USERNAME accordingly if possible # [[ $EUID == 0 && $_USER != $USERNAME ]] && { # _verbose "Updating USERNAME from '::1 USERNAME::' to '::2 _USER::')" $USERNAME $_USER # USERNAME=$_USER # } # Force HOME to _USER's HOME if necessary local home=`_get_home $_USER` [[ $home == $HOME ]] || { _verbose "Updating HOME to match user's: ::1 home:: (was ::2 HOME::)" \ $home $HOME HOME=$home } # Get connecting TTY from option -T or the environment option_is_set -T && _TTY=$(option_value -T) [[ -z $_TTY ]] && _TTY=$TTY } # Provide a random filename in shared memory _tmp_create() { [[ -d "$TMPDIR" ]] || { # we create the tempdir with the sticky bit on _sudo mkdir -m 1777 "$TMPDIR" [[ $? == 0 ]] || _failure "Fatal error creating the temporary directory: ::1 temp dir::" "$TMPDIR" } # We're going to add one more $RANDOM for each time someone complains # about this being too weak of a random. tfile="${TMPDIR}/$RANDOM$RANDOM$RANDOM$RANDOM" # Temporary file umask 066 [[ $? == 0 ]] || { _failure "Fatal error setting the permission umask for temporary files" } [[ -r "$tfile" ]] && { _failure "Someone is messing up with us trying to hijack temporary files." } touch "$tfile" [[ $? == 0 ]] || { _failure "Fatal error creating a temporary file: ::1 temp file::" "$tfile" } _verbose "Created tempfile: ::1 temp file::" "$tfile" TOMBTMP="$tfile" TOMBTMPFILES+=("$tfile") return 0 } # Check if a *block* device is encrypted # Synopsis: _is_encrypted_block /path/to/block/device # Return 0 if it is an encrypted block device _is_encrypted_block() { local b=$1 # Path to a block device local s="" # lsblk option -s (if available) # Issue #163 # lsblk --inverse appeared in util-linux 2.22 # but --version is not consistent... lsblk --help | grep -Fq -- --inverse [[ $? -eq 0 ]] && s="--inverse" sudo lsblk $s -o type -n $b 2>/dev/null \ | egrep -q '^crypt$' return $? } # Check if swap is activated # Return 0 if NO swap is used, 1 if swap is used. # Return 1 if any of the swaps is not encrypted. # Return 2 if swap(s) is(are) used, but ALL encrypted. # Use _check_swap in functions. It will call this function and # exit if unsafe swap is present. _ensure_safe_swap() { local -i r=1 # Return code: 0 no swap, 1 unsafe swap, 2 encrypted local -a swaps # List of swap partitions local bone is_crypt swaps="$(awk '/^\// { print $1 }' /proc/swaps 2>/dev/null)" [[ -z "$swaps" ]] && return 0 # No swap partition is active _message "An active swap partition is detected..." for s in $=swaps; do if _is_encrypted_block $s; then r=2; else # We're dealing with unencrypted stuff. # Maybe it lives on an encrypted filesystem anyway. # @todo: verify it's actually on an encrypted FS (see #163 and !189) # Well, no: bail out. r=1; break; fi done if [[ $r -eq 2 ]]; then _success "The undertaker found that all swap partitions are encrypted. Good." else _warning "This poses a security risk." _warning "You can deactivate all swap partitions using the command:" _warning " swapoff -a" _warning "[#163] I may not detect plain swaps on an encrypted volume." _warning "But if you want to proceed like this, use the -f (force) flag." fi return $r } # Wrapper to allow encrypted swap and remind the user about possible # data leaks to disk if swap is on, which shouldn't be ignored. It could # be run once in main(), but as swap evolves, it's better to run it # whenever swap may be needed. # Exit if unencrypted swap is active on the system. _check_swap() { if ! option_is_set -f && ! option_is_set --ignore-swap; then _ensure_safe_swap case $? in 0|2) # No, or encrypted swap return 0 ;; *) # Unencrypted swap _failure "Operation aborted." ;; esac fi } pinentry_assuan_getpass() { # simply prints out commands for pinentry's stdin to activate the # password dialog cat <<EOF OPTION ttyname=$TTY OPTION lc-ctype=$LANG SETTITLE $title SETDESC $description SETPROMPT Password: GETPIN EOF } # Ask user for a password # Wraps around the pinentry command, from the GnuPG project, as it # provides better security and conveniently use the right toolkit. ask_password() { local description="$1" local title="${2:-Enter tomb password.}" local output local password local gtkrc local theme local pass_asked # Distributions have broken wrappers for pinentry: they do # implement fallback, but they disrupt the output somehow. We are # better off relying on less intermediaries, so we implement our # own fallback mechanisms. Pinentry supported: curses, gtk-2, qt4, qt5 # and x11. # make sure LANG is set, default to C LANG=${LANG:-C} _verbose "asking password with tty=$TTY lc-ctype=$LANG" pass_asked=0 if [[ ! -z $WAYLAND_DISPLAY ]]; then _verbose "wayland display detected" _is_found "pinentry-gnome3" && { _verbose "using pinentry-gnome3 on wayland" output=$(pinentry_assuan_getpass | pinentry-gnome3) pass_asked=1 } fi if [[ ! -z $DISPLAY ]] && [[ $pass_asked == 0 ]]; then _verbose "X11 display detected" if _is_found "pinentry-gtk-2"; then _verbose "using pinentry-gtk2" output=$(pinentry_assuan_getpass | pinentry-gtk-2) pass_asked=1 elif _is_found "pinentry-x11"; then _verbose "using pinentry-x11" output=$(pinentry_assuan_getpass | pinentry-x11) pass_asked=1 elif _is_found "pinentry-gnome3"; then _verbose "using pinentry-gnome3 on X11" output=$(pinentry_assuan_getpass | pinentry-gnome3) pass_asked=1 elif _is_found "pinentry-qt5"; then _verbose "using pinentry-qt5" output=$(pinentry_assuan_getpass | pinentry-qt5) pass_asked=1 elif _is_found "pinentry-qt4"; then _verbose "using pinentry-qt4" output=$(pinentry_assuan_getpass | pinentry-qt4) pass_asked=1 fi fi if [[ $pass_asked == 0 ]]; then _verbose "no display detected" _is_found "pinentry-curses" && { _verbose "using pinentry-curses with no display" output=$(pinentry_assuan_getpass | pinentry-curses) pass_asked=1 } fi [[ $pass_asked == 0 ]] && _failure "Cannot find any pinentry-curses and no DISPLAY detected." # parse the pinentry output local pinentry_error for i in ${(f)output}; do [[ "$i" =~ "^ERR.*" ]] && { pinentry_error="${i[(w)3]}" } # here the password is found [[ "$i" =~ "^D .*" ]] && password="${i##D }"; done [[ ! -z $pinentry_error ]] && [[ -z $password ]] && { _warning "Pinentry error: ::1 error::" ${pinentry_error} print "canceled" return 1 } # if sphinx mode is chosen, use the provided input # as master password to retrieve the actual password if option_is_set --sphx-user || option_is_set --sphx-host; then password=$(sphinx_get_password "$password") fi [[ -z $password ]] && { _warning "Empty password" print "empty" return 1 } print "$password" return 0 } # Retrieve PASSWORD from sphinx # $1 MASTER password for the password store # requires --sphx-host and --sphx-user flags to be set sphinx_get_password() { local errorfile local password if option_is_set --sphx-user && option_is_set --sphx-host; then # value error in sphinx doesn't set exit code # using tempfile as a workaround to notice the error errorfile=$(mktemp /tmp/tomb_error.XXXXXXXXX) password=$(echo "$1" | sphinx get $(option_value --sphx-user) $(option_value --sphx-host) 2>$errorfile) if ! grep -q "ValueError: fail" $errorfile ; then echo "$password" rm $errorfile return 0 else _warning "sphinx returns error: ::1 error::" $(cat $errorfile) rm $errorfile _failure "Failed to retrieve actual password with sphinx." fi else _failure "Both host and user have to be set to use sphinx" fi } # Create PASSWORD in sphinx # $1 MASTER password for the password store # requires --sphx-host and --sphx-user flags to be set sphinx_set_password() { local errorfile local password if option_is_set --sphx-user && option_is_set --sphx-host; then # value error in sphinx doesn't set exit code # using tempfile as a workaround to notice the error errorfile=$(mktemp /tmp/tomb_error.XXXXXXXXX) # check first if this host/user combination exists in store # if yes, there is no need to make a call to create password=$(echo "$1" | sphinx get $(option_value --sphx-user) $(option_value --sphx-host) 2>$errorfile) if ! grep -q "ValueError: fail" $errorfile ; then echo "$password" rm $errorfile return 0 fi # no such host/user combination in store, create one password=$(echo "$1" | sphinx create $(option_value --sphx-user) $(option_value --sphx-host) ulsd 0 2>$errorfile) if ! grep -q "ValueError: fail" $errorfile ; then echo "$password" rm $errorfile return 0 else _warning "sphinx returns error: ::1 error::" $(cat $errorfile) rm $errorfile _failure "Failed to create password with sphinx" fi else _failure "Both host and user have to be set to use sphinx" fi } # Check if a filename is a valid tomb is_valid_tomb() { _verbose "is_valid_tomb ::1 tomb file::" $1 # First argument must be the path to a tomb [[ ! -z $1 ]] || _failure "Tomb file is missing from arguments." local _fail=0 # Tomb file must be a readable, writable, non-empty regular file. # If passed the "ro" mount option, the writable check is skipped. [[ ! -w "$1" ]] && [[ $(option_value -o) != *"ro"* ]] && { _warning "Tomb file is not writable: ::1 tomb file::" $1 _fail=1 } _verbose "tomb file is readable" [[ ! -f "$1" ]] && { _warning "Tomb file is not a regular file: ::1 tomb file::" $1 _fail=1 } _verbose "tomb file is a regular file" [[ ! -s "$1" ]] && { _warning "Tomb file is empty (zero length): ::1 tomb file::" $1 _fail=1 } _verbose "tomb file is not empty" [[ $_fail == 1 ]] && { _failure "Tomb command failed: ::1 command name::" $subcommand } # Tomb file may be a LUKS FS (or we are creating it) [[ "`file $1`" =~ "luks encrypted file" ]] || { _warning "File is not yet a tomb: ::1 tomb file::" $1 } # We set global variables typeset -g TOMBPATH TOMBDIR TOMBFILE TOMBNAME TOMBMAPPER TOMBPATH="$1" TOMBDIR=$(dirname $TOMBPATH) TOMBFILE=$(basename $TOMBPATH) # The tomb name is TOMBFILE without an extension and underscores instead of spaces (for mount and cryptsetup) # It can start with dots: ..foo bar baz.tomb -> ..foo_bar_baz TOMBNAME=${${TOMBFILE// /_}%.*} # use the entire filename if the previous transformation returns # an empty string. This handles the corner case of tomb being # hidden files (starting with a dot) and have no extension (only # one dot in string) TOMBNAME=${TOMBNAME:-${TOMBFILE}} [[ -z $TOMBNAME ]] && _failure "Tomb won't work without a TOMBNAME." # checks if Tomb already mounted (or we cannot alter it) local maphash=`realpath $TOMBPATH | sha256sum -z` local nextloop=`_sudo losetup -f` TOMBMAPPER="tomb.$TOMBNAME.${maphash[(w)1]}.`basename $nextloop`" local mounted_tombs=(`list_tomb_mounts`) local usedmapper for t in ${mounted_tombs}; do usedmapper=`basename "${t[(ws:;:)1]}"` [[ "${usedmapper%.*}" == "${TOMBMAPPER%.*}" ]] && _failure "Tomb file already in use: ::1 tombname::" $TOMBPATH done _verbose "Mapper: ::1 mapper::" $TOMBMAPPER _verbose "tomb file is not currently in use" _message "Valid tomb file found: ::1 tomb path::" $TOMBPATH return 0 } # $1 is the tomb file to be lomounted lo_mount() { tpath="$1" # check if we have support for loop mounting TOMBLOOP=`_sudo losetup -f` [[ $? = 0 ]] || { _warning "Loop mount of volumes is not possible on this machine, this error" _warning "often occurs on VPS and kernels that don't provide the loop module." _warning "It is impossible to use Tomb on this machine under these conditions." _failure "Operation aborted." } _sudo losetup -f "$tpath" # allocates the next loopback for our file TOMBLOOPDEVS+=("$TOMBLOOP") # add to array of lodevs used return 0 } # print out latest loopback mounted lo_new() { print - "${TOMBLOOPDEVS[${#TOMBLOOPDEVS}]}" } # $1 is the path to the lodev to be preserved after quit lo_preserve() { _verbose "lo_preserve on ::1 path::" $1 # remove the lodev from the tomb_lodevs array TOMBLOOPDEVS=("${(@)TOMBLOOPDEVS:#$1}") } # eventually used for debugging dump_secrets() { print "TOMBPATH: $TOMBPATH" print "TOMBNAME: $TOMBNAME" print "TOMBKEY len: ${#TOMBKEY}" print "TOMBKEYFILE: $TOMBKEYFILE" print "TOMBSECRET len: ${#TOMBSECRET}" print "TOMBPASSWORD: $TOMBPASSWORD" print "TOMBTMPFILES: ${(@)TOMBTMPFILES}" print "TOMBLOOPDEVS: ${(@)TOMBLOOPDEVS}" } # }}} # {{{ Commandline interaction usage() { _print "Syntax: tomb [options] command [arguments]" echo _print "Commands:" echo _print " // Creation:" _print " dig create a new empty TOMB file of size -s in MiB" _print " forge create a new KEY file and set its password" _print " lock installs a lock on a TOMB to use it with KEY" echo _print " // Operations on tombs:" _print " open open an existing TOMB (-k KEY file or - for stdin)" _print " index update the search indexes of tombs" _print " search looks for filenames matching text patterns" _print " list list of open TOMBs and information on them" _print " ps list of running processes inside open TOMBs" _print " close close a specific TOMB (or 'all')" _print " slam slam a TOMB killing all programs using it" [[ $RESIZER == 1 ]] && { _print " resize resize a TOMB to a new size -s (can only grow)" } echo _print " // Operations on keys:" _print " passwd change the password of a KEY (needs old pass)" _print " setkey change the KEY locking a TOMB (needs old key and pass)" echo [[ $QRENCODE == 1 ]] && { _print " // Backup on paper:" _print " engrave makes a QR code of a KEY to be saved on paper" echo } [[ $STEGHIDE == 1 || $CLOAKIFY == 1 || $DECLOAKIFY == 1 ]] && { _print " // Steganography:" [[ $STEGHIDE == 1 ]] && { _print " bury hide a KEY inside a JPEG image (for use with -k)" _print " exhume extract a KEY from a JPEG image (prints to stdout)" } [[ $CLOAKIFY == 1 ]] && { _print " cloak transform a KEY into TEXT using CIPHER (for use with -k)" } [[ $DECLOAKIFY == 1 ]] && { _print " uncloak extract a KEY from a TEXT using CIPHER (prints to stdout)" } echo } _print "Options:" echo _print " -s size of the tomb file when creating/resizing one (in MiB)" _print " -k path to the key to be used ('-k -' to read from stdin)" _print " -n don't launch the execution hooks found in tomb" _print " -p preserve the ownership of all files in tomb" _print " -o options passed to commands: open, lock, forge (see man)" _print " -f force operation (i.e. even if swap is active)" _print " -g use a GnuPG key to encrypt a tomb key" _print " -r provide GnuPG recipients (separated by comma)" _print " -R provide GnuPG hidden recipients (separated by comma)" [[ $SPHINX == 1 ]] && { _print " --sphx-user user associated with the key (for use with pitchforkedsphinx)" _print " --sphx-host host associated with the key (for use with pitchforkedsphinx)" } [[ $KDF == 1 ]] && { _print " --kdf forge keys armored against dictionary attacks" } echo _print " -h print this help" _print " -v print version, license and list of available ciphers" _print " -q run quietly without printing informations" _print " -D print debugging information at runtime" echo _print "For more information on Tomb read the manual: man tomb" _print "Please report bugs on <http://github.com/dyne/tomb/issues>." } # Check whether a commandline option is set. # # Synopsis: option_is_set -flag [out] # # First argument is the commandline flag (e.g., "-s"). # If the second argument is present and set to 'out', print out the # result: either 'set' or 'unset' (useful for if conditions). # # Return 0 if is set, 1 otherwise option_is_set() { local -i r # the return code (0 = set, 1 = unset) [[ -n ${(k)OPTS[$1]} ]]; r=$? [[ $2 == "out" ]] && { [[ $r == 0 ]] && { print 'set' } || { print 'unset' } } return $r; } # Print the option value matching the given flag # Unique argument is the commandline flag (e.g., "-s"). option_value() { print -n - "${OPTS[$1]}" } # Messaging function with pretty coloring function _msg() { local msg="$2" local i command -v gettext 1>/dev/null 2>/dev/null && msg="$(gettext -s "$2")" for i in {3..${#}}; do msg=${(S)msg//::$(($i - 2))*::/$*[$i]} done local command="print -P" local progname="${TOMBEXEC##*/}" local pchars="" local pcolor="normal" local fd=2 local -i returncode case "$1" in inline) command+=" -n"; pchars=" > "; pcolor="yellow" ;; message) pchars=" . "; pcolor="white" ;; verbose) pchars="[D]"; pcolor="blue" ;; success) pchars="(*)"; pcolor="green" ;; warning) pchars="[W]"; pcolor="yellow" ;; failure) pchars="[E]"; pcolor="red" returncode=1 ;; print) progname="" fd=1 ;; *) pchars="[F]"; pcolor="red" msg="Developer oops! Usage: _msg MESSAGE_TYPE \"MESSAGE_CONTENT\"" returncode=127 ;; esac [[ -n $_MSG_FD_OVERRIDE ]] && fd=$_MSG_FD_OVERRIDE if [[ -t $fd ]]; then [[ -n "$progname" ]] && progname="$fg[magenta]$progname$reset_color" [[ -n "$pchars" ]] && pchars="$fg_bold[$pcolor]$pchars$reset_color" msg="$fg[$pcolor]$msg$reset_color" fi ${=command} "${progname}" "${pchars}" "${msg}" >&$fd return $returncode } function _message() { local notice="message" [[ "$1" = "-n" ]] && shift && notice="inline" option_is_set -q || _msg "$notice" $@ return 0 } function _verbose() { option_is_set -D && _msg verbose $@ return 0 } function _success() { option_is_set -q || _msg success $@ return 0 } function _warning() { option_is_set -q || _msg warning $@ return 1 } function _failure() { typeset -i exitcode=${exitv:-1} option_is_set -q || _msg failure $@ # be sure we forget the secrets we were told exit $exitcode } function _print() { option_is_set -q || _msg print $@ return 0 } _list_optional_tools() { typeset -a _deps _deps=(gettext dcfldd shred steghide) _deps+=(resize2fs tomb-kdb-pbkdf2 qrencode swish-e unoconv lsof) for d in $_deps; do _print "`which $d`" done return 0 } # Check program dependencies # # Tomb depends on system utilities that must be present, and other # functionality that can be provided by various programs according to # what's available on the system. If some required commands are # missing, bail out. _ensure_dependencies() { # Check for required programs for req in cryptsetup pinentry sudo gpg mkfs.ext4 e2fsck; do command -v $req 1>/dev/null 2>/dev/null || { _failure "Missing required dependency ::1 command::. Please install it." $req; } done # Ensure system binaries are available in the PATH path+=(/sbin /usr/sbin) # zsh magic # Which dd command to use command -v dcfldd 1>/dev/null 2>/dev/null && DD=(dcfldd statusinterval=1) # Which wipe command to use command -v shred 1>/dev/null 2>/dev/null && WIPE=(shred -f -u) # Check for lsof for slamming tombs command -v lsof 1>/dev/null 2>/dev/null || LSOF=0 # Check for steghide command -v steghide 1>/dev/null 2>/dev/null || STEGHIDE=0 # Check for python2 command -v python2 -V 1>/dev/null 2>/dev/null || PYTHON2=0 # Check for cloakify command -v cloakify 1>/dev/null 2>/dev/null || CLOAKIFY=0 # Check for decloakify command -v decloakify 1>/dev/null 2>/dev/null || DECLOAKIFY=0 # Check for pitchforkedsphinx client command -v sphinx 1>/dev/null 2>/dev/null || SPHINX=0 # Check for resize command -v resize2fs 1>/dev/null 2>/dev/null || RESIZER=0 # Check for KDF auxiliary tools command -v tomb-kdb-pbkdf2 1>/dev/null 2>/dev/null || KDF=0 # Check for Swish-E file content indexer command -v swish-e 1>/dev/null 2>/dev/null || SWISH=0 # Check for QREncode for paper backups of keys command -v qrencode 1>/dev/null 2>/dev/null || QRENCODE=0 } # }}} - Commandline interaction # {{{ Key operations # $@ is the list of all the recipient used to encrypt a tomb key is_valid_recipients() { typeset -a recipients recipients=($@) trusted=(m f u w s) _verbose "is_valid_recipients" # All the keys ID must be valid (the public keys must be present in the database) for gpg_id in ${recipients[@]}; do trust="$(gpg --with-colons --batch --list-keys "$gpg_id" 2> /dev/null | awk 'BEGIN { FS=":" } /^pub/ { print $2; exit}')" [[ $? != 0 ]] && { _warning "Not a valid GPG key ID: ::1 gpgid:: " $gpg_id return 1 } [[ ${trusted[(r)$trust]} != $trust ]] && { _warning "The key ::1 gpgid:: is not trusted enough" $gpg_id return 1 } done # At least one private key must be present for gpg_id in ${recipients[@]}; do gpg --with-colons --batch --list-secret-keys "$gpg_id" &> /dev/null [[ $? = 0 ]] && { return 0 } done return 1 } # $@ is the list of all the recipient used to encrypt a tomb key # Print the recipient arg to be used in gpg. _recipients_arg() { local arg="$1"; shift typeset -a recipients recipients=($@) for gpg_id in ${recipients[@]}; do print -R -n "$arg $gpg_id " done return 0 } # $1 is a GPG key recipient # Print the fingerprint of the GPG key _gpg_fingerprint() { gpg --with-colons --fingerprint "$1" | awk 'BEGIN { FS=":" } /^fpr/ { print $10; exit }' } _gpg_uid() { gpg --with-colons --list-key "$1" | awk 'BEGIN { FS=":" } /^uid/ { print $10; exit}' } # helpers to retrieve data from passwd using getent _get_username() { getent passwd ${1} | awk -F: '{print $1}' } _get_home() { getent passwd ${1} | awk -F: '{print $6}' } # $1 is the encrypted key contents we are checking is_valid_key() { local key="$1" # Unique argument is an encrypted key to test _verbose "is_valid_key" [[ -z $key ]] && key=$TOMBKEY [[ "$key" = "cleartext" ]] && { { option_is_set --unsafe } || { _warning "cleartext key from stdin selected: this is unsafe." exitv=127 _failure "please use --unsafe if you really want to do this." } _warning "received key in cleartext from stdin (unsafe mode)" return 0 } [[ -z $key ]] && { _warning "is_valid_key() called without an argument." return 1 } # If the key file is an image don't check file header [[ -r $TOMBKEYFILE ]] \ && [[ $(file $TOMBKEYFILE) =~ "JP.G" ]] \ && { _message "Key is an image, it might be valid." return 0 } [[ $KDF == 1 ]] && { ! option_is_set -g } && { option_is_set --kdf } && { _head="${key[(f)1]}" [[ $_head =~ '^_KDF_' ]] || { _warning "Key is missing KDF header." return 1 } } [[ $key =~ "BEGIN PGP" ]] && { _message "Key is valid." return 0 } return 1 } # $1 is a string containing an encrypted key recover_key() { local key="${1}" # Unique argument is an encrypted key _warning "Attempting key recovery." _head="${key[(f)1]}" # take the first line TOMBKEY="" # Reset global variable [[ $_head =~ "^_KDF_" ]] && TOMBKEY+="$_head\n" TOMBKEY+="-----BEGIN PGP MESSAGE-----\n" TOMBKEY+="$key\n" TOMBKEY+="-----END PGP MESSAGE-----\n" return 0 } # Retrieve the tomb key from the file specified from the command line, # or from stdin if -k - was selected. Run validity checks on the # file. On success, return 0 and print out the full path of the key. # Set global variables TOMBKEY and TOMBKEYFILE. _load_key() { local keyfile="$1" # Unique argument is an optional keyfile [[ -z $keyfile ]] && keyfile=$(option_value -k) [[ -z $keyfile ]] && { _failure "This operation requires a key file to be specified using the -k option." } if [[ $keyfile == "-" ]]; then _verbose "load_key reading from stdin." _message "Waiting for the key to be piped from stdin... " TOMBKEYFILE=stdin TOMBKEY=$(cat) elif [[ $keyfile == "cleartext" ]]; then _verbose "load_key reading SECRET from stdin" _message "Waiting for the key to be piped from stdin... " TOMBKEYFILE=cleartext TOMBKEY=cleartext TOMBSECRET=$(cat) else _verbose "load_key argument: ::1 key file::" $keyfile [[ -r $keyfile ]] || _failure "Key not found, specify one using -k." _track_stat "$keyfile" TOMBKEYFILE=$keyfile TOMBKEY="${mapfile[$TOMBKEYFILE]}" fi _verbose "load_key: ::1 key::" $TOMBKEYFILE [[ -z $TOMBKEY ]] && { # something went wrong, there is no key to load # this occurs especially when piping from stdin and aborted _failure "Key not found, specify one using -k." } is_valid_key $TOMBKEY || { _warning "The key seems invalid or its format is not known by this version of Tomb." recover_key $TOMBKEY } # Declared TOMBKEYFILE (path) # Declared TOMBKEY (contents) return 0 } # takes two args just like get_lukskey # prints out the decrypted content # contains tweaks for different gpg versions # support both symmetric and asymmetric encryption gpg_decrypt() { # fix for gpg 1.4.11 where the --status-* options don't work ;^/ local gpgver=$(gpg --version --no-permission-warning | awk '/^gpg/ {print $3}') local gpgpass="$1\n$TOMBKEY" local tmpres ret typeset -a gpgopt gpgpopt=(--batch --no-tty --passphrase-fd 0 --no-options) { option_is_set -g } && { gpgpass="$TOMBKEY" gpgpopt=(--yes) # GPG option '--try-secret-key' exist since GPG 2.1 { option_is_set -R } && { autoload -U is-at-least && is-at-least "2.1" $gpgver } && { typeset -a recipients recipients=(${(s:,:)$(option_value -R)}) { is_valid_recipients $recipients } || { _failure "You set an invalid GPG ID." } gpgpopt+=(`_recipients_arg "--try-secret-key" $recipients`) } } [[ $gpgver == "1.4.11" ]] && { _verbose "GnuPG is version 1.4.11 - adopting status fix." TOMBSECRET=`print - "$gpgpass" | \ gpg --decrypt ${gpgpopt[@]}` ret=$? unset gpgpass return $ret } _tmp_create tmpres=$TOMBTMP TOMBSECRET=`print - "$gpgpass" | \ gpg --decrypt ${gpgpopt[@]} \ --status-fd 2 --no-mdc-warning --no-permission-warning \ --no-secmem-warning 2> $tmpres` unset gpgpass ret=1 for i in ${(f)"$(cat $tmpres)"}; do _verbose "$i" [[ "$i" =~ "DECRYPTION_OKAY" ]] && ret=0; done return $ret } # Gets a key file and a password, prints out the decoded contents to # be used directly by Luks as a cryptographic key get_lukskey() { # $1 is the password _verbose "get_lukskey" _password="$1" firstline="${TOMBKEY[(f)1]}" # key is KDF encoded if [[ $firstline =~ '^_KDF_' ]]; then kdf_hash="${firstline[(ws:_:)2]}" _verbose "KDF: ::1 kdf::" "$kdf_hash" case "$kdf_hash" in "pbkdf2sha1") kdf_salt="${firstline[(ws:_:)3]}" kdf_ic="${firstline[(ws:_:)4]}" kdf_len="${firstline[(ws:_:)5]}" _message "Unlocking KDF key protection (::1 kdf::)" $kdf_hash _verbose "KDF salt: $kdf_salt" _verbose "KDF ic: $kdf_ic" _verbose "KDF len: $kdf_len" _password=$(tomb-kdb-pbkdf2 $kdf_salt $kdf_ic $kdf_len 2>/dev/null <<<$_password) ;; *) _failure "No suitable program for KDF ::1 program::." $pbkdf_hash unset _password return 1 ;; esac # key needs to be exhumed from an image elif [[ -r $TOMBKEYFILE && $(file $TOMBKEYFILE) =~ "JP.G" ]]; then if option_is_set -g; then # When using a GPG key, the tomb key is buried using a steganography password if option_is_set --tomb-pwd; then _password="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 tomb pass::" $_password else _password=$(ask_password "Insert password to exhume key from $imagefile") [[ $? != 0 ]] && { _warning "User aborted password dialog." return 1 } fi exhume_key $TOMBKEYFILE "$_password" unset _password else exhume_key $TOMBKEYFILE "$_password" fi fi gpg_decrypt "$_password" # Save decrypted contents into $TOMBSECRET ret="$?" _verbose "get_lukskey returns ::1::" $ret return $ret } # This function asks the user for the password to use the key it tests # it against the return code of gpg on success returns 0 and saves # the password in the global variable $TOMBPASSWORD ask_key_password() { [[ -z "$TOMBKEYFILE" ]] && { _failure "Internal error: ask_key_password() called before _load_key()." } [[ "$TOMBKEYFILE" = "cleartext" ]] && { _verbose "no password needed, using secret bytes from stdin" return 0 } if option_is_set -g; then _verbose "no password needed, using GPG key" get_lukskey return $? fi _message "A password is required to use key ::1 key::" $TOMBKEYFILE passok=0 tombpass="" if [[ -z $1 ]]; then for c in 1 2 3; do if [[ $c == 1 ]]; then tombpass=$(ask_password "Insert password to: $TOMBKEYFILE") else tombpass=$(ask_password "Insert password to: $TOMBKEYFILE (attempt $c)") fi [[ $? = 0 ]] || { _warning "User aborted password dialog." return 1 } get_lukskey "$tombpass" [[ $? = 0 ]] && { passok=1; _message "Password OK." break; } done else # if a second argument is present then the password is already known tombpass="$1" _verbose "ask_key_password with tombpass: ::1 tomb pass::" $tombpass # if sphinx mode is chosen, use the provided input # as master password to retrieve the actual password if option_is_set --sphx-user || option_is_set --sphx-host; then tombpass=$(sphinx_get_password "$tombpass") fi get_lukskey "$tombpass" [[ $? = 0 ]] && { passok=1; _message "Password OK." } fi [[ $passok == 1 ]] || return 1 TOMBPASSWORD=$tombpass return 0 } # call cryptsetup with arguments using the currently known secret # echo flags eliminate newline and disable escape (BSD_ECHO) _cryptsetup() { print -R -n - "$TOMBSECRET" | _sudo cryptsetup --type luks1 --key-file - ${@} return $? } # change tomb key password change_passwd() { local tmpnewkey lukskey c tombpass tombpasstmp _check_swap # Ensure swap is secure, if any _load_key # Try loading key from option -k and set TOMBKEYFILE { option_is_set -g } && { _message "Commanded to change GnuPG key for tomb key ::1 key::" $TOMBKEYFILE } || { _message "Commanded to change password for tomb key ::1 key::" $TOMBKEYFILE } _tmp_create tmpnewkey=$TOMBTMP if option_is_set --tomb-old-pwd; then local tomboldpwd="`option_value --tomb-old-pwd`" _verbose "tomb-old-pwd = ::1 old pass::" $tomboldpwd ask_key_password "$tomboldpwd" else ask_key_password fi [[ $? == 0 ]] || _failure "No valid password supplied." { option_is_set -g } && { _success "Changing GnuPG key for ::1 key file::" $TOMBKEYFILE } || { _success "Changing password for ::1 key file::" $TOMBKEYFILE } # Here $TOMBSECRET contains the key material in clear { option_is_set --tomb-pwd } && { local tombpwd="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 new pass::" $tombpwd gen_key "$tmpnewkey" "$tombpwd" } || { gen_key "$tmpnewkey" } { is_valid_key "${mapfile[$tmpnewkey]}" } || { _failure "Error: the newly generated keyfile does not seem valid." } # Copy the new key as the original keyfile name cp -f "${tmpnewkey}" $TOMBKEYFILE { option_is_set -g } && { _success "Your GnuPG key was successfully changed" } || { _success "Your passphrase was successfully updated." } return 0 } # takes care to encrypt a key # honored options: --kdf --tomb-pwd -o -g -r gen_key() { # $1 key file # $2 the password to use; if not set ask user # -o is the --cipher-algo to use (string taken by GnuPG) local algopt="`option_value -o`" local algo="${algopt:-AES256}" local gpgpass opt local recipients_opt typeset -a gpgopt local sphx_host_tmp local sphx_user_tmp # here user is prompted for key password tombpass="" tombpasstmp="" # remove sphinx opts not to mess with initial password prompt option_is_set --sphx-user && { sphx_user_tmp="$(option_value --sphx-user)" unset "OPTS[--sphx-user]" } option_is_set --sphx-host && { sphx_host_tmp="$(option_value --sphx-host)" unset "OPTS[--sphx-host]" } if option_is_set -g; then gpgopt=(--encrypt) if option_is_set -r || option_is_set -R; then typeset -a recipients if option_is_set -r; then recipients=(${(s:,:)$(option_value -r)}) recipients_opt="--recipient" else recipients=(${(s:,:)$(option_value -R)}) recipients_opt="--hidden-recipient" fi is_valid_recipients $recipients || { _failure "You set an invalid GPG ID." } _warning "You are going to encrypt a tomb key with ::1 nrecipients:: recipient(s)." ${#recipients} _warning "It is your responsibility to check these fingerprints." _warning "The fingerprints are:" for gpg_id in ${recipients[@]}; do _warning " `_gpg_fingerprint "$gpg_id"` :: `_gpg_uid "$gpg_id"`" done gpgopt+=(`_recipients_arg "$recipients_opt" $recipients`) else _message "No recipient specified, using default GPG key." gpgopt+=("--default-recipient-self") fi # Set gpg inputs and options gpgpass="$TOMBSECRET" opt='' else if [ "$2" = "" ]; then while true; do # 3 tries to write two times a matching password tombpass=`ask_password "Type the new password to secure your key"` if [[ $? != 0 ]]; then _failure "User aborted." fi if [ -z $tombpass ]; then _failure "You set empty password, which is not possible." fi tombpasstmp=$tombpass tombpass=`ask_password "Type the new password to secure your key (again)"` if [[ $? != 0 ]]; then _failure "User aborted." fi if [ "$tombpasstmp" = "$tombpass" ]; then break; fi unset tombpasstmp unset tombpass done else tombpass="$2" _verbose "gen_key takes tombpass from CLI argument: ::1 tomb pass::" $tombpass fi # if sphinx mode is chosen, use the provided input # as master password to generate the actual password if [[ ! -z $sphx_host_tmp ]] || [[ ! -z $sphx_user_tmp ]]; then OPTS[--sphx-user]=$sphx_user_tmp OPTS[--sphx-host]=$sphx_host_tmp unset sphx_user_tmp unset sphx_host_tmp tombpass=$(sphinx_set_password "$tombpass") if [[ $? != 0 ]]; then _failure "User aborted." fi fi header="" [[ $KDF == 1 ]] && { { option_is_set --kdf } && { # KDF is a new key strenghtening technique against brute forcing # see: https://github.com/dyne/Tomb/issues/82 itertime="`option_value --kdf`" # removing support of floating points because they can't be type checked well if [[ "$itertime" != <-> ]]; then unset tombpass unset tombpasstmp _warning "Wrong argument for --kdf: must be an integer number (iteration seconds)." _failure "Depending on the speed of machines using this tomb, use 1 to 10, or more" return 1 fi # --kdf takes one parameter: iter time (on present machine) in seconds local -i microseconds microseconds=$(( itertime * 1000000 )) _success "Using KDF, iteration time: ::1 microseconds::" $microseconds _message "generating salt" pbkdf2_salt=`tomb-kdb-pbkdf2-gensalt` _message "calculating iterations" pbkdf2_iter=`tomb-kdb-pbkdf2-getiter $microseconds` _message "encoding the password" # We use a length of 64bytes = 512bits (more than needed!?) tombpass=`tomb-kdb-pbkdf2 $pbkdf2_salt $pbkdf2_iter 64 <<<"${tombpass}"` header="_KDF_pbkdf2sha1_${pbkdf2_salt}_${pbkdf2_iter}_64\n" } } print $header >> "$1" # Set gpg inputs and options gpgpass="${tombpass}\n$TOMBSECRET" gpgopt=(--passphrase-fd 0 --symmetric --no-options) opt='-n' fi _tmp_create local tmpres=$TOMBTMP print $opt - "$gpgpass" \ | gpg --openpgp --force-mdc --cipher-algo ${algo} \ --batch --no-tty ${gpgopt} \ --status-fd 2 -o - --armor 2> $tmpres >> "$1" unset gpgpass # check result of gpg operation for i in ${(f)"$(cat $tmpres)"}; do _verbose "$i" done # print -n "${tombpass}" \ # | gpg --openpgp --force-mdc --cipher-algo ${algo} \ # --batch --no-options --no-tty --passphrase-fd 0 --status-fd 2 \ # -o - -c -a ${lukskey} TOMBPASSWORD="$tombpass" # Set global variable unset tombpass unset tombpasstmp } # prints an array of ciphers available in gnupg (to encrypt keys) list_gnupg_ciphers() { # On gpg1 and gpg2 line 10 always point to available ciphers. # Print those until the next section is found ciphers=(`gpg --version | awk ' BEGIN { ciphers=0 } NR==11 { gsub(/,/,""); sub(/^.*:/,""); print; ciphers=1; next } /^.*:/ { ciphers=0 } { if(ciphers==0) { next } else { gsub(/,/,""); print; } } '`) print "${ciphers}" return 1 } # Steganographic function to bury a key inside an image. # Requires steghide(1) to be installed bury_key() { _load_key # Try loading key from option -k and set TOMBKEY imagefile=$PARAM [[ "`file $imagefile`" =~ "JPEG" ]] || { _warning "Encode failed: ::1 image file:: is not a jpeg image." $imagefile return 1 } _success "Encoding key ::1 tomb key:: inside image ::2 image file::" $TOMBKEY $imagefile { option_is_set -g } && { _message "Using GnuPG Key ID" } || { _message "Please confirm the key password for the encoding" } # We ask the password and test if it is the same encoding the # base key, to insure that the same password is used for the # encryption and the steganography. This is a standard enforced # by Tomb, but it isn't strictly necessary (and having different # password would enhance security). Nevertheless here we prefer # usability. # However, steganography cannot be done with GPG key. Therefore, # if using a GPG key, we test if the user can decrypt the tomb # with its key and we ask for a steganography password. { option_is_set --tomb-pwd } && { ! option_is_set -g } && { local tombpwd="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 tomb pass::" $tombpwd ask_key_password "$tombpwd" } || { ask_key_password } [[ $? != 0 ]] && { _warning "Wrong password/GnuPG ID supplied." _failure "You shall not bury a key whose password is unknown to you." } if option_is_set -g && option_is_set --tomb-pwd; then TOMBPASSWORD="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 tomb pass::" $TOMBPASSWORD elif option_is_set -g; then tombpass="" tombpasstmp="" while true; do # 3 tries to write two times a matching password tombpass=`ask_password "Type a password to bury your key"` if [[ $? != 0 ]]; then _failure "User aborted." fi if [ -z $tombpass ]; then _failure "You set empty password, which is not possible." fi tombpasstmp=$tombpass tombpass=`ask_password "Type a password to bury your key (again)"` if [[ $? != 0 ]]; then _failure "User aborted." fi if [ "$tombpasstmp" = "$tombpass" ]; then break; fi unset tombpasstmp unset tombpass done TOMBPASSWORD="$tombpass" fi # We omit armor strings since having them as constants can give # ground to effective attacks on steganography print - "$TOMBKEY" | awk ' /^-----/ {next} /^Version/ {next} {print $0}' \ | steghide embed --embedfile - --coverfile ${imagefile} \ -p $TOMBPASSWORD -z 9 -e serpent cbc if [ $? != 0 ]; then _warning "Encoding error: steghide reports problems." res=1 else _success "Tomb key encoded succesfully into image ::1 image file::" $imagefile res=0 fi return $res } # mandatory 1st arg: the image file where key is supposed to be # optional 2nd arg: the password to use (same as key, internal use) # optional 3rd arg: the key where to save the result (- for stdout) exhume_key() { [[ -z $1 ]] && { _failure "Exhume failed, no image specified" } local imagefile="$1" # The image file where to look for the key local tombpass="$2" # (Optional) the password to use (internal use) local destkey="$3" # (Optional) the key file where to save the # result (- for stdout) local r=1 # Return code (default: fail) # write all messages to stderr to avoid polluting stdout _MSG_FD_OVERRIDE=2 # Ensure the image file is a readable JPEG [[ ! -r $imagefile ]] && { _failure "Exhume failed, image file not found: ::1 image file::" "${imagefile:-none}" } [[ ! $(file "$imagefile") =~ "JP.G" ]] && { _failure "Exhume failed: ::1 image file:: is not a jpeg image." $imagefile } # When a password is passed as argument then always print out # the exhumed key on stdout without further checks (internal use) [[ -n "$tombpass" ]] && { TOMBKEY=$(steghide extract -sf $imagefile -p $tombpass -xf -) [[ $? != 0 ]] && { _failure "Wrong password or no steganographic key found" } recover_key $TOMBKEY return 0 } # Ensure we have a valid destination for the key [[ -z $destkey ]] && { option_is_set -k } && destkey=$(option_value -k) [[ -z $destkey ]] && { destkey="-" # No key was specified: fallback to stdout _message "printing exhumed key on stdout" } # Bail out if destination exists, unless -f (force) was passed [[ $destkey != "-" && -s $destkey ]] && { _warning "File exists: ::1 tomb key::" $destkey { option_is_set -f } && { _warning "Use of --force selected: overwriting." rm -f $destkey } || { _warning "Make explicit use of --force to overwrite." _failure "Refusing to overwrite file. Operation aborted." } } _message "Trying to exhume a key out of image ::1 image file::" $imagefile { option_is_set --tomb-pwd } && { tombpass=$(option_value --tomb-pwd) _verbose "tomb-pwd = ::1 tomb pass::" $tombpass } || { [[ -n $TOMBPASSWORD ]] && tombpass=$TOMBPASSWORD } || { tombpass=$(ask_password "Insert password to exhume key from $imagefile") [[ $? != 0 ]] && { _warning "User aborted password dialog." return 1 } } # Extract the key from the image steghide extract -sf $imagefile -p ${tombpass} -xf $destkey r=$? # Report to the user [[ "$destkey" = "-" ]] && destkey="stdout" [[ $r == 0 ]] && { _success "Key succesfully exhumed to ::1 key::." $destkey } || { _warning "Nothing found in ::1 image file::" $imagefile } unset _MSG_FD_OVERRIDE return $r } # Steganographic function to transform a key into harmless-looking text # using a cipher # Requires cloakify to be installed # # mandatory 1st arg: the cipher to use # optional 2nd arg: the output file where to save the result (none for stdout) cloakify_key() { _load_key # Try loading key from option -k and set TOMBKEY local cipher="$1" # The cipher to use local destfile="$2" # (Optional) the output file where to save the # result (none for stdout) _success "Encoding key ::1 tomb key:: using cipher ::2 cipher file::" $TOMBKEYFILE $cipher # Ensure we have a valid destination for the cloaked key [[ -z $destfile ]] && { destfile="/dev/stdout" # No file was specified: fallback to stdout _message "printing cloaked key on stdout" } # Bail out if destination exists, unless -f (force) was passed [[ $destfile != "/dev/stdout" && -s $destfile ]] && { _warning "File exists: ::1 output file::" $destfile { option_is_set -f } && { _warning "Use of --force selected: overwriting." rm -f $destfile } || { _warning "Make explicit use of --force to overwrite." _failure "Refusing to overwrite file. Operation aborted." } } # Cipher the key cloakify $TOMBKEYFILE $cipher >$destfile if [ $? != 0 ]; then _warning "Encoding error: cloakify reports problems." res=1 else _success "Tomb key encoded succesfully" res=0 fi return $res } # mandatory 1st arg: the text file where key is supposed to be # mandatory 2nd arg: the cipher to use # optional 3rd arg: the key where to save the result (none for stdout) decloakify_key() { [[ -z $1 ]] && { _failure "Uncloak failed, no text file specified" } [[ -z $2 ]] && { _failure "Uncloak failed, no cipher file specified" } local textfile="$1" # The text file where to look for the key local cipher="$2" # The cipher to use local destkey="$3" # (Optional) the key file where to save the # result (none for stdout) local r=1 # Return code (default: fail) # write all messages to stderr to avoid polluting stdout _MSG_FD_OVERRIDE=2 # Ensure the text file is readable [[ ! -r $textfile ]] && { _failure "Uncloak failed, text file not found: ::1 text file::" "${textfile:-none}" } # Ensure the cipher file is readable [[ ! -r $cipher ]] && { _failure "Uncloak failed, cipher file not found: ::1 cipher file::" "${cipher:-none}" } # Ensure we have a valid destination for the key [[ -z $destkey ]] && { option_is_set -k } && destkey=$(option_value -k) [[ -z $destkey ]] && { destkey="/dev/stdout" # No key was specified: fallback to stdout _message "printing uncloaked key on stdout" } # Bail out if destination exists, unless -f (force) was passed [[ $destkey != "/dev/stdout" && -s $destkey ]] && { _warning "File exists: ::1 tomb key::" $destkey { option_is_set -f } && { _warning "Use of --force selected: overwriting." rm -f $destkey } || { _warning "Make explicit use of --force to overwrite." _failure "Refusing to overwrite file. Operation aborted." } } # Extract the key from the text file decloakify $textfile $cipher >$destkey r=$? # Report to the user [[ "$destkey" = "/dev/stdout" ]] && destkey="stdout" [[ $r == 0 ]] && { _success "Key succesfully uncloaked to ::1 key::." $destkey } || { _warning "Nothing found in ::1 text file::" $textfile } unset _MSG_FD_OVERRIDE return $r } # Produces a printable image of the key contents so a backup on paper # can be made and hidden in books etc. engrave_key() { _load_key # Try loading key from option -k and set TOMBKEYFILE local keyname=$(basename $TOMBKEYFILE) local pngname="$keyname.qr.png" _success "Rendering a printable QRCode for key: ::1 tomb key file::" $TOMBKEYFILE # we omit armor strings to save space awk '/^-----/ {next}; /^Version/ {next}; {print $0}' $TOMBKEYFILE \ | qrencode --size 4 --level H --casesensitive -o $pngname [[ $? != 0 ]] && { _failure "QREncode reported an error." } _success "Operation successful:" # TODO: only if verbose and/or not silent ls -lh $pngname file $pngname } # }}} - Key handling # {{{ Create # Since version 1.5.3, tomb creation is a three-step process that replaces create_tomb(): # # * dig a .tomb (the large file) using /dev/urandom (takes some minutes at least) # # * forge a .key (the small file) using /dev/random (good entropy needed) # # * lock the .tomb file with the key, binding the key to the tomb (requires dm_crypt format) # Step one - Dig a tomb # # Synopsis: dig_tomb /path/to/tomb -s sizemebibytes # # It will create an empty file to be formatted as a loopback # filesystem. Initially the file is filled with random data taken # from /dev/urandom to improve overall tomb's security and prevent # some attacks aiming at detecting how much data is in the tomb, or # which blocks in the filesystem contain that data. dig_tomb() { # $1 arg is path to tomb # Require the specification of the size of the tomb (-s) in MiB local -i tombsize=$(option_value -s) _message "Commanded to dig tomb ::1 tomb path::" $tombpath [[ ! -z $1 ]] || _failure "Missing path to tomb" [[ -n "$tombsize" ]] || _failure "Size argument missing, use -s" [[ $tombsize == <-> ]] || _failure "Size must be an integer (mebibytes)" [[ $tombsize -ge 10 ]] || _failure "Tombs can't be smaller than 10 mebibytes" [[ -e $1 ]] && { _warning "A tomb exists already. I'm not digging here:" ls -lh $1 return 1 } _success "Creating a new tomb in ::1 tomb path::" $1 _message "Generating ::1 tomb file:: of ::2 size::MiB" $1 $tombsize touch "$1" [[ $? = 0 ]] || { _warning "Error creating the tomb ::1 tomb path::" $1 _failure "Operation aborted." } # Ensure that file permissions are safe even if interrupted [[ -n $SUDO_USER ]] && chown ${_UID}:${_GID} "$1" chmod 0600 $1 _verbose "Data dump using ::1:: from /dev/urandom" ${DD[1]} ${=DD} if=/dev/urandom bs=1048576 count=$tombsize of=$1 ls -lh "$1" _success "Done digging ::1 tomb name::" $1 _message "Your tomb is not yet ready, you need to forge a key and lock it:" _message "tomb forge ::1 tomb path::.key" $1 _message "tomb lock ::1 tomb path:: -k ::1 tomb path::.key" $1 return 0 } # Step two -- Create a detached key to lock a tomb with # # Synopsis: forge_key [destkey|-k destkey] [-o cipher] [-r|-R gpgid] # # Arguments: # -k path to destination keyfile # -o Use an alternate algorithm # -r GPG recipients to be used # forge_key() { # can be specified both as simple argument or using -k local destkey="$1" { option_is_set -k } && { destkey=$(option_value -k) } local algo="AES256" # Default encryption algorithm [[ -z "$destkey" ]] && { _failure "A filename needs to be specified using -k to forge a new key." } # _message "Commanded to forge key ::1 key::" $destkey _check_swap # Ensure the available memory is safe to use # Ensure GnuPG won't exit with an error before first run local gpghome=${GNUPGHOME:-$HOME/.gnupg} [[ -r $gpghome/pubring.gpg ]] || { mkdir -p -m 0700 $gpghome touch $gpghome/pubring.gpg } # Do not overwrite any files accidentally [[ -r "$destkey" ]] && { ls -lh $destkey _failure "Forging this key would overwrite an existing file. Operation aborted." } touch $destkey [[ $? == 0 ]] || { _warning "Cannot generate encryption key." _failure "Operation aborted." } chmod 0600 $destkey # Update algorithm if it was passed on the command line with -o { option_is_set -o } && algopt="$(option_value -o)" [[ -n "$algopt" ]] && algo=$algopt _message "Commanded to forge key ::1 key:: with cipher algorithm ::2 algorithm::" \ $destkey $algo [[ $KDF == 1 ]] && { ! option_is_set -g } && { _message "Using KDF to protect the key password (`option_value --kdf` rounds)" } TOMBKEYFILE="$destkey" # Set global variable _warning "This operation takes time. Keep using this computer on other tasks." _warning "Once done you will be asked to choose a password for your tomb." _warning "To make it faster you can move the mouse around." _warning "If you are on a server, you can use an Entropy Generation Daemon." # Use /dev/urandom as the entropy source, unless --use-random is specified local random_source=/dev/urandom { option_is_set --use-random } && random_source=/dev/random _verbose "Data dump using ::1:: from ::2 source::" ${DD[1]} $random_source TOMBSECRET=$(${=DD} bs=1 count=512 if=$random_source) [[ $? == 0 ]] || { _warning "Cannot generate encryption key." _failure "Operation aborted." } # Here the global variable TOMBSECRET contains the naked secret { option_is_set -g } && { _success "Using GnuPG key(s) to encrypt your key: ::1 tomb key::" $TOMBKEYFILE } || { _success "Choose the password of your key: ::1 tomb key::" $TOMBKEYFILE } _message "(You can also change it later using 'tomb passwd'.)" # _user_file $TOMBKEYFILE tombname="$TOMBKEYFILE" # XXX ??? # the gen_key() function takes care of the new key's encryption { option_is_set --tomb-pwd } && { local tombpwd="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 new pass::" $tombpwd gen_key $TOMBKEYFILE "$tombpwd" } || { gen_key $TOMBKEYFILE } # load the key contents (set global variable) TOMBKEY="${mapfile[$TOMBKEYFILE]}" # this does a check on the file header is_valid_key $TOMBKEY || { _warning "The key does not seem to be valid." _warning "Dumping contents to screen:" print "${mapfile[$TOMBKEY]}" _warning "--" rm -f ${TOMBKEYFILE} _failure "Operation aborted." } [[ -n $SUDO_USER ]] && chown ${_UID}:${_GID} "$TOMBKEYFILE" _message "Done forging ::1 key file::" $TOMBKEYFILE _success "Your key is ready:" ls -lh $TOMBKEYFILE } # Step three -- Lock tomb # # Synopsis: tomb_lock file.tomb file.tomb.key [-o cipher] [-r gpgid] # # Lock the given tomb with the given key file, in fact formatting the # loopback volume as a LUKS device. # Default cipher 'aes-xts-plain64'can be overridden with -o lock_tomb_with_key() { # old default was aes-cbc-essiv:sha256 # Override with -o # for more alternatives refer to cryptsetup(8) local cipher="aes-xts-plain64" local tombpath="$1" # First argument is the path to the tomb [[ -n $tombpath ]] || { _warning "No tomb specified for locking." _warning "Usage: tomb lock file.tomb -k file.tomb.key" return 1 } is_valid_tomb $tombpath _message "Commanded to lock tomb ::1 tomb file::" $TOMBFILE [[ -f $TOMBPATH ]] || { _failure "There is no tomb here. You have to dig it first." } _verbose "Tomb found: ::1 tomb path::" $TOMBPATH local filesystem=ext4 option_is_set --filesystem && { filesystem=`option_value --filesystem` case $filesystem in ext3|ext4) ;; btrfs) ;; *) _failure "Filesystem not supported: ::1 filesystem::" $filesystem return 1 ;; esac # TODO: check validity, only ext3 or 4 or btrfs support _message "Selected filesystem type $filesystem." } lo_mount $TOMBPATH _verbose "Loop mounted on ::1 mount point::" $TOMBLOOP _message "Checking if the tomb is empty (we never step on somebody else's bones)." _sudo cryptsetup isLuks ${TOMBLOOP} if [ $? = 0 ]; then # is it a LUKS encrypted nest? then bail out and avoid reformatting it _warning "The tomb was already locked with another key." _failure "Operation aborted. I cannot lock an already locked tomb. Go dig a new one." else _message "Fine, this tomb seems empty." fi _load_key # Try loading key from option -k and set TOMBKEYFILE # the encryption cipher for a tomb can be set when locking using -c { option_is_set -o } && algopt="$(option_value -o)" [[ -n "$algopt" ]] && cipher=$algopt _message "Locking using cipher: ::1 cipher::" $cipher # get the pass from the user and check it if option_is_set --tomb-pwd; then tomb_pwd="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 tomb pass::" $tomb_pwd ask_key_password "$tomb_pwd" else ask_key_password fi [[ $? == 0 ]] || _failure "No valid password supplied." _success "Locking ::1 tomb file:: with ::2 tomb key file::" $TOMBFILE $TOMBKEYFILE _message "Formatting Luks mapped device." _cryptsetup --batch-mode \ --cipher ${cipher} --hash sha512 --key-size 512 --key-slot 0 \ luksFormat ${TOMBLOOP} [[ $? == 0 ]] || { _warning "cryptsetup luksFormat returned an error." _failure "Operation aborted." } _cryptsetup --cipher ${cipher} --hash sha512 luksOpen ${TOMBLOOP} tomb.tmp [[ $? == 0 ]] || { _warning "cryptsetup luksOpen returned an error." _failure "Operation aborted." } _message "Formatting your Tomb with $filesystem filesystem." case $filesystem in ext3|ext4) _sudo mkfs.${filesystem} -q -F -j -L $TOMBNAME /dev/mapper/tomb.tmp ;; btrfs) # TODO: cover with test _sudo mkfs.${filesystem} -q -L $TOMBNAME /dev/mapper/tomb.tmp ;; esac [[ $? == 0 ]] || { _warning "Tomb format returned an error." _sudo cryptsetup luksClose tomb.tmp _failure "Your tomb ::1 tomb file:: may be corrupted." $TOMBFILE } # Sync _sudo cryptsetup luksClose tomb.tmp _message "Done locking ::1 tomb name:: using Luks dm-crypt ::2 cipher::" $TOMBNAME $cipher _success "Your tomb is ready in ::1 tomb path:: and secured with key ::2 tomb key::" \ $TOMBPATH $TOMBKEYFILE return 0 } # This function changes the key that locks a tomb change_tomb_key() { local tombkey="$1" # Path to the tomb's key file local tombpath="$2" # Path to the tomb _message "Commanded to reset key for tomb ::1 tomb path::" $tombpath [[ -z "$tombpath" ]] && { _warning "Command 'setkey' needs two arguments: the old key file and the tomb." _warning "I.e: tomb -k new.tomb.key old.tomb.key secret.tomb" _failure "Execution aborted." } _check_swap is_valid_tomb $tombpath lo_mount $TOMBPATH _sudo cryptsetup isLuks ${TOMBLOOP} # is it a LUKS encrypted nest? we check one more time [[ $? == 0 ]] || { _failure "Not a valid LUKS encrypted volume: ::1 volume::" $TOMBPATH } _load_key $tombkey # Try loading given key and set TOMBKEY # TOMBKEYFILE local oldkey=$TOMBKEY local oldkeyfile=$TOMBKEYFILE # we have everything, prepare to mount _success "Changing lock on tomb ::1 tomb name::" $TOMBNAME _message "Old key: ::1 old key::" $oldkeyfile # load the old key if option_is_set --tomb-old-pwd; then tomb_old_pwd="`option_value --tomb-old-pwd`" _verbose "tomb-old-pwd = ::1 old pass::" $tomb_old_pwd ask_key_password "$tomb_old_pwd" else ask_key_password fi [[ $? == 0 ]] || { _failure "No valid password supplied for the old key." } old_secret=$TOMBSECRET # luksOpen the tomb (not really mounting, just on the loopback) print -R -n - "$old_secret" | _sudo cryptsetup --key-file - \ luksOpen ${TOMBLOOP} ${TOMBMAPPER} [[ $? == 0 ]] || _failure "Unexpected error in luksOpen." _load_key # Try loading new key from option -k and set TOMBKEYFILE _message "New key: ::1 key file::" $TOMBKEYFILE if option_is_set --tomb-pwd; then tomb_new_pwd="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 tomb pass::" $tomb_new_pwd ask_key_password "$tomb_new_pwd" else ask_key_password fi [[ $? == 0 ]] || { _failure "No valid password supplied for the new key." } _tmp_create tmpnewkey=$TOMBTMP print -R -n - "$TOMBSECRET" >> $tmpnewkey print -R -n - "$old_secret" | _sudo cryptsetup --key-file - \ luksChangeKey "$TOMBLOOP" "$tmpnewkey" [[ $? == 0 ]] || _failure "Unexpected error in luksChangeKey." _sudo cryptsetup luksClose "${TOMBMAPPER}" || _failure "Unexpected error in luksClose." _success "Succesfully changed key for tomb: ::1 tomb file::" $TOMBFILE _message "The new key is: ::1 new key::" $TOMBKEYFILE return 0 } # }}} - Creation # {{{ Open _update_control_file() { # make sure a control file exists, gives it user ownership # and replaces it with new contents # stdin = contents # $1 = path to control file # $2 = contents [[ -z $2 ]] && return 1 _sudo touch "$1" _sudo chown ${_UID}:${_GID} "$1" print "$2" > "$1" _verbose "updated control file $1 = $2" } _detect_filesystem() { local device=$1 _verbose "detecting filesystem of ::1 device::" $device print "`lsblk -in -o FSTYPE $device`" } # $1 = tombfile $2(optional) = mountpoint mount_tomb() { [[ -n "$1" ]] || _failure "No tomb name specified for opening." _message "Commanded to open tomb ::1 tomb name::" $1 _check_swap is_valid_tomb $1 _track_stat "$TOMBPATH" _load_key # Try loading new key from option -k and set TOMBKEYFILE tombmount="$2" [[ -z $tombmount ]] && { tombmount=/media/$TOMBNAME [[ -d /media ]] || { # no /media found, adopting /run/media/$USER (udisks2 compat) tombmount=/run/media/$_USER/$TOMBNAME } _message "Mountpoint not specified, using default: ::1 mount point::" $tombmount } _success "Opening ::1 tomb file:: on ::2 mount point::" $TOMBNAME $tombmount # check if the mountpoint is already used mounted_tombs=(`list_tomb_mounts`) for t in ${mounted_tombs}; do usedmount=${t[(ws:;:)2]} [[ "$usedmount" == "$tombmount" ]] && _failure "Mountpoint already in use: ::1 mount point::" $tombmount done lo_mount $TOMBPATH _sudo cryptsetup isLuks ${TOMBLOOP} || { # is it a LUKS encrypted nest? see cryptsetup(1) _failure "::1 tomb file:: is not a valid Luks encrypted storage file." $TOMBFILE } _message "This tomb is a valid LUKS encrypted device." luksdump="`_sudo cryptsetup luksDump ${TOMBLOOP}`" tombdump=(`print $luksdump | awk ' /^Cipher name/ {print $3} /^Cipher mode/ {print $3} /^Hash spec/ {print $3}'`) _message "Cipher is \"::1 cipher::\" mode \"::2 mode::\" hash \"::3 hash::\"" $tombdump[1] $tombdump[2] $tombdump[3] slotwarn=`print $luksdump | awk ' BEGIN { zero=0 } /^Key slot 0/ { zero=1 } /^Key slot.*ENABLED/ { if(zero==1) print "WARN" }'` [[ "$slotwarn" == "WARN" ]] && { _warning "Multiple key slots are enabled on this tomb. Beware: there can be a backdoor." } _verbose "Tomb key: ::1 key file::" $TOMBKEYFILE # take the name only, strip extensions _verbose "Tomb name: ::1 tomb name:: (to be engraved)" $TOMBNAME { option_is_set --tomb-pwd } && { ! option_is_set -g } && { tomb_pwd="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 tomb pass::" $tomb_pwd ask_key_password "$tomb_pwd" } || { ask_key_password } [[ $? == 0 ]] || _failure "No valid password supplied." _cryptsetup luksOpen ${TOMBLOOP} ${TOMBMAPPER} [[ $? = 0 ]] || { _failure "Failure mounting the encrypted file." } # preserve the loopdev after exit lo_preserve "$TOMBLOOP" # array: [ cipher, keysize, loopdevice ] tombstat=(`_sudo cryptsetup status ${TOMBMAPPER} | awk ' /cipher:/ {print $2} /keysize:/ {print $2} /device:/ {print $2}'`) _success "Success unlocking tomb ::1 tomb name::" $TOMBNAME _verbose "Key size is ::1 size:: for cipher ::2 cipher::" $tombstat[2] $tombstat[1] filesystem=`_detect_filesystem /dev/mapper/${TOMBMAPPER}` _message "Filesystem detected: ::1 filesystem::" $filesystem # TODO: check if FS is supported, else close luks and loop _verbose "Tomb engraved as ::1 tomb name::" $TOMBNAME _message "Checking filesystem via ::1::" $tombstat[3] case $filesystem in ext3|ext4) _sudo fsck -p -C0 /dev/mapper/${TOMBMAPPER} # TODO: btrfs filesystem label [<device>|<mount_point>] [<newlabel>] _sudo tune2fs -L $TOMBNAME /dev/mapper/${TOMBMAPPER} > /dev/null ;; btrfs) _sudo btrfs check /dev/mapper/${TOMBMAPPER} _sudo btrfs filesystem label /dev/mapper/${TOMBMAPPER} ${TOMBNAME} ;; esac # we need root from here on _sudo mkdir -p $tombmount # Default mount options are overridden with the -o switch { option_is_set -o } && { local oldmountopts=$MOUNTOPTS MOUNTOPTS="$(option_value -o)" } # TODO: safety check MOUNTOPTS # safe_mount_options && _sudo mount -o $MOUNTOPTS /dev/mapper/${TOMBMAPPER} ${tombmount} # Clean up if the mount failed [[ $? == 0 ]] || { _warning "Error mounting ::1 mapper:: on ::2 tombmount::" $TOMBMAPPER $tombmount [[ $oldmountopts != $MOUNTOPTS ]] && \ _warning "Are mount options '::1 mount options::' valid?" $MOUNTOPTS # TODO: move cleanup to _endgame() [[ -d $tombmount ]] && _sudo rmdir $tombmount [[ -e /dev/mapper/$TOMBMAPPER ]] && _sudo cryptsetup luksClose $TOMBMAPPER # The loop is taken care of in _endgame() _failure "Cannot mount ::1 tomb name::" $TOMBNAME } _success "Success opening ::1 tomb file:: on ::2 mount point::" $TOMBFILE $tombmount local tombtty tombhost tombuid tombuser # print out when it was opened the last time, by whom and where [[ -r ${tombmount}/.last ]] && { tombsince=$(_cat ${tombmount}/.last) tombsince=$(date --date=@$tombsince +%c) tombtty=$(_cat ${tombmount}/.tty) tombhost=$(_cat ${tombmount}/.host) tomblast=$(_cat ${tombmount}/.last) tombuid=$(_cat ${tombmount}/.uid | tr -d ' ') tombuser=`_get_username $tombuid` _message "Last visit by ::1 user::(::2 tomb build::) from ::3 tty:: on ::4 host::" $tombuser $tombuid $tombtty $tombhost _message "on date ::1 date::" $tombsince } # write down the UID and TTY that opened the tomb _update_control_file ${tombmount}/.uid $_UID _update_control_file ${tombmount}/.tty $_TTY # also the hostname _update_control_file ${tombmount}/.host `hostname` # and the "last time opened" information # in minutes since 1970, this is printed at next open _update_control_file ${tombmount}/.last `date +%s` # human readable: date --date=@"`cat .last`" +%c # process bind-hooks (mount -o bind of directories) # and exec-hooks (execute on open) option_is_set -n || { exec_safe_bind_hooks ${tombmount} exec_safe_func_hooks open ${tombmount} } # Changes ownership to current user. This facilitates a lot # usability by single users. If a Tomb is "multiuser" and contains # ACL "by convention" using UNIX ownership that needs to be # preserved then this behavior can be deactivated using -p option_is_set -p || _sudo chown -R ${_UID}:${_GID} ${tombmount} return 0 } ## HOOKS EXECUTION # # Execution of code inside a tomb may present a security risk, e.g., # if the tomb is shared or compromised, an attacker could embed # malicious code. When in doubt, open the tomb with the -n switch in # order to skip this feature and verify the files mount-hooks and # bind-hooks inside the tomb yourself before letting them run. # Mount files and directories from the tomb to the current user's HOME. # # Synopsis: exec_safe_bind_hooks /path/to/mounted/tomb # # This can be a security risk if you share tombs with untrusted people. # In that case, use the -n switch to turn off this feature. exec_safe_bind_hooks() { local mnt="$1" # First argument is the mount point of the tomb # Default mount options are overridden with the -o switch [[ -n ${(k)OPTS[-o]} ]] && MOUNTOPTS=${OPTS[-o]} # No HOME set? Note: this should never happen again. [[ -z $HOME ]] && { _warning "How pitiful! A tomb, and no HOME." return 1 } [[ -z $mnt || ! -d $mnt ]] && { _warning "Cannot exec bind hooks without a mounted tomb." return 1 } [[ -r "$mnt/bind-hooks" ]] || { _verbose "bind-hooks not found in ::1 mount point::" $mnt return 0 } typeset -Al maps # Maps of files and directories to mount typeset -al mounted # Track already mounted files and directories # better parsing for bind hooks checks for two separated words on # each line, using zsh word separator array subscript _bindhooks="${mapfile[${mnt}/bind-hooks]}" for h in ${(f)_bindhooks}; do s="${h[(w)1]}" d="${h[(w)2]}" [[ -z $s ]] && { _warning "bind-hooks file is broken"; return 1 } [[ -z $d ]] && { _warning "bind-hooks file is broken"; return 1 } maps+=($s $d) _verbose "bind-hook found: $s -> $d" done unset _bindhooks for dir in ${(k)maps}; do [[ "${dir[1]}" == "/" || "${dir[1,2]}" == ".." ]] && { _warning "bind-hooks map format: local/to/tomb local/to/\$HOME" continue } [[ "${${maps[$dir]}[1]}" == "/" || "${${maps[$dir]}[1,2]}" == ".." ]] && { _warning "bind-hooks map format: local/to/tomb local/to/\$HOME. Rolling back" for dir in ${mounted}; do _sudo umount $dir; done return 0 } if [[ ! -r "$HOME/${maps[$dir]}" ]]; then _warning "bind-hook target not existent, skipping ::1 home::/::2 subdir::" $HOME ${maps[$dir]} elif [[ ! -r "$mnt/$dir" ]]; then _warning "bind-hook source not found in tomb, skipping ::1 mount point::/::2 subdir::" $mnt $dir else _sudo mount -o bind,$MOUNTOPTS $mnt/$dir $HOME/${maps[$dir]} \ && mounted+=("$HOME/${maps[$dir]}") fi done } # Execute automated actions configured in the tomb. # # Synopsis: exec_safe_func_hooks /path/to/mounted/tomb # # If an executable file named 'exec-hooks' is found inside the tomb, # run it as a user. This might need a dialog for security on what is # being run, however we expect you know well what is inside your tomb. # If you're mounting an untrusted tomb, be safe and use the -n switch # to verify what it would run if you let it. This feature opens the # possibility to make encrypted executables. exec_safe_func_hooks() { local mnt mnt="$2" # Only run if post-hooks has the executable bit set [[ -x $mnt/exec-hooks ]] && { _success "Exec hook: ::1 exec hook:: ::2 action::" \ "${mnt}/exec-hooks" "$1" # here call two actions: open or close. Synopsis: # $1 $2 $3 $4 $5 # open "$tombmount" # close "$tombmount" "$tombname" "$tombloop" "$TOMBMAPPER" $mnt/exec-hooks "$1" "$2" "$3" "$4" "$5" return $? } return 0 } # }}} - Tomb open # {{{ List # list all tombs mounted in a readable format # $1 is optional, to specify a tomb list_tombs() { local tombname tombmount tombfs tombfsopts tombloop local ts tombtot tombused tombavail tombpercent tombp tombsince local tombtty tombhost tombuid tombuser # list all open tombs mounted_tombs=(`list_tomb_mounts $1`) [[ ${#mounted_tombs} == 0 ]] && { _failure "I can't see any ::1 status:: tomb, may they all rest in peace." ${1:-open} } for t in ${mounted_tombs}; do mapper=`basename ${t[(ws:;:)1]}` tombname=${t[(ws:;:)5]} tombmount=${t[(ws:;:)2]} tombfs=${t[(ws:;:)3]} tombfsopts=${t[(ws:;:)4]} tombloop=${mapper[(ws:.:)4]} # calculate tomb size ts=`df -hP /dev/mapper/$mapper | awk "/mapper/"' { print $2 ";" $3 ";" $4 ";" $5 }'` tombtot=${ts[(ws:;:)1]} tombused=${ts[(ws:;:)2]} tombavail=${ts[(ws:;:)3]} tombpercent=${ts[(ws:;:)4]} tombp=${tombpercent%%%} # obsolete way to get the last open date from /dev/mapper # which doesn't work when tomb filename contain dots # tombsince=`date --date=@${mapper[(ws:.:)3]} +%c` # find out who opens it from where [[ -r ${tombmount}/.tty ]] && { tombsince=$(_cat ${tombmount}/.last) tombsince=$(date --date=@$tombsince +%c) tombtty=$(_cat ${tombmount}/.tty) tombhost=$(_cat ${tombmount}/.host) tombuid=$(_cat ${tombmount}/.uid | tr -d ' ') tombuser=`_get_username $tombuid` } { option_is_set --get-mountpoint } && { print $tombmount; continue } _message "::1 tombname:: open on ::2 tombmount:: using ::3 tombfsopts::" \ $tombname $tombmount $tombfsopts _verbose "::1 tombname:: /dev/::2 tombloop:: device mounted (detach with losetup -d)" $tombname $tombloop _message "::1 tombname:: open since ::2 tombsince::" $tombname $tombsince [[ -z "$tombtty" ]] || { _message "::1 tombname:: open by ::2 tombuser:: from ::3 tombtty:: on ::4 tombhost::" \ $tombname $tombuser $tombtty $tombhost } _message "::1 tombname:: size ::2 tombtot:: of which ::3 tombused:: (::5 tombpercent::%) is used: ::4 tombavail:: free " \ $tombname $tombtot $tombused $tombavail $tombpercent [[ ${tombp} -ge 90 ]] && { _warning "::1 tombname:: warning: your tomb is almost full!" $tombname } # Now check hooks mounted_hooks=(`list_tomb_binds $tombname $tombmount`) for h in ${mounted_hooks}; do _message "::1 tombname:: hooks ::2 hookdest::" \ $tombname ${h[(ws:;:)2]} done done return 0 } # Print out an array of mounted tombs (internal use) # Format is semi-colon separated list of attributes # if 1st arg is supplied, then list only that tomb # # String positions in the semicolon separated array: # # 1. full mapper path # # 2. mountpoint # # 3. filesystem type # # 4. mount options # # 5. tomb name list_tomb_mounts() { [[ -z "$1" ]] && { # list all open tombs _sudo findmnt -rvo SOURCE,TARGET,FSTYPE,OPTIONS,LABEL \ | awk ' BEGIN { main="" } /^\/dev\/mapper\/tomb/ { if(main==$1) next; print $1 ";" $2 ";" $3 ";(" $4 ");[" $5 "]" main=$1 } ' } || { # list a specific tomb # add square parens if not present (detection) local tname if [[ "${1[1]}" = "[" ]]; then tname="$1" else tname="[$1]"; fi _sudo findmnt -rvo SOURCE,TARGET,FSTYPE,OPTIONS,LABEL \ | awk -vtomb="$tname" ' BEGIN { main="" } /^\/dev\/mapper\/tomb/ { if("["$5"]"!=tomb) next; if(main==$1) next; print $1 ";" $2 ";" $3 ";(" $4 ");[" $5 "]" main=$1 } ' } } # list_tomb_binds # print out an array of mounted bind hooks (internal use) # format is semi-colon separated list of attributes # needs two arguments: name of tomb whose hooks belong # mount tomb list_tomb_binds() { [[ -z "$2" ]] && { _failure "Internal error: list_tomb_binds called without argument." } # much simpler than the crazy from before # in fact, the second parameter is now redundant # as we only need the tomb name # note that this code assumes that the tomb name is provided in square brackets _sudo findmnt -ro SOURCE,TARGET,FSTYPE,OPTIONS,LABEL \ | grep -F "/dev/mapper/tomb" \ | awk -vpattern="$1" ' BEGIN { } { if("["$5"]"!=pattern) next; if(index($1,"[")==0) next; gsub("[[][^]]*[]]","",$1); print $1 ";" $2 ";" $3 ";(" $4 ");[" $5 "]" } ' } # }}} - Tomb list # {{{ Index and search # index files in all tombs for search # $1 is optional, to specify a tomb index_tombs() { { command -v updatedb 1>/dev/null 2>/dev/null } || { _failure "Cannot index tombs on this system: updatedb (mlocate) not installed." } updatedbver=`updatedb --version | grep '^updatedb'` [[ "$updatedbver" =~ "GNU findutils" ]] && { _warning "Cannot use GNU findutils for index/search commands." } [[ "$updatedbver" =~ "mlocate" ]] || { _failure "Index command needs 'mlocate' to be installed." } _verbose "$updatedbver" mounted_tombs=(`list_tomb_mounts $1`) [[ ${#mounted_tombs} == 0 ]] && { # Considering one tomb [[ -n "$1" ]] && { _failure "There seems to be no open tomb engraved as [::1::]" $1 } # Or more _failure "I can't see any open tomb, may they all rest in peace." } _success "Creating and updating search indexes." # start the LibreOffice document converter if installed { command -v unoconv 1>/dev/null 2>/dev/null } && { unoconv -l 2>/dev/null & _verbose "unoconv listener launched." sleep 1 } for t in ${mounted_tombs}; do mapper=`basename ${t[(ws:;:)1]}` tombname=${t[(ws:;:)5]} tombmount=${t[(ws:;:)2]} [[ -r ${tombmount}/.noindex ]] && { _message "Skipping ::1 tomb name:: (.noindex found)." $tombname continue } _message "Indexing ::1 tomb name:: filenames..." $tombname updatedb -l 0 -o ${tombmount}/.updatedb -U ${tombmount} # here we use swish to index file contents [[ $SWISH == 1 ]] && { _message "Indexing ::1 tomb name:: contents..." $tombname rm -f ${tombmount}/.swishrc _message "Generating a new swish-e configuration file: ::1 swish conf::" ${tombmount}/.swishrc cat <<EOF > ${tombmount}/.swishrc # index directives DefaultContents TXT* IndexDir $tombmount IndexFile $tombmount/.swish # exclude images FileRules filename regex /\.jp.?g/i FileRules filename regex /\.png/i FileRules filename regex /\.gif/i FileRules filename regex /\.tiff/i FileRules filename regex /\.svg/i FileRules filename regex /\.xcf/i FileRules filename regex /\.eps/i FileRules filename regex /\.ttf/i # exclude audio FileRules filename regex /\.mp3/i FileRules filename regex /\.ogg/i FileRules filename regex /\.wav/i FileRules filename regex /\.mod/i FileRules filename regex /\.xm/i # exclude video FileRules filename regex /\.mp4/i FileRules filename regex /\.avi/i FileRules filename regex /\.ogv/i FileRules filename regex /\.ogm/i FileRules filename regex /\.mkv/i FileRules filename regex /\.mov/i FileRules filename regex /\.flv/i FileRules filename regex /\.webm/i # exclude system FileRules filename is ok FileRules filename is lock FileRules filename is control FileRules filename is status FileRules filename is proc FileRules filename is sys FileRules filename is supervise FileRules filename regex /\.asc$/i FileRules filename regex /\.gpg$/i # pdf and postscript FileFilter .pdf pdftotext "'%p' -" FileFilter .ps ps2txt "'%p' -" # compressed files FileFilterMatch lesspipe "%p" /\.tgz$/i FileFilterMatch lesspipe "%p" /\.zip$/i FileFilterMatch lesspipe "%p" /\.gz$/i FileFilterMatch lesspipe "%p" /\.bz2$/i FileFilterMatch lesspipe "%p" /\.Z$/ # spreadsheets FileFilterMatch unoconv "-d spreadsheet -f csv --stdout %P" /\.xls.*/i FileFilterMatch unoconv "-d spreadsheet -f csv --stdout %P" /\.xlt.*/i FileFilter .ods unoconv "-d spreadsheet -f csv --stdout %P" FileFilter .ots unoconv "-d spreadsheet -f csv --stdout %P" FileFilter .dbf unoconv "-d spreadsheet -f csv --stdout %P" FileFilter .dif unoconv "-d spreadsheet -f csv --stdout %P" FileFilter .uos unoconv "-d spreadsheet -f csv --stdout %P" FileFilter .sxc unoconv "-d spreadsheet -f csv --stdout %P" # word documents FileFilterMatch unoconv "-d document -f txt --stdout %P" /\.doc.*/i FileFilterMatch unoconv "-d document -f txt --stdout %P" /\.odt.*/i FileFilterMatch unoconv "-d document -f txt --stdout %P" /\.rtf.*/i FileFilterMatch unoconv "-d document -f txt --stdout %P" /\.tex$/i # native html support IndexContents HTML* .htm .html .shtml IndexContents XML* .xml EOF swish-e -c ${tombmount}/.swishrc -S fs -v3 } _message "Search index updated." done return 0 } search_tombs() { { command -v locate 1>/dev/null 2>/dev/null } || { _failure "Cannot index tombs on this system: updatedb (mlocate) not installed." } updatedbver=`updatedb --version | grep '^updatedb'` [[ "$updatedbver" =~ "GNU findutils" ]] && { _warning "Cannot use GNU findutils for index/search commands." } [[ "$updatedbver" =~ "mlocate" ]] || { _failure "Index command needs 'mlocate' to be installed." } _verbose "$updatedbver" # list all open tombs mounted_tombs=(`list_tomb_mounts`) [[ ${#mounted_tombs} == 0 ]] && { _failure "I can't see any open tomb, may they all rest in peace." } _success "Searching for: ::1::" ${(f)@} for t in ${mounted_tombs}; do _verbose "Checking for index: ::1::" ${t} mapper=`basename ${t[(ws:;:)1]}` tombname=${t[(ws:;:)5]} tombmount=${t[(ws:;:)2]} [[ -r ${tombmount}/.updatedb ]] && { # Use mlocate to search hits on filenames _message "Searching filenames in tomb ::1 tomb name::" $tombname locate -d ${tombmount}/.updatedb -e -i "${(f)@}" _message "Matches found: ::1 matches::" \ $(locate -d ${tombmount}/.updatedb -e -i -c ${(f)@}) # Use swish-e to search over contents [[ $SWISH == 1 && -r $tombmount/.swish ]] && { _message "Searching contents in tomb ::1 tomb name::" $tombname swish-e -w ${@} -f $tombmount/.swish -H0 } } || { _warning "Skipping tomb ::1 tomb name::: not indexed." $tombname _warning "Run 'tomb index' to create indexes." } done _message "Search completed." return 0 } # }}} - Index and search # {{{ Resize # resize tomb file size resize_tomb() { local tombpath="$1" # First argument is the path to the tomb _message "Commanded to resize tomb ::1 tomb name:: to ::2 size:: mebibytes." $1 $OPTS[-s] [[ -z "$1" ]] && _failure "No tomb name specified for resizing." [[ ! -r "$1" ]] && _failure "Cannot find ::1::" $1 newtombsize="`option_value -s`" [[ -z "$newtombsize" ]] && { _failure "Aborting operations: new size was not specified, use -s" } is_valid_tomb $tombpath _load_key # Try loading new key from option -k and set TOMBKEYFILE if option_is_set --tomb-pwd; then tomb_pwd="`option_value --tomb-pwd`" _verbose "tomb-pwd = ::1 tomb pass::" $tomb_pwd ask_key_password "$tomb_pwd" else ask_key_password fi [[ $? == 0 ]] || _failure "No valid password supplied." local oldtombsize=$(( `stat -c %s "$TOMBPATH" 2>/dev/null` / 1048576 )) # New tomb size must be specified [[ -n "$newtombsize" ]] || { _failure "You must specify the new size of ::1 tomb name::" $TOMBNAME } # New tomb size must be an integer [[ $newtombsize == <-> ]] || _failure "Size is not an integer." # Tombs can only grow in size if [[ "$newtombsize" -gt "$oldtombsize" ]]; then delta="$(( $newtombsize - $oldtombsize ))" _message "Generating ::1 tomb file:: of ::2 size::MiB" $TOMBFILE $newtombsize _verbose "Data dump using ::1:: from /dev/urandom" ${DD[1]} ${=DD} if=/dev/urandom bs=1048576 count=${delta} >> $TOMBPATH [[ $? == 0 ]] || { _failure "Error creating the extra resize ::1 size::, operation aborted." \ $tmp_resize } # If same size this allows to re-launch resize if pinentry expires # so that it will continue resizing without appending more space. # Resizing the partition to the file size cannot harm data anyway. elif [[ "$newtombsize" = "$oldtombsize" ]]; then _message "Tomb seems resized already, operating filesystem stretch" else _failure "The new size must be greater then old tomb size." fi lo_mount "$TOMBPATH" _message "opening tomb" _cryptsetup luksOpen ${TOMBLOOP} ${TOMBMAPPER} || { _failure "Failure mounting the encrypted file." } _sudo cryptsetup resize "${TOMBMAPPER}" || { _failure "cryptsetup failed to resize ::1 mapper::" $TOMBMAPPER } filesystem=`_detect_filesystem /dev/mapper/${TOMBMAPPER}` _message "Filesystem detected: ::1 filesystem::" $filesystem case $filesystem in ext3|ext4) _sudo e2fsck -p -f /dev/mapper/${TOMBMAPPER} || { _sudo cryptsetup luksClose "${TOMBMAPPER}" _failure "e2fsck failed to check ::1 mapper::" $TOMBMAPPER } _sudo resize2fs /dev/mapper/${TOMBMAPPER} || { _sudo cryptsetup luksClose "${TOMBMAPPER}" _failure "resize2fs failed to resize ::1 mapper::" $TOMBMAPPER } ;; btrfs) _sudo btrfs check /dev/mapper/${TOMBMAPPER} || { _sudo cryptsetup luksClose "${TOMBMAPPER}" _failure "filesystem check failed on ::1 mapper::" $TOMBMAPPER } # btrfs requires mounting before resize local mp=${TOMBNAME}.tomb.resize mkdir -p /tmp/${mp} _sudo mount /dev/mapper/${TOMBMAPPER} /tmp/${mp} _sudo btrfs filesystem resize max /tmp/${mp} || { _sudo umount /tmp/${mp} _sudo cryptsetup luksClose "${TOMBMAPPER}" rmdir /tmp/${mp} _failure "filesystem resize failed on ::1 mapper::" $TOMBMAPPER } _sudo umount /tmp/${mp} rmdir /tmp/${mp} ;; # TODO: report error on unrecognized filesystem esac # close and free the loop device _sudo cryptsetup luksClose "${TOMBMAPPER}" return 0 } # }}} # {{{ Close umount_tomb() { local tombs how_many_tombs local pathmap mapper tombname tombmount loopdev local ans pidk pname if [ "$1" = "all" ]; then mounted_tombs=(`list_tomb_mounts`) else mounted_tombs=(`list_tomb_mounts $1`) fi [[ ${#mounted_tombs} == 0 ]] && { _failure "There is no open tomb to be closed." } [[ ${#mounted_tombs} -gt 1 && -z "$1" ]] && { _warning "Too many tombs mounted, please specify one (see tomb list)" _warning "or issue the command 'tomb close all' to close them all." _failure "Operation aborted." } for t in ${mounted_tombs}; do mapper=`basename ${t[(ws:;:)1]}` # strip square parens from tombname tombname=${t[(ws:;:)5]} tombmount=${t[(ws:;:)2]} tombfs=${t[(ws:;:)3]} tombfsopts=${t[(ws:;:)4]} tombloop=${mapper[(ws:.:)4]} _verbose "Name: ::1 tomb name::" $tombname _verbose "Mount: ::1 mount point::" $tombmount _verbose "Loop: ::1 mount loop::" $tombloop _verbose "Mapper: ::1 mapper::" $mapper [[ -e "$mapper" ]] && { _warning "Tomb not found: ::1 tomb file::" $1 _warning "Please specify an existing tomb." return 0 } option_is_set -n || { exec_safe_func_hooks \ close "$tombmount" "$tombname" "$tombloop" "$mapper" exec_hook_res=$? [[ $exec_hook_res = 0 ]] || { _warning "close exec-hook returns a non-zero error code: ::1 error::" $exec_hook_res _failure "Operation aborted" } } _message "Closing tomb ::1 tomb name:: mounted on ::2 mount point::" \ $tombname $tombmount # check if there are binded dirs and close them bind_tombs=(`list_tomb_binds $tombname $tombmount`) for b in ${(f)"$(list_tomb_binds $tombname $tombmount)"}; do bind_mapper="${b[(ws:;:)1]}" bind_mount="${b[(ws:;:)2]}" _message "Closing tomb bind hook: ::1 hook::" $bind_mount _sudo umount $bind_mount || _failure "Tomb bind hook ::1 hook:: is busy, cannot close tomb." $bind_mount done # check if the tomb is actually still mounted. Background: # When mounted on a binded directory in appears twice in 'list_tomb_binds' # and will get umounted automatically through the above function # causing an error and a remaining (decrypted!) loop device # posing a security risk. # See https://github.com/dyne/Tomb/issues/273 # checking for tombs still mounted mounted_tombs=(`list_tomb_mounts`) for t in ${mounted_tombs}; do usedmount=${t[(ws:;:)2]} [[ "$usedmount" == "$tombmount" ]] && { # Tomb was not umounted through the above command # Will do so now _verbose "Performing umount of ::1 mount point::" $tombmount _sudo umount ${tombmount} [[ $? = 0 ]] || { _failure "Tomb is busy, cannot umount!" } } done # If we used a default mountpoint and is now empty, delete it tombname_regex=${tombname//\[/} tombname_regex=${tombname_regex//\]/} [[ "$tombmount" =~ "(/run)?/media(/$_USER)?/$tombname_regex" ]] && { _sudo rmdir $tombmount } _sudo cryptsetup luksClose $mapper || _failure "Error occurred in cryptsetup luksClose ::1 mapper::" $mapper # Normally the loopback device is detached when unused [[ -e "/dev/$tombloop" ]] && { _sudo losetup -d "/dev/$tombloop" || _verbose "/dev/$tombloop was already closed." } _success "Tomb ::1 tomb name:: closed: your bones will rest in peace." $tombname done # loop across mounted tombs return 0 } list_processes() { # $1 = (optional) name of tomb # returns a list of process UIDs, one per line local mounted_tombs i local pnum puid pcmd powner found found=0 mounted_tombs=(`list_tomb_mounts $1`) if [[ "${#mounted_tombs}" -gt 0 ]]; then if [[ -z $1 ]]; then _success "Listing processes running inside all open tombs..." else _success "Listing processes running inside tomb '::1 tombname::'..." "$1" fi for i in ${mounted_tombs}; do _verbose "scanning tomb: ::1 tombmount::" $i tombmount=${i[(ws:;:)2]} tombname=${i[(ws:;:)5]} for pnum in ${(f)"$(_sudo lsof -t +D $tombmount)"}; do found=$(($found + 1)) _verbose "process found: $pnum" puid=$(_cat /proc/${pnum}/loginuid) pcmd=$(_cat /proc/${pnum}/cmdline) powner=`_get_username $puid` _verbose "process found: $pnum $pcmd ($powner)" _message "::1 tombname:: ::2 cmd:: (::3 owner::)" \ $tombname $pcmd $powner done done fi _message "::1 foundproc:: running processes found inside ::2 numtombs:: open tombs" \ $found ${#mounted_tombs} return 0 } # Kill all processes using the tomb slam_tomb() { # $1 = (optional) name of tomb to slam, or "all" if more mounted if [ "$1" = "all" ]; then mounted_tombs=(`list_tomb_mounts`) else mounted_tombs=(`list_tomb_mounts $1`) fi [[ ${#mounted_tombs} == 0 ]] && { _failure "There is no open tomb to be closed." } [[ ${#mounted_tombs} -gt 1 && -z "$1" ]] && { _warning "Too many tombs mounted, please specify one (see tomb list)" _warning "or issue the command 'tomb close all' to close them all." _failure "Operation aborted." } local pnum puid pcmd powner result result=0 # iterate through all mounted tomb affected for i in ${mounted_tombs}; do tombname=${i[(ws:;:)5]} tombmount=${i[(ws:;:)2]} _success "Slamming tomb ::1 tombname:: mounted on ::2 tombmount::" \ ${tombname} ${tombmount} # iterate through all processes running in mounted tombs for pnum in ${(f)"$(_sudo lsof -t +D $tombmount)"}; do puid=$(_cat /proc/${pnum}/loginuid) pcmd=$(_cat /proc/${pnum}/cmdline) powner=`_get_username $puid` _verbose "process found: $pnum $pcmd ($powner)" # iterate through 3 different signals to send, break on success for s in TERM HUP KILL; do _message "::1 tombname:: sending ::2 sig:: to ::3 cmd:: (::4 uid::)" \ ${tombname} ${s} ${pcmd} ${powner} _sudo kill -$s $pnum # give some time to the process for a clean quit sleep .5 # stop sending other signals if kill was succesfull [[ -r /proc/$pnum ]] || break done # if process still running then signal failure [[ -r /proc/$pnum ]] && { _warning "Can't kill ::1 process:: ::2 pcmd:: (::3 powner::)" \ $pnum $pcmd $powner result=1 } done # if it failed killing a process, report it [[ $result = 0 ]] && umount_tomb $tombname done return $result } # }}} - Tomb close # {{{ Main routine main() { _ensure_dependencies # Check dependencies are present or bail out local -A subcommands_opts ### Options configuration # # Hi, dear developer! Are you trying to add a new subcommand, or # to add some options? Well, keep in mind that option names are # global: they cannot bear a different meaning or behaviour across # subcommands. The only exception is "-o" which means: "options # passed to the local subcommand", and thus can bear a different # meaning for different subcommands. # # For example, "-s" means "size" and accepts one argument. If you # are tempted to add an alternate option "-s" (e.g., to mean # "silent", and that doesn't accept any argument) DON'T DO IT! # # There are two reasons for that: # I. Usability; users expect that "-s" is "size" # II. Option parsing WILL EXPLODE if you do this kind of bad # things (it will complain: "option defined more than once") # # If you want to use the same option in multiple commands then you # can only use the non-abbreviated long-option version like: # -force and NOT -f # main_opts=(q -quiet=q D -debug=D h -help=h v -version=v f -force=f -tmp: U: G: T: -no-color -unsafe g -gpgkey=g) subcommands_opts[__default]="" # -o in open and mount is used to pass alternate mount options subcommands_opts[open]="n -nohook=n k: -kdf: o: -ignore-swap -tomb-pwd: r: R: -sphx-host: -sphx-user: p -preserve-ownership=p" subcommands_opts[mount]=${subcommands_opts[open]} subcommands_opts[create]="" # deprecated, will issue warning # -o in forge and lock is used to pass an alternate cipher. subcommands_opts[forge]="-ignore-swap k: -kdf: o: -tomb-pwd: -use-random r: R: -sphx-host: -sphx-user: " subcommands_opts[dig]="-ignore-swap s: -size=s " subcommands_opts[lock]="-ignore-swap k: -kdf: o: -tomb-pwd: r: R: -sphx-host: -sphx-user: -filesystem: " subcommands_opts[setkey]="k: -ignore-swap -kdf: -tomb-old-pwd: -tomb-pwd: r: R: -sphx-host: -sphx-user: " subcommands_opts[engrave]="k: " subcommands_opts[passwd]="k: -ignore-swap -kdf: -tomb-old-pwd: -tomb-pwd: r: R: -sphx-host: -sphx-user: " subcommands_opts[close]="" subcommands_opts[help]="" subcommands_opts[slam]="" subcommands_opts[ps]="" subcommands_opts[list]="-get-mountpoint " subcommands_opts[index]="" subcommands_opts[search]="" subcommands_opts[help]="" subcommands_opts[bury]="k: -tomb-pwd: r: R: -sphx-host: -sphx-user: " subcommands_opts[exhume]="k: -tomb-pwd: r: R: -sphx-host: -sphx-user: " subcommands_opts[cloak]="k: " subcommands_opts[uncloak]="k: " # subcommands_opts[decompose]="" # subcommands_opts[recompose]="" # subcommands_opts[install]="" subcommands_opts[askpass]="" subcommands_opts[source]="" subcommands_opts[resize]="-ignore-swap s: -size=s k: -tomb-pwd: r: R: -sphx-host: -sphx-user: " subcommands_opts[check]="-ignore-swap " # subcommands_opts[translate]="" ### Detect subcommand local -aU every_opts #every_opts behave like a set; that is, an array with unique elements for optspec in $subcommands_opts$main_opts; do for opt in ${=optspec}; do every_opts+=${opt} done done local -a oldstar oldstar=("${(@)argv}") #### detect early: useful for --option-parsing zparseopts -M -D -Adiscardme ${every_opts} if [[ -n ${(k)discardme[--option-parsing]} ]]; then print $1 if [[ -n "$1" ]]; then return 1 fi return 0 fi unset discardme if ! zparseopts -M -E -D -Adiscardme ${every_opts}; then _failure "Error parsing." return 127 fi unset discardme subcommand=$1 if [[ -z $subcommand ]]; then subcommand="__default" fi if [[ -z ${(k)subcommands_opts[$subcommand]} ]]; then _warning "There's no such command \"::1 subcommand::\"." $subcommand exitv=127 _failure "Please try -h for help." fi argv=("${(@)oldstar}") unset oldstar ### Parsing global + command-specific options # zsh magic: ${=string} will split to multiple arguments when spaces occur set -A cmd_opts ${main_opts} ${=subcommands_opts[$subcommand]} # if there is no option, we don't need parsing if [[ -n $cmd_opts ]]; then zparseopts -M -E -D -AOPTS ${cmd_opts} if [[ $? != 0 ]]; then _warning "Some error occurred during option processing." exitv=127 _failure "See \"tomb help\" for more info." fi fi #build PARAM (array of arguments) and check if there are unrecognized options ok=0 PARAM=() for arg in $*; do if [[ $arg == '--' || $arg == '-' ]]; then ok=1 continue #it shouldn't be appended to PARAM elif [[ $arg[1] == '-' ]]; then if [[ $ok == 0 ]]; then exitv=127 _failure "Unrecognized option ::1 arg:: for subcommand ::2 subcommand::" $arg $subcommand fi fi PARAM+=$arg done # First parameter actually is the subcommand: delete it and shift [[ $subcommand != '__default' ]] && { PARAM[1]=(); shift } ### End parsing command-specific options # Use colors unless told not to { ! option_is_set --no-color } && { autoload -Uz colors && colors } # Some options are only available during insecure mode { ! option_is_set --unsafe } && { for opt in --tomb-pwd --tomb-old-pwd; do { option_is_set $opt } && { exitv=127 _failure "You specified option ::1 option::, which is DANGEROUS and should only be used for testing\nIf you really want so, add --unsafe" $opt } done } # read -t or --tmp flags to set a custom temporary directory option_is_set --tmp && TMPDIR=$(option_value --tmp) # When we run as root, we remember the original uid:gid to set # permissions for the calling user and drop privileges _whoami # Reset _UID, _GID, _TTY [[ -z $PARAM ]] && { _verbose "Tomb command: ::1 subcommand::" $subcommand } || { _verbose "Tomb command: ::1 subcommand:: ::2 param::" $subcommand $PARAM } [[ -z $_UID ]] || { _verbose "Caller: uid[::1 uid::], gid[::2 gid::], tty[::3 tty::]." \ $_UID $_GID $_TTY } _verbose "Temporary directory: $TMPDIR" # Process subcommand case "$subcommand" in # USAGE help) usage ;; # DEPRECATION notice (leave here as 'create' is still present in old docs) create) _warning "The create command is deprecated, please use dig, forge and lock instead." _warning "For more informations see Tomb's manual page (man tomb)." _failure "Operation aborted." ;; # CREATE Step 1: dig -s NN file.tomb dig) dig_tomb $PARAM ;; # CREATE Step 2: forge file.tomb.key forge) forge_key $PARAM ;; # CREATE Step 3: lock -k file.tomb.key file.tomb lock) lock_tomb_with_key $PARAM ;; # Open the tomb mount|open) mount_tomb $PARAM ;; # List all processes using a tomb ps) list_processes $PARAM ;; # Slam a tomb killing all processes running inside slam) slam_tomb $PARAM ;; # Close the tomb # `slam` is used to force closing. umount|close) [[ "$subcommand" == "slam" ]] && { SLAM=1 [[ $LSOF == 0 ]] && { unset SLAM _warning "lsof not installed: cannot slam tombs." _warning "Trying a regular close." }} umount_tomb $PARAM[1] ;; # Grow tomb's size resize) [[ $RESIZER == 0 ]] && { _failure "Resize2fs not installed: cannot resize tombs." } resize_tomb $PARAM[1] ;; ## Contents manipulation # Index tomb contents index) index_tombs $PARAM[1] ;; # List tombs list) list_tombs $PARAM[1] ;; # Search tomb contents search) search_tombs $PARAM ;; ## Locking operations # Export key to QR Code engrave) [[ $QRENCODE == 0 ]] && { _failure "QREncode not installed: cannot engrave keys on paper." } engrave_key $PARAM ;; # Change password on existing key passwd) change_passwd $PARAM[1] ;; # Change tomb key setkey) change_tomb_key $PARAM ;; # STEGANOGRAPHY: hide key inside an image bury) [[ $STEGHIDE == 0 ]] && { _failure "Steghide not installed: cannot bury keys into images." } bury_key $PARAM[1] ;; # STEGANOGRAPHY: read key hidden in an image exhume) [[ $STEGHIDE == 0 ]] && { _failure "Steghide not installed: cannot exhume keys from images." } exhume_key $PARAM[1] ;; # STEGANOGRAPHY: transform key into text using cipher cloak) [[ $CLOAKIFY == 0 ]] && { _failure "Cloakify not installed: cannot cipher keys into texts" } cloakify_key $PARAM ;; # STEGANOGRAPHY: read key from text using cipher uncloak) [[ $DECLOAKIFY == 0 ]] && { _failure "Decloakify not installed: cannot decipher keys from texts" } decloakify_key $PARAM ;; ## Internal commands useful to developers # Make tomb functions available to the calling shell or script 'source') return 0 ;; # Ask user for a password interactively askpass) ask_password $PARAM[1] $PARAM[2] ;; # Default operation: presentation, or version information with -v __default) _print "Tomb ::1 version:: - a strong and gentle undertaker for your secrets" $VERSION echo _print " Copyright (C) 2007-2021 Dyne.org Foundation, License GNU GPL v3+" _print " This is free software: you are free to change and redistribute it" _print " For the latest sourcecode go to <http://dyne.org/software/tomb>" echo option_is_set -v && { local langwas=$LANG LANG=en _print " This source code is distributed in the hope that it will be useful," _print " but WITHOUT ANY WARRANTY; without even the implied warranty of" _print " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." LANG=$langwas _print " When in need please refer to <http://dyne.org/support>." echo _print "System utils:" echo cat <<EOF `zsh --version` `sudo -V | head -n1` `cryptsetup --version` `pinentry --version | head -n1` `findmnt -V` `gpg --version | head -n1` - key forging algorithms (GnuPG symmetric ciphers): `list_gnupg_ciphers` EOF echo _print "Optional utils:" echo _list_optional_tools version return 0 } usage ;; # Reject unknown command and suggest help *) _warning "Command \"::1 subcommand::\" not recognized." $subcommand _message "Try -h for help." return 1 ;; esac return $? } # }}} # {{{ Run main "$@" || exit $? # Prevent `source tomb source` from exiting # }}} |