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 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103
|
#!/usr/bin/perl
# zipdetails
#
# Display info on the contents of a Zip file
#
use 5.010; # for unpack "Q<"
my $NESTING_DEBUG = 0 ;
BEGIN {
# Check for a 32-bit Perl
if (!eval { pack "Q", 1 }) {
warn "zipdetails requires 64 bit integers, ",
"this Perl has 32 bit integers.\n";
exit(1);
}
}
BEGIN { pop @INC if $INC[-1] eq '.' }
use strict;
use warnings ;
no warnings 'portable'; # for unpacking > 2^32
use feature qw(state say);
use IO::File;
use Encode;
use Getopt::Long;
use List::Util qw(min max);
my $VERSION = '4.004' ;
sub fatal_tryWalk;
sub fatal_truncated ;
sub info ;
sub warning ;
sub error ;
sub debug ;
sub fatal ;
sub topLevelFatal ;
sub internalFatal;
sub need ;
sub decimalHex;
use constant MAX64 => 0xFFFFFFFFFFFFFFFF ;
use constant MAX32 => 0xFFFFFFFF ;
use constant MAX16 => 0xFFFF ;
# Compression types
use constant ZIP_CM_STORE => 0 ;
use constant ZIP_CM_IMPLODE => 6 ;
use constant ZIP_CM_DEFLATE => 8 ;
use constant ZIP_CM_BZIP2 => 12 ;
use constant ZIP_CM_LZMA => 14 ;
use constant ZIP_CM_PPMD => 98 ;
# General Purpose Flag
use constant ZIP_GP_FLAG_ENCRYPTED_MASK => (1 << 0) ;
use constant ZIP_GP_FLAG_STREAMING_MASK => (1 << 3) ;
use constant ZIP_GP_FLAG_PATCHED_MASK => (1 << 5) ;
use constant ZIP_GP_FLAG_STRONG_ENCRYPTED_MASK => (1 << 6) ;
use constant ZIP_GP_FLAG_LZMA_EOS_PRESENT => (1 << 1) ;
use constant ZIP_GP_FLAG_LANGUAGE_ENCODING => (1 << 11) ;
use constant ZIP_GP_FLAG_PKWARE_ENHANCED_COMP => (1 << 12) ;
use constant ZIP_GP_FLAG_ENCRYPTED_CD => (1 << 13) ;
# All the encryption flags
use constant ZIP_GP_FLAG_ALL_ENCRYPT => (ZIP_GP_FLAG_ENCRYPTED_MASK | ZIP_GP_FLAG_STRONG_ENCRYPTED_MASK | ZIP_GP_FLAG_ENCRYPTED_CD );
# Internal File Attributes
use constant ZIP_IFA_TEXT_MASK => 1;
# Signatures for each of the headers
use constant ZIP_LOCAL_HDR_SIG => 0x04034b50;
use constant ZIP_DATA_HDR_SIG => 0x08074b50;
use constant ZIP_CENTRAL_HDR_SIG => 0x02014b50;
use constant ZIP_END_CENTRAL_HDR_SIG => 0x06054b50;
use constant ZIP64_END_CENTRAL_REC_HDR_SIG => 0x06064b50;
use constant ZIP64_END_CENTRAL_LOC_HDR_SIG => 0x07064b50;
use constant ZIP_DIGITAL_SIGNATURE_SIG => 0x05054b50;
use constant ZIP_ARCHIVE_EXTRA_DATA_RECORD_SIG => 0x08064b50;
use constant ZIP_SINGLE_SEGMENT_MARKER => 0x30304b50; # APPNOTE 6.3.10, sec 8.5.4
# Extra sizes
use constant ZIP_EXTRA_HEADER_SIZE => 2 ;
use constant ZIP_EXTRA_MAX_SIZE => 0xFFFF ;
use constant ZIP_EXTRA_SUBFIELD_ID_SIZE => 2 ;
use constant ZIP_EXTRA_SUBFIELD_LEN_SIZE => 2 ;
use constant ZIP_EXTRA_SUBFIELD_HEADER_SIZE => ZIP_EXTRA_SUBFIELD_ID_SIZE +
ZIP_EXTRA_SUBFIELD_LEN_SIZE;
use constant ZIP_EXTRA_SUBFIELD_MAX_SIZE => ZIP_EXTRA_MAX_SIZE -
ZIP_EXTRA_SUBFIELD_HEADER_SIZE;
use constant ZIP_EOCD_MIN_SIZE => 22 ;
use constant ZIP_LD_FILENAME_OFFSET => 30;
use constant ZIP_CD_FILENAME_OFFSET => 46;
my %ZIP_CompressionMethods =
(
0 => 'Stored',
1 => 'Shrunk',
2 => 'Reduced compression factor 1',
3 => 'Reduced compression factor 2',
4 => 'Reduced compression factor 3',
5 => 'Reduced compression factor 4',
6 => 'Imploded',
7 => 'Reserved for Tokenizing compression algorithm',
8 => 'Deflated',
9 => 'Deflate64',
10 => 'PKWARE Data Compression Library Imploding',
11 => 'Reserved by PKWARE',
12 => 'BZIP2',
13 => 'Reserved by PKWARE',
14 => 'LZMA',
15 => 'Reserved by PKWARE',
16 => 'IBM z/OS CMPSC Compression',
17 => 'Reserved by PKWARE',
18 => 'IBM/TERSE or Xceed BWT', # APPNOTE has IBM/TERSE. Xceed reuses it unofficially
19 => 'IBM LZ77 z Architecture (PFS)',
20 => 'Ipaq8', # see https://encode.su/threads/1048-info-zip-lpaq8
92 => 'Reference', # Winzip Only from version 25
93 => 'Zstandard',
94 => 'MP3',
95 => 'XZ',
96 => 'WinZip JPEG Compression',
97 => 'WavPack compressed data',
98 => 'PPMd version I, Rev 1',
99 => 'AES Encryption', # Apple also use this code for LZFSE compression in IPA files
);
my %OS_Lookup = (
0 => "MS-DOS",
1 => "Amiga",
2 => "OpenVMS",
3 => "Unix",
4 => "VM/CMS",
5 => "Atari ST",
6 => "HPFS (OS/2, NT 3.x)",
7 => "Macintosh",
8 => "Z-System",
9 => "CP/M",
10 => "Windows NTFS or TOPS-20",
11 => "MVS or NTFS",
12 => "VSE or SMS/QDOS",
13 => "Acorn RISC OS",
14 => "VFAT",
15 => "alternate MVS",
16 => "BeOS",
17 => "Tandem",
18 => "OS/400",
19 => "OS/X (Darwin)",
30 => "AtheOS/Syllable",
);
{
package Signatures ;
my %Lookup = (
# Map unpacked signature to
# decoder
# name
# central flag
# Core Signatures
::ZIP_LOCAL_HDR_SIG, [ \&::LocalHeader, "Local File Header", 0 ],
::ZIP_DATA_HDR_SIG, [ \&::DataDescriptor, "Data Descriptor", 0 ],
::ZIP_CENTRAL_HDR_SIG, [ \&::CentralHeader, "Central Directory Header", 1 ],
::ZIP_END_CENTRAL_HDR_SIG, [ \&::EndCentralHeader, "End Central Directory Record", 1 ],
::ZIP_SINGLE_SEGMENT_MARKER, [ \&::SingleSegmentMarker, "Split Archive Single Segment Marker", 0],
# Zip64
::ZIP64_END_CENTRAL_REC_HDR_SIG, [ \&::Zip64EndCentralHeader, "Zip64 End of Central Directory Record", 1 ],
::ZIP64_END_CENTRAL_LOC_HDR_SIG, [ \&::Zip64EndCentralLocator, "Zip64 End of Central Directory Locator", 1 ],
# Digital signature (pkzip)
::ZIP_DIGITAL_SIGNATURE_SIG, [ \&::DigitalSignature, "Digital Signature", 1 ],
# Archive Encryption Headers (pkzip) - never seen this one
::ZIP_ARCHIVE_EXTRA_DATA_RECORD_SIG, [ \&::ArchiveExtraDataRecord, "Archive Extra Record", 1 ],
);
sub decoder
{
my $signature = shift ;
return undef
unless exists $Lookup{$signature};
return $Lookup{$signature}[0];
}
sub name
{
my $signature = shift ;
return 'UNKNOWN'
unless exists $Lookup{$signature};
return $Lookup{$signature}[1];
}
sub titleName
{
my $signature = shift ;
uc name($signature);
}
sub hexValue
{
my $signature = shift ;
sprintf "0x%X", $signature ;
}
sub hexValue32
{
my $signature = shift ;
sprintf "0x%08X", $signature ;
}
sub hexValue16
{
my $signature = shift ;
sprintf "0x%04X", $signature ;
}
sub nameAndHex
{
my $signature = shift ;
return "'" . name($signature) . "' (" . hexValue32($signature) . ")"
}
sub isCentralHeader
{
my $signature = shift ;
return undef
unless exists $Lookup{$signature};
return $Lookup{$signature}[2];
}
#sub isValidSignature
#{
# my $signature = shift ;
# return exists $Lookup{$signature}}
#}
sub getSigsForScan
{
my %sigs =
# map { $_ => 1 }
# map { substr($_->[0], 2, 2) => $_->[1] } # don't want the initial "PK"
map { substr(pack("V", $_), 2, 2) => $_ }
keys %Lookup ;
return %sigs;
}
}
my %Extras = (
# Local Central
# ID Name Handler min size max size min size max size
0x0001, ['ZIP64', \&decode_Zip64, 0, 28, 0, 28],
0x0007, ['AV Info', undef], # TODO
0x0008, ['Extended Language Encoding', undef], # TODO
0x0009, ['OS/2 extended attributes', undef], # TODO
0x000a, ['NTFS FileTimes', \&decode_NTFS_Filetimes, 32, 32, 32, 32],
0x000c, ['OpenVMS', \&decode_OpenVMS, 4, undef, 4, undef],
0x000d, ['Unix', undef],
0x000e, ['Stream & Fork Descriptors', undef], # TODO
0x000f, ['Patch Descriptor', undef],
0x0014, ['PKCS#7 Store for X.509 Certificates', undef],
0x0015, ['X.509 Certificate ID and Signature for individual file', undef],
0x0016, ['X.509 Certificate ID for Central Directory', undef],
0x0017, ['Strong Encryption Header', \&decode_strong_encryption, 12, undef, 12, undef],
0x0018, ['Record Management Controls', undef],
0x0019, ['PKCS#7 Encryption Recipient Certificate List', undef],
0x0020, ['Reserved for Timestamp record', undef],
0x0021, ['Policy Decryption Key Record', undef],
0x0022, ['Smartcrypt Key Provider Record', undef],
0x0023, ['Smartcrypt Policy Key Data Record', undef],
# The Header ID mappings defined by Info-ZIP and third parties are:
0x0065, ['IBM S/390 attributes - uncompressed', \&decode_MVS, 4, undef, 4, undef],
0x0066, ['IBM S/390 attributes - compressed', undef],
0x07c8, ['Info-ZIP Macintosh (old, J. Lee)', undef],
0x10c5, ['Minizip CMS Signature', \&decode_Minizip_Signature, undef, undef, undef, undef], # https://github.com/zlib-ng/minizip-ng/blob/master/doc/mz_extrafield.md
0x1986, ['Pixar USD', undef], # TODO
0x1a51, ['Minizip Hash', \&decode_Minizip_Hash, 4, undef, 4, undef], # https://github.com/zlib-ng/minizip-ng/blob/master/doc/mz_extrafield.md
0x2605, ['ZipIt Macintosh (first version)', undef],
0x2705, ['ZipIt Macintosh v 1.3.5 and newer (w/o full filename)', undef],
0x2805, ['ZipIt Macintosh v 1.3.5 and newer', undef],
0x334d, ["Info-ZIP Macintosh (new, D. Haase's 'Mac3' field)", undef], # TODO
0x4154, ['Tandem NSK [TA]', undef], # TODO
0x4341, ['Acorn/SparkFS [AC]', undef], # TODO
0x4453, ['Windows NT security descriptor [SD]', \&decode_NT_security, 11, undef, 4, 4], # TODO
0x4690, ['POSZIP 4690', undef],
0x4704, ['VM/CMS', undef],
0x470f, ['MVS', undef],
0x4854, ['Theos [TH]', undef],
0x4b46, ['FWKCS MD5 [FK]', undef],
0x4c41, ['OS/2 access control list [AL]', undef],
0x4d49, ['Info-ZIP OpenVMS (obsolete) [IM]', undef],
0x4d63, ['Macintosh SmartZIP [cM]', undef], # TODO
0x4f4c, ['Xceed original location [LO]', undef],
0x5356, ['AOS/VS (binary ACL) [VS]', undef],
0x5455, ['Extended Timestamp [UT]', \&decode_UT, 1, 13, 1, 13],
0x554e, ['Xceed unicode extra field [UN]', \&decode_Xceed_unicode, 6, undef, 8, undef],
0x564B, ['Key-Value Pairs [KV]', \&decode_Key_Value_Pair, 13, undef, 13, undef],# TODO -- https://github.com/sozip/keyvaluepairs-spec/blob/master/zip_keyvalue_extra_field_specification.md
0x5855, ['Unix Extra type 1 [UX]', \&decode_UX, 12, 12, 8, 8],
0x5a4c, ['ZipArchive Unicode Filename [LZ]', undef], # https://www.artpol-software.com/ZipArchive
0x5a4d, ['ZipArchive Offsets Array [MZ]', undef], # https://www.artpol-software.com/ZipArchive
0x6375, ['Unicode Comment [uc]', \&decode_uc, 5, undef, 5, undef],
0x6542, ['BeOS/Haiku [Be]', undef], # TODO
0x6854, ['Theos [Th]', undef],
0x7075, ['Unicode Path [up]', \&decode_up, 5, undef, 5, undef],
0x756e, ['ASi Unix [un]', \&decode_ASi_Unix], # TODO
0x7441, ['AtheOS [At]', undef],
0x7855, ['Unix Extra type 2 [Ux]', \&decode_Ux, 4,4, 0, 0 ],
0x7875, ['Unix Extra type 3 [ux]', \&decode_ux, 3, undef, 3, undef],
0x9901, ['AES Encryption', \&decode_AES, 7, 7, 7, 7],
0x9903, ['Reference', \&decode_Reference, 20, 20, 20, 20], # Added in WinZip ver 25
0xa11e, ['Data Stream Alignment', \&decode_DataStreamAlignment, 2, undef, 2, undef ],
0xA220, ['Open Packaging Growth Hint', \&decode_GrowthHint, 4, undef, 4, undef ],
0xCAFE, ['Java Executable', \&decode_Java_exe, 0, 0, 0, 0],
0xCDCD, ['Minizip Central Directory', \&decode_Minizip_CD, 8, 8, 8, 8], # https://github.com/zlib-ng/minizip-ng/blob/master/doc/mz_extrafield.md
0xd935, ['Android APK Alignment', undef], # TODO
0xE57a, ['ALZip Codepage', undef], # TODO
0xfb4a, ['SMS/QDOS', undef], # TODO
);
# Dummy entry only used in test harness, so only enable when ZIPDETAILS_TESTHARNESS is set
$Extras{0xFFFF} =
['DUMMY', \&decode_DUMMY, undef, undef, undef, undef]
if $ENV{ZIPDETAILS_TESTHARNESS} ;
sub extraFieldIdentifier
{
my $id = shift ;
my $name = $Extras{$id}[0] // "Unknown";
return "Extra Field '$name' (ID " . hexValue16($id) .")";
}
# Zip64EndCentralHeader version 2
my %HashIDLookup = (
0x0000 => 'none',
0x0001 => 'CRC32',
0x8003 => 'MD5',
0x8004 => 'SHA1',
0x8007 => 'RIPEMD160',
0x800C => 'SHA256',
0x800D => 'SHA384',
0x800E => 'SHA512',
);
# Zip64EndCentralHeader version 2, Strong Encryption Header & DecryptionHeader
my %AlgIdLookup = (
0x6601 => "DES",
0x6602 => "RC2 (version needed to extract < 5.2)",
0x6603 => "3DES 168",
0x6609 => "3DES 112",
0x660E => "AES 128",
0x660F => "AES 192",
0x6610 => "AES 256",
0x6702 => "RC2 (version needed to extract >= 5.2)",
0x6720 => "Blowfish",
0x6721 => "Twofish",
0x6801 => "RC4",
0xFFFF => "Unknown algorithm",
);
# Zip64EndCentralHeader version 2, Strong Encryption Header & DecryptionHeader
my %FlagsLookup = (
0x0001 => "Password required to decrypt",
0x0002 => "Certificates only",
0x0003 => "Password or certificate required to decrypt",
# Values > 0x0003 reserved for certificate processing
);
# Strong Encryption Header & DecryptionHeader
my %HashAlgLookup = (
0x8004 => 'SHA1',
);
my $FH;
my $ZIP64 = 0 ;
my $NIBBLES = 8;
my $LocalHeaderCount = 0;
my $CentralHeaderCount = 0;
my $InfoCount = 0;
my $WarningCount = 0;
my $ErrorCount = 0;
my $lastWasMessage = 0;
my $fatalDisabled = 0;
my $OFFSET = 0 ;
# Prefix data
my $POSSIBLE_PREFIX_DELTA = 0;
my $PREFIX_DELTA = 0;
my $TRAILING = 0 ;
my $PAYLOADLIMIT = 256;
my $ZERO = 0 ;
my $APK = 0 ;
my $START_APK = 0;
my $APK_LEN = 0;
my $CentralDirectory = CentralDirectory->new();
my $LocalDirectory = LocalDirectory->new();
my $HeaderOffsetIndex = HeaderOffsetIndex->new();
my $EOCD_Present = 0;
sub prOff
{
my $offset = shift;
my $s = offset($OFFSET);
$OFFSET += $offset;
return $s;
}
sub offset
{
my $v = shift ;
sprintf("%0${NIBBLES}X", $v);
}
# Format variables
my ($OFF, $ENDS_AT, $LENGTH, $CONTENT, $TEXT, $VALUE) ;
my $FMT1 = 'STDOUT1';
my $FMT2 = 'STDOUT2';
sub setupFormat
{
my $wantVerbose = shift ;
my $nibbles = shift;
my $width = '@' . ('>' x ($nibbles -1));
my $space = " " x length($width);
# See https://github.com/Perl/perl5/issues/14255 for issue with "^*" in perl < 5.22
# my $rightColumn = "^*" ;
my $rightColumn = "^" . ("<" x 132);
# Fill mode can split on space or newline chars
# Spliting on hyphen works differently from Perl 5.20 onwards
$: = " \n";
my $fmt ;
if ($wantVerbose) {
eval "format $FMT1 =
$width $width $width ^<<<<<<<<<<<^<<<<<<<<<<<<<<<<<<<< $rightColumn
\$OFF, \$ENDS_AT, \$LENGTH, \$CONTENT, \$TEXT, \$VALUE
$space $space $space ^<<<<<<<<<<<^<<<<<<<<<<<<<<<<<<<< $rightColumn~~
\$CONTENT, \$TEXT, \$VALUE
.
";
eval "format $FMT2 =
$width $width $width ^<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<< $rightColumn
\$OFF, \$ENDS_AT, \$LENGTH, \$CONTENT, \$TEXT, \$VALUE
$space $space $space ^<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<< $rightColumn~~
\$CONTENT, \$TEXT, \$VALUE
.
";
}
else {
eval "format $FMT1 =
$width ^<<<<<<<<<<<<<<<<<<<< $rightColumn
\$OFF, \$TEXT, \$VALUE
$space ^<<<<<<<<<<<<<<<<<<<< $rightColumn~~
\$TEXT, \$VALUE
.
";
eval "format $FMT2 =
$width ^<<<<<<<<<<<<<<<<<< $rightColumn
\$OFF, \$TEXT, \$VALUE
$space ^<<<<<<<<<<<<<<<<<< $rightColumn~~
\$TEXT, \$VALUE
.
"
}
no strict 'refs';
open($FMT1, ">&", \*STDOUT); select $FMT1; $| = 1 ;
open($FMT2, ">&", \*STDOUT); select $FMT2; $| = 1 ;
select 'STDOUT';
$| = 1;
}
sub mySpr
{
my $format = shift ;
return "" if ! defined $format;
return $format unless @_ ;
return sprintf $format, @_ ;
}
sub xDump
{
my $input = shift;
$input =~ tr/\0-\37\177-\377/./;
return $input;
}
sub hexDump
{
return uc join ' ', unpack('(H2)*', $_[0]);
}
sub hexDump16
{
return uc
join "\r",
map { join ' ', unpack('(H2)*', $_ ) }
unpack('(a16)*', $_[0]) ;
}
sub charDump2
{
sprintf "%v02X", $_[0];
}
sub charDump
{
sprintf "%vX", $_[0];
}
sub hexValue
{
return sprintf("0x%X", $_[0]);
}
sub hexValue32
{
return sprintf("0x%08X", $_[0]);
}
sub hexValue16
{
return sprintf("0x%04X", $_[0]);
}
sub outHexdump
{
my $size = shift;
my $text = shift;
my $limit = shift ;
return 0
if $size == 0;
# TODO - add a limit to data output
# if ($limit)
# {
# outSomeData($size, $text);
# }
# else
{
myRead(my $payload, $size);
out($payload, $text, hexDump16($payload));
}
return $size;
}
sub decimalHex
{
sprintf("%0*X (%u)", $_[1] // 0, $_[0], $_[0])
}
sub decimalHex0x
{
sprintf("0x%0*X (%u)", $_[1] // 0, $_[0], $_[0])
}
sub decimalHex0xUndef
{
return 'Unknown'
if ! defined $_[0];
return decimalHex0x @_;
}
sub out
{
my $data = shift;
my $text = shift;
my $format = shift;
my $size = length($data) ;
$ENDS_AT = offset($OFFSET + ($size ? $size - 1 : 0)) ;
$OFF = prOff($size);
$LENGTH = offset($size) ;
$CONTENT = hexDump($data);
$TEXT = $text;
$VALUE = mySpr $format, @_;
no warnings;
write $FMT1 ;
$lastWasMessage = 0;
}
sub out0
{
my $size = shift;
my $text = shift;
my $format = shift;
$ENDS_AT = offset($OFFSET + ($size ? $size - 1 : 0)) ;
$OFF = prOff($size);
$LENGTH = offset($size) ;
$CONTENT = '...';
$TEXT = $text;
$VALUE = mySpr $format, @_;
write $FMT1;
skip($FH, $size);
$lastWasMessage = 0;
}
sub out1
{
my $text = shift;
my $format = shift;
$ENDS_AT = '' ;
$OFF = '';
$LENGTH = '' ;
$CONTENT = '';
$TEXT = $text;
$VALUE = mySpr $format, @_;
write $FMT1;
$lastWasMessage = 0;
}
sub out2
{
my $data = shift ;
my $text = shift ;
my $format = shift;
my $size = length($data) ;
$ENDS_AT = offset($OFFSET + ($size ? $size - 1 : 0)) ;
$OFF = prOff($size);
$LENGTH = offset($size);
$CONTENT = hexDump($data);
$TEXT = $text;
$VALUE = mySpr $format, @_;
no warnings;
write $FMT2;
$lastWasMessage = 0;
}
sub Value
{
my $letter = shift;
if ($letter eq 'C')
{ return decimalHex($_[0], 2) }
elsif ($letter eq 'v')
{ return decimalHex($_[0], 4) }
elsif ($letter eq 'V')
{ return decimalHex($_[0], 8) }
elsif ($letter eq 'Q<')
{ return decimalHex($_[0], 16) }
else
{ internalFatal undef, "here letter $letter"}
}
sub outer
{
my $name = shift ;
my $unpack = shift ;
my $size = shift ;
my $cb1 = shift ;
my $cb2 = shift ;
myRead(my $buff, $size);
my (@value) = unpack $unpack, $buff;
my $hex = Value($unpack, @value);
if (defined $cb1) {
my $v ;
if (ref $cb1 eq 'CODE') {
$v = $cb1->(@value) ;
}
else {
$v = $cb1 ;
}
$v = "'" . $v unless $v =~ /^'/;
$v .= "'" unless $v =~ /'$/;
$hex .= " $v" ;
}
out $buff, $name, $hex ;
$cb2->(@value)
if defined $cb2 ;
return $value[0];
}
sub out_C
{
my $name = shift ;
my $cb1 = shift ;
my $cb2 = shift ;
outer($name, 'C', 1, $cb1, $cb2);
}
sub out_v
{
my $name = shift ;
my $cb1 = shift ;
my $cb2 = shift ;
outer($name, 'v', 2, $cb1, $cb2);
}
sub out_V
{
my $name = shift ;
my $cb1 = shift ;
my $cb2 = shift ;
outer($name, 'V', 4, $cb1, $cb2);
}
sub out_Q
{
my $name = shift ;
my $cb1 = shift ;
my $cb2 = shift ;
outer($name, 'Q<', 8, $cb1, $cb2);
}
sub outSomeData
{
my $size = shift;
my $message = shift;
my $redact = shift ;
# return if $size == 0;
if ($size > 0) {
if ($size > $PAYLOADLIMIT) {
my $before = $FH->tell();
out0 $size, $message;
} else {
myRead(my $buffer, $size );
$buffer = "X" x $size
if $redact;
out $buffer, $message, xDump $buffer ;
}
}
}
sub outSomeDataParagraph
{
my $size = shift;
my $message = shift;
my $redact = shift ;
return if $size == 0;
print "\n";
outSomeData($size, $message, $redact);
}
sub unpackValue_C
{
Value_v(unpack "C", $_[0]);
}
sub Value_C
{
return decimalHex($_[0], 2);
}
sub unpackValue_v
{
Value_v(unpack "v", $_[0]);
}
sub Value_v
{
return decimalHex($_[0], 4);
}
sub unpackValue_V
{
Value_V(unpack "V", $_[0]);
}
sub Value_V
{
return decimalHex($_[0] // 0, 8);
}
sub unpackValue_Q
{
my $v = unpack ("Q<", $_[0]);
Value_Q($v);
}
sub Value_Q
{
return decimalHex($_[0], 16);
}
sub read_Q
{
my $b ;
myRead($b, 8);
return ($b, unpack ("Q<" , $b));
}
sub read_V
{
my $b ;
myRead($b, 4);
return ($b, unpack ("V", $b));
}
sub read_v
{
my $b ;
myRead($b, 2);
return ($b, unpack "v", $b);
}
sub read_C
{
my $b ;
myRead($b, 1);
return ($b, unpack "C", $b);
}
sub seekTo
{
my $offset = shift ;
my $loc = shift ;
$loc = SEEK_SET
if ! defined $loc ;
$FH->seek($offset, $loc);
$OFFSET = $FH->tell();
}
sub rewindRelative
{
my $offset = shift ;
$FH->seek(-$offset, SEEK_CUR);
# $OFFSET -= $offset;
$OFFSET = $FH->tell();
}
sub deltaToNextSignature
{
my $start = $FH->tell();
my $got = scanForSignature(1);
my $delta = $FH->tell() - $start ;
seekTo($start);
if ($got)
{
return $delta ;
}
return 0 ;
}
sub scanForSignature
{
my $walk = shift // 0;
# $count is only used to when 'walk' is enabled.
# Want to scan for a PK header at the start of the file.
# All other PK headers are should be directly after the previous PK record.
state $count = 0;
$count += $walk;
my %sigs = Signatures::getSigsForScan();
my $start = $FH->tell();
# TODO -- Fix this?
if (1 || $count <= 1) {
my $last = '';
my $offset = 0;
my $buffer ;
BUFFER:
while ($FH->read($buffer, 1024 * 1000))
{
my $combine = $last . $buffer ;
my $ix = 0;
while (1)
{
$ix = index($combine, "PK", $ix) ;
if ($ix == -1)
{
$last = '';
next BUFFER;
}
my $rest = substr($combine, $ix + 2, 2);
if (! $sigs{$rest})
{
$ix += 2;
next;
}
# possible match
my $here = $FH->tell();
seekTo($here - length($combine) + $ix);
my $name = Signatures::name($sigs{$rest});
return $sigs{$rest};
}
$last = substr($combine, $ix+4);
}
}
else {
die "FIX THIS";
return ! $FH->eof();
}
# printf("scanForSignature %X\t%X (%X)\t%s\n", $start, $FH->tell(), $FH->tell() - $start, 'NO MATCH') ;
return 0;
}
my $is64In32 = 0;
my $opt_verbose = 0;
my $opt_scan = 0;
my $opt_walk = 0;
my $opt_Redact = 0;
my $opt_utc = 0;
my $opt_want_info_mesages = 1;
my $opt_want_warning_mesages = 1;
my $opt_want_error_mesages = 1;
my $opt_want_message_exit_status = 0;
my $exit_status_code = 0;
my $opt_help =0;
$Getopt::Long::bundling = 1 ;
TextEncoding::setDefaults();
GetOptions("h|help" => \$opt_help,
"v" => \$opt_verbose,
"scan" => \$opt_scan,
"walk" => \$opt_walk,
"redact" => \$opt_Redact,
"utc" => \$opt_utc,
"version" => sub { print "$VERSION\n"; exit },
# Filename/comment encoding
"encoding=s" => \&TextEncoding::parseEncodingOption,
"no-encoding" => \&TextEncoding::NoEncoding,
"debug-encoding" => \&TextEncoding::debugEncoding,
"output-encoding=s" => \&TextEncoding::parseEncodingOption,
"language-encoding!" => \&TextEncoding::LanguageEncodingFlag,
# Message control
"exit-bitmask!" => \$opt_want_message_exit_status,
"messages!" => sub {
my ($opt_name, $opt_value) = @_;
$opt_want_info_mesages =
$opt_want_warning_mesages =
$opt_want_error_mesages = $opt_value;
},
)
or exit 255 ;
Usage()
if $opt_help;
die("No zipfile\n")
unless @ARGV == 1;
die("Cannot specify both '--walk' and '--scan'\n")
if $opt_walk && $opt_scan ;
my $filename = shift @ARGV;
topLevelFatal "No such file"
unless -e $filename ;
topLevelFatal "'$filename' is a directory"
if -d $filename ;
topLevelFatal "'$filename' is not a standard file"
unless -f $filename ;
$FH = IO::File->new( "<$filename" )
or topLevelFatal "Cannot open '$filename': $!";
binmode($FH);
displayFileInfo($filename);
TextEncoding::encodingInfo();
my $FILELEN = -s $filename ;
$TRAILING = -s $filename ;
$NIBBLES = nibbles(-s $filename) ;
topLevelFatal "'$filename' is empty"
if $FILELEN == 0 ;
topLevelFatal "file is too short to be a zip file"
if $FILELEN < ZIP_EOCD_MIN_SIZE ;
setupFormat($opt_verbose, $NIBBLES);
my @Messages = ();
if ($opt_scan || $opt_walk)
{
# Main loop for walk/scan processing
my $foundZipRecords = 0;
my $foundCentralHeader = 0;
my $lastEndsAt = 0;
my $lastSignature = 0;
my $lastHeader = {};
$CentralDirectory->{alreadyScanned} = 1 ;
my $output_encryptedCD = 0;
reportPrefixData();
while(my $s = scanForSignature($opt_walk))
{
my $here = $FH->tell();
my $delta = $here - $lastEndsAt ;
# delta can only be negative when '--scan' is used
if ($delta < 0 )
{
# nested or overlap
# check if nested
# remember & check if matching entry in CD
# printf("### WARNING: OVERLAP/NESTED Record found 0x%X 0x%X $delta\n", $here, $lastEndsAt) ;
}
elsif ($here != $lastEndsAt)
{
# scanForSignature had to skip bytes to find the next signature
# some special cases that don't have signatures need to be checked first
seekTo($lastEndsAt);
if (! $output_encryptedCD && $CentralDirectory->isEncryptedCD())
{
displayEncryptedCD();
$output_encryptedCD = 1;
$lastEndsAt = $FH->tell();
next;
}
elsif ($lastSignature == ZIP_LOCAL_HDR_SIG && $lastHeader->{'streamed'} )
{
# Check for size of possibe malformed Data Descriptor before outputting payload
if (! $lastHeader->{'gotDataDescriptorSize'})
{
my $hdrSize = checkForBadlyFormedDataDescriptor($lastHeader, $delta) ;
if ($hdrSize)
{
# remove size of Data Descriptor from payload
$delta -= $hdrSize;
$lastHeader->{'gotDataDescriptorSize'} = $hdrSize;
}
}
if(defined($lastHeader->{'payloadOutput'}) && ($lastEndsAt = BadlyFormedDataDescriptor($lastHeader, $delta)))
{
$HeaderOffsetIndex->rewindIndex();
$lastHeader->{entry}->readDataDescriptor(1) ;
next;
}
# Assume we have the payload when streaming is enabled
outSomeData($delta, "PAYLOAD", $opt_Redact) ;
$lastHeader->{'payloadOutput'} = 1;
$lastEndsAt = $FH->tell();
next;
}
elsif (Signatures::isCentralHeader($s) && $foundCentralHeader == 0)
{
# check for an APK header directly before the first central header
$foundCentralHeader = 1;
($START_APK, $APK, $APK_LEN) = chckForAPKSigningBlock($FH, $here, 0) ;
if ($START_APK)
{
seekTo($lastEndsAt+4);
scanApkBlock();
$lastEndsAt = $FH->tell();
next;
}
seekTo($lastEndsAt);
}
# Not a special case, so output generic padding message
if ($delta > 0)
{
reportPrefixData($delta)
if $lastEndsAt == 0 ;
outSomeDataParagraph($delta, "UNEXPECTED PADDING");
info $FH->tell() - $delta, decimalHex0x($delta) . " Unexpected Padding bytes"
if $FH->tell() - $delta ;
$POSSIBLE_PREFIX_DELTA = $delta
if $lastEndsAt == 0;
$lastEndsAt = $FH->tell();
next;
}
else
{
seekTo($here);
}
}
my ($buffer, $signature) = read_V();
$lastSignature = $signature;
my $handler = Signatures::decoder($signature);
if (!defined $handler) {
internalFatal undef, "xxx";
}
$foundZipRecords = 1;
$lastHeader = $handler->($signature, $buffer, $FH->tell() - 4) // {'streamed' => 0};
$lastEndsAt = $FH->tell();
seekTo($here + 4)
if $opt_scan;
}
topLevelFatal "'$filename' is not a zip file"
unless $foundZipRecords ;
}
else
{
# Main loop for non-walk/scan processing
# check for prefix data
my $s = scanForSignature();
if ($s && $FH->tell() != 0)
{
$POSSIBLE_PREFIX_DELTA = $FH->tell();
}
seekTo(0);
scanCentralDirectory($FH);
fatal_tryWalk undef, "No Zip metadata found at end of file"
if ! $CentralDirectory->exists() && ! $EOCD_Present ;
$CentralDirectory->{alreadyScanned} = 1 ;
Nesting::clearStack();
# $HeaderOffsetIndex->dump();
$OFFSET = 0 ;
$FH->seek(0, SEEK_SET) ;
my $expectedOffset = 0;
my $expectedSignature = 0;
my $expectedBuffer = 0;
my $foundCentralHeader = 0;
my $processedAPK = 0;
my $processedECD = 0;
my $lastHeader ;
# my $lastWasLocalHeader = 0;
# my $inCentralHeader = 0;
while (1)
{
last if $FH->eof();
my $here = $FH->tell();
if ($here >= $TRAILING) {
my $delta = $FILELEN - $TRAILING;
outSomeDataParagraph($delta, "TRAILING DATA");
info $FH->tell(), "Unexpected Trailing Data: " . decimalHex0x($delta) . " bytes";
last;
}
my ($buffer, $signature) = read_V();
$expectedOffset = undef;
$expectedSignature = undef;
# Check for split archive marker at start of file
if ($here == 0 && $signature == ZIP_SINGLE_SEGMENT_MARKER)
{
# let it drop through
$expectedSignature = ZIP_SINGLE_SEGMENT_MARKER;
$expectedOffset = 0;
}
else
{
my $expectedEntry = $HeaderOffsetIndex->getNextIndex() ;
if ($expectedEntry)
{
$expectedOffset = $expectedEntry->offset();
$expectedSignature = $expectedEntry->signature();
$expectedBuffer = pack "V", $expectedSignature ;
}
}
my $delta = $expectedOffset - $here ;
# if ($here != $expectedOffset && $signature != ZIP_DATA_HDR_SIG)
# {
# rewindRelative(4);
# my $delta = $expectedOffset - $here ;
# outSomeDataParagraph($delta, "UNEXPECTED PADDING");
# $HeaderOffsetIndex->rewindIndex();
# next;
# }
# Need to check for use-case where
# * there is a ZIP_DATA_HDR_SIG directly after a ZIP_LOCAL_HDR_SIG.
# The HeaderOffsetIndex object doesn't have visibility of it.
# * APK header directly before the CD
# * zipbomb
if (defined $expectedOffset && $here != $expectedOffset && ( $CentralDirectory->exists() || $EOCD_Present) )
{
if ($here > $expectedOffset)
{
# Probable zipbomb
# Cursor $OFFSET need to rewind
$OFFSET = $expectedOffset;
$FH->seek($OFFSET + 4, SEEK_SET) ;
$signature = $expectedSignature;
$buffer = $expectedBuffer ;
}
# If get here then $here is less than $expectedOffset
# check for an APK header directly before the first central header
# Make sure not to miss a streaming data descriptor
if ($signature != ZIP_DATA_HDR_SIG && Signatures::isCentralHeader($expectedSignature) && $START_APK && ! $processedAPK )
{
seekTo($here+4);
# rewindRelative(4);
scanApkBlock();
$HeaderOffsetIndex->rewindIndex();
$processedAPK = 1;
next;
}
# Check Encrypted Central Directory
# if ($CentralHeaderSignatures{$expectedSignature} && $CentralDirectory->isEncryptedCD() && ! $processedECD)
# {
# # rewind the invalid signature
# seekTo($here);
# # rewindRelative(4);
# displayEncryptedCD();
# $processedECD = 1;
# next;
# }
if ($signature != ZIP_DATA_HDR_SIG && $delta >= 0)
{
rewindRelative(4);
if($lastHeader->{'streamed'} && BadlyFormedDataDescriptor($lastHeader, $delta))
{
$lastHeader->{entry}->readDataDescriptor(1) ;
$HeaderOffsetIndex->rewindIndex();
next;
}
reportPrefixData($delta)
if $here == 0;
outSomeDataParagraph($delta, "UNEXPECTED PADDING");
info $FH->tell() - $delta, decimalHex0x($delta) . " Unexpected Padding bytes"
if $FH->tell() - $delta ;
$HeaderOffsetIndex->rewindIndex();
next;
}
# ZIP_DATA_HDR_SIG drops through
}
my $handler = Signatures::decoder($signature);
if (!defined $handler)
{
# if ($CentralDirectory->exists()) {
# # Should be at offset that central directory says
# my $locOffset = $CentralDirectory->getNextLocalOffset();
# my $delta = $locOffset - $here ;
# if ($here + 4 == $locOffset ) {
# for (0 .. 3) {
# $FH->ungetc(ord(substr($buffer, $_, 1)))
# }
# outSomeData($delta, "UNEXPECTED PADDING");
# next;
# }
# }
# if ($here == $CentralDirectory->{CentralDirectoryOffset} && $EOCD_Present && $CentralDirectory->isEncryptedCD())
# {
# # rewind the invalid signature
# rewindRelative(4);
# displayEncryptedCD();
# next;
# }
# elsif ($here < $CentralDirectory->{CentralDirectoryOffset})
# {
# # next
# # if scanForSignature() ;
# my $skippedFrom = $FH->tell() ;
# my $skippedContent = $CentralDirectory->{CentralDirectoryOffset} - $skippedFrom ;
# printf "\nWARNING!\nExpected Zip header not found at offset 0x%X\n", $here;
# printf "Skipping 0x%X bytes to Central Directory...\n", $skippedContent;
# push @Messages,
# sprintf("Expected Zip header not found at offset 0x%X, ", $skippedFrom) .
# sprintf("skipped 0x%X bytes\n", $skippedContent);
# seekTo($CentralDirectory->{CentralDirectoryOffset});
# next;
# }
# else
{
fatal $here, sprintf "Unexpected Zip Signature '%s' at offset %s", Value_V($signature), decimalHex0x($here) ;
last;
}
}
$ZIP64 = 0 if $signature != ZIP_DATA_HDR_SIG ;
$lastHeader = $handler->($signature, $buffer, $FH->tell() - 4);
# $lastWasLocalHeader = $signature == ZIP_LOCAL_HDR_SIG ;
$HeaderOffsetIndex->rewindIndex()
if $signature == ZIP_DATA_HDR_SIG ;
}
}
dislayMessages()
if $opt_want_error_mesages ;
exit $exit_status_code ;
sub dislayMessages
{
# Compare Central & Local for discrepencies
if ($CentralDirectory->isMiniZipEncrypted)
{
# don't compare local & central entries when minizip-ng encryption is in play
info undef, "Zip file uses minizip-ng central directory encryption"
}
elsif ($CentralDirectory->exists() && $LocalDirectory->exists())
{
# TODO check number of entries matches eocd
# TODO check header length matches reality
# Nesting::dump();
$LocalDirectory->sortByLocalOffset();
my %cleanCentralEntries = %{ $CentralDirectory->{byCentralOffset} };
if ($NESTING_DEBUG)
{
if (Nesting::encapsulationCount())
{
say "# ENCAPSULATIONS";
for my $index (sort { $a <=> $b } keys %{ Nesting::encapsulations() })
{
my $outer = Nesting::entryByIndex($index) ;
say "# Nesting " . $outer->outputFilename . " " . $outer->offsetStart . " " . $outer->offsetEnd ;
for my $inner (sort { $a <=> $b } @{ Nesting::encapsulations()->{$index} } )
{
say "# " . $inner->outputFilename . " " . $inner->offsetStart . " " . $inner->offsetEnd ;;
}
}
}
}
{
# check for Local Directory orphans
my %orphans = map { $_->localHeaderOffset => $_->outputFilename }
grep { $_->entryType == ZIP_LOCAL_HDR_SIG && # Want Local Headers
! $_->encapsulated &&
@{ $_->getCdEntries } == 0
}
values %{ Nesting::getEntriesByOffset() };
if (keys %orphans)
{
error undef, "Orphan Local Headers found: " . scalar(keys %orphans) ;
my $table = new SimpleTable;
$table->addHeaderRow('Offset', 'Filename');
$table->addDataRow(decimalHex0x($_), $orphans{$_})
for sort { $a <=> $b } keys %orphans ;
$table->display();
}
}
{
# check for Central Directory orphans
# probably only an issue with --walk & a zipbomb
my %orphans = map { $_->centralHeaderOffset => $_ }
grep { $_->entryType == ZIP_CENTRAL_HDR_SIG # Want Central Headers
&& ! $_->ldEntry # Filter out orphans
&& ! $_->encapsulated # Not encapsulated
}
values %{ Nesting::getEntriesByOffset() };
if (keys %orphans)
{
error undef, "Possible zipbomb -- Orphan Central Headers found: " . scalar(keys %orphans) ;
my $table = new SimpleTable;
$table->addHeaderRow('Offset', 'Filename');
for (sort { $a <=> $b } keys %orphans )
{
$table->addDataRow(decimalHex0x($_), $orphans{$_}{filename});
delete $cleanCentralEntries{ $_ };
}
$table->display();
}
}
if (Nesting::encapsulationCount())
{
# Benign Nested zips
# This is the use-case where a zip file is "stored" in another zip file.
# NOT a zipbomb -- want the benign nested entries
# Note: this is only active when scan is used
my %outerEntries = map { $_->localHeaderOffset => $_->outputFilename }
grep {
$_->entryType == ZIP_CENTRAL_HDR_SIG &&
! $_->encapsulated && # not encapsulated
$_->ldEntry && # central header has a local sibling
$_->ldEntry->childrenCount && # local entry has embedded entries
! Nesting::childrenInCentralDir($_->ldEntry)
}
values %{ Nesting::getEntriesByOffset() };
if (keys %outerEntries)
{
my $count = scalar keys %outerEntries;
info undef, "Nested Zip files found: $count";
my $table = new SimpleTable;
$table->addHeaderRow('Offset', 'Filename');
$table->addDataRow(decimalHex0x($_), $outerEntries{$_})
for sort { $a <=> $b } keys %outerEntries ;
$table->display();
}
}
if ($LocalDirectory->anyStreamedEntries)
{
# Check for a missing Data Descriptors
my %missingDataDescriptor = map { $_->localHeaderOffset => $_->outputFilename }
grep { $_->entryType == ZIP_LOCAL_HDR_SIG &&
$_->streamed &&
! $_->readDataDescriptor
}
values %{ Nesting::getEntriesByOffset() };
for my $offset (sort keys %missingDataDescriptor)
{
my $filename = $missingDataDescriptor{$offset};
error $offset, "Filename '$filename': Missing 'Data Descriptor'" ;
}
}
{
# compare local & central for duplicate entries (CD entries point to same local header)
my %ByLocalOffset = map { $_->localHeaderOffset => $_ }
grep {
$_->entryType == ZIP_LOCAL_HDR_SIG # Want Local Headers
&& ! $_->encapsulated # Not encapsulated
&& @{ $_->getCdEntries } > 1
}
values %{ Nesting::getEntriesByOffset() };
for my $offset (sort keys %ByLocalOffset)
{
my @entries = @{ $ByLocalOffset{$offset}->getCdEntries };
if (@entries > 1)
{
# found duplicates
my $localEntry = $LocalDirectory->getByLocalOffset($offset) ;
if ($localEntry)
{
error undef, "Possible zipbomb -- Duplicate Central Headers referring to one Local header for '" . $localEntry->outputFilename . "' at offset " . decimalHex0x($offset);
}
else
{
error undef, "Possible zipbomb -- Duplicate Central Headers referring to one Local header at offset " . decimalHex0x($offset);
}
my $table = new SimpleTable;
$table->addHeaderRow('Offset', 'Filename');
for (sort { $a->centralHeaderOffset <=> $b->centralHeaderOffset } @entries)
{
$table->addDataRow(decimalHex0x($_->centralHeaderOffset), $_->outputFilename);
delete $cleanCentralEntries{ $_->centralHeaderOffset };
}
$table->display();
}
}
}
if (Nesting::encapsulationCount())
{
# compare local & central for nested entries
# get the local offsets referenced in the CD
# this deliberately ignores any valid nested local entries
my @localOffsets = sort { $a <=> $b } keys %{ $CentralDirectory->{byLocalOffset} };
# now check for nesting
my %nested ;
my %bomb;
for my $offset (@localOffsets)
{
my $innerEntry = $LocalDirectory->{byLocalOffset}{$offset};
if ($innerEntry)
{
my $outerLocalEntry = Nesting::getOuterEncapsulation($innerEntry);
if (defined $outerLocalEntry)
{
my $outerOffset = $outerLocalEntry->localHeaderOffset();
if ($CentralDirectory->{byLocalOffset}{ $offset })
{
push @{ $bomb{ $outerOffset } }, $offset ;
}
else
{
push @{ $nested{ $outerOffset } }, $offset ;
}
}
}
}
if (keys %nested)
{
# The real central directory at eof does not know about these.
# likely to be a zip file stored in another zip file
warning undef, "Nested Local Entries found";
for my $loc (sort keys %nested)
{
my $count = scalar @{ $nested{$loc} };
my $outerEntry = $LocalDirectory->getByLocalOffset($loc);
say "Local Header for '" . $outerEntry->outputFilename . "' at offset " . decimalHex0x($loc) . " has $count nested Local Headers";
for my $n ( @{ $nested{$loc} } )
{
my $innerEntry = $LocalDirectory->getByLocalOffset($n);
say "# Nested Local Header for filename '" . $innerEntry->outputFilename . "' is at Offset " . decimalHex0x($n) ;
}
}
}
if (keys %bomb)
{
# Central Directory knows about these, so this is a zipbomb
error undef, "Possible zipbomb -- Nested Local Entries found";
for my $loc (sort keys %bomb)
{
my $count = scalar @{ $bomb{$loc} };
my $outerEntry = $LocalDirectory->getByLocalOffset($loc);
say "# Local Header for '" . $outerEntry->outputFilename . "' at offset " . decimalHex0x($loc) . " has $count nested Local Headers";
my $table = new SimpleTable;
$table->addHeaderRow('Offset', 'Filename');
$table->addDataRow(decimalHex0x($_), $LocalDirectory->getByLocalOffset($_)->outputFilename)
for sort @{ $bomb{$loc} } ;
$table->display();
delete $cleanCentralEntries{ $_ }
for grep { defined $_ }
map { $CentralDirectory->{byLocalOffset}{$_}{centralHeaderOffset} }
@{ $bomb{$loc} } ;
}
}
}
# Check if contents of local headers match with central headers
#
# When central header encryption is used the local header values are masked (see APPNOTE 6.3.10, sec 4)
# In this usecase the central header will appear to be absent
#
# key fields
# filename, compressed/uncompessed lengths, crc, compression method
{
for my $centralEntry ( sort { $a->centralHeaderOffset() <=> $b->centralHeaderOffset() } values %cleanCentralEntries )
{
my $localOffset = $centralEntry->localHeaderOffset;
my $localEntry = $LocalDirectory->getByLocalOffset($localOffset);
next
unless $localEntry;
state $fields = [
# field name offset display name stringify
['filename', ZIP_CD_FILENAME_OFFSET,
'Filename', undef, ],
['extractVersion', 7, 'Extract Zip Spec', sub { decimalHex0xUndef($_[0]) . " " . decodeZipVer($_[0]) }, ],
['generalPurposeFlags', 8, 'General Purpose Flag', \&decimalHex0xUndef, ],
['compressedMethod', 10, 'Compression Method', sub { decimalHex0xUndef($_[0]) . " " . getcompressionMethodName($_[0]) }, ],
['lastModDateTime', 12, 'Modification Time', sub { decimalHex0xUndef($_[0]) . " " . LastModTime($_[0]) }, ],
['crc32', 16, 'CRC32', \&decimalHex0xUndef, ],
['compressedSize', 20, 'Compressed Size', \&decimalHex0xUndef, ],
['uncompressedSize', 24, 'Uncompressed Size', \&decimalHex0xUndef, ],
] ;
my $table = new SimpleTable;
$table->addHeaderRow('Field Name', 'Central Offset', 'Central Value', 'Local Offset', 'Local Value');
for my $data (@$fields)
{
my ($field, $offset, $name, $stringify) = @$data;
# if the local header uses streaming and we are running a scan/walk, the compressed/uncompressed sizes will not be known
my $localValue = $localEntry->{$field} ;
my $centralValue = $centralEntry->{$field};
if (($localValue // '-1') ne ($centralValue // '-2'))
{
if ($stringify)
{
$localValue = $stringify->($localValue);
$centralValue = $stringify->($centralValue);
}
$table->addDataRow($name,
decimalHex0xUndef($centralEntry->centralHeaderOffset() + $offset),
$centralValue,
decimalHex0xUndef($localOffset+$offset),
$localValue);
}
}
my $badFields = $table->hasData;
if ($badFields)
{
error undef, "Found $badFields Field Mismatch for Filename '". $centralEntry->outputFilename . "'";
$table->display();
}
}
}
}
elsif ($CentralDirectory->exists())
{
my @messages = "Central Directory exists, but Local Directory not found" ;
push @messages , "Try running with --walk' or '--scan' options"
unless $opt_scan || $opt_walk ;
error undef, @messages;
}
elsif ($LocalDirectory->exists())
{
if ($CentralDirectory->isEncryptedCD())
{
warning undef, "Local Directory exists, but Central Directory is encrypted"
}
else
{
error undef, "Local Directory exists, but Central Directory not found"
}
}
if ($ErrorCount ||$WarningCount || $InfoCount )
{
say "#"
unless $lastWasMessage ;
say "# Error Count: $ErrorCount"
if $ErrorCount;
say "# Warning Count: $WarningCount"
if $WarningCount;
say "# Info Count: $InfoCount"
if $InfoCount;
}
if (@Messages)
{
my $count = scalar @Messages ;
say "#\nWARNINGS";
say "# * $_\n" for @Messages ;
}
say "#\n# Done";
}
sub checkForBadlyFormedDataDescriptor
{
my $lastHeader = shift;
my $delta = shift // 0;
# check size of delta - a DATA HDR without a signature can only be
# 12 bytes for 32-bit
# 20 bytes for 64-bit
my $here = $FH->tell();
my $localEntry = $lastHeader->{entry};
return 0
unless $opt_scan || $opt_walk ;
# delta can be the actual payload + a data descriptor without a sig
my $signature = unpack "V", peekAtOffset($here + $delta, 4);
if ($signature == ZIP_DATA_HDR_SIG)
{
return 0;
}
my $cl32 = unpack "V", peekAtOffset($here + $delta - 8, 4);
my $cl64 = unpack "Q<", peekAtOffset($here + $delta - 16, 8);
if ($cl32 == $delta - 12)
{
return 12;
}
if ($cl64 == $delta - 20)
{
return 20 ;
}
return 0;
}
sub BadlyFormedDataDescriptor
{
my $lastHeader= shift;
my $delta = shift;
# check size of delta - a DATA HDR without a signature can only be
# 12 bytes for 32-bit
# 20 bytes for 64-bit
my $here = $FH->tell();
my $localEntry = $lastHeader->{entry};
my $compressedSize = $lastHeader->{payloadLength} ;
my $sigName = Signatures::titleName(ZIP_DATA_HDR_SIG);
if ($opt_scan || $opt_walk)
{
# delta can be the actual payload + a data descriptor without a sig
if ($lastHeader->{'gotDataDescriptorSize'} == 12)
{
# seekTo($FH->tell() + $delta - 12) ;
# outSomeData($delta - 12, "PAYLOAD", $opt_Redact) ;
print "\n";
out1 "Missing $sigName Signature", Value_V(ZIP_DATA_HDR_SIG);
error $FH->tell(), "Missimg $sigName Signature";
$localEntry->crc32( out_V "CRC");
$localEntry->compressedSize( out_V "Compressed Size");
$localEntry->uncompressedSize( out_V "Uncompressed Size");
if ($localEntry->zip64)
{
error $here, "'$sigName': expected 64-bit values, got 32-bit";
}
return $FH->tell();
}
if ($lastHeader->{'gotDataDescriptorSize'} == 20)
{
# seekTo($FH->tell() + $delta - 20) ;
# outSomeData($delta - 20, "PAYLOAD", $opt_Redact) ;
print "\n";
out1 "Missing $sigName Signature", Value_V(ZIP_DATA_HDR_SIG);
error $FH->tell(), "Missimg $sigName Signature";
$localEntry->crc32( out_V "CRC");
$localEntry->compressedSize( out_Q "Compressed Size");
$localEntry->uncompressedSize( out_Q "Uncompressed Size");
if (! $localEntry->zip64)
{
error $here, "'$sigName': expected 32-bit values, got 64-bit";
}
return $FH->tell();
}
error 0, "MISSING $sigName";
seekTo($here);
return 0;
}
my $cdEntry = $localEntry->getCdEntry;
if ($delta == 12)
{
$FH->seek($lastHeader->{payloadOffset} + $lastHeader->{payloadLength}, SEEK_SET) ;
my $cl = unpack "V", peekAtOffset($FH->tell() + 4, 4);
if ($cl == $compressedSize)
{
print "\n";
out1 "Missing $sigName Signature", Value_V(ZIP_DATA_HDR_SIG);
error $FH->tell(), "Missimg $sigName Signature";
$localEntry->crc32( out_V "CRC");
$localEntry->compressedSize( out_V "Compressed Size");
$localEntry->uncompressedSize( out_V "Uncompressed Size");
if ($localEntry->zip64)
{
error $here, "'$sigName': expected 64-bit values, got 32-bit";
}
return $FH->tell();
}
}
if ($delta == 20)
{
$FH->seek($lastHeader->{payloadOffset} + $lastHeader->{payloadLength}, SEEK_SET) ;
my $cl = unpack "Q<", peekAtOffset($FH->tell() + 4, 8);
if ($cl == $compressedSize)
{
print "\n";
out1 "Missing $sigName Signature", Value_V(ZIP_DATA_HDR_SIG);
error $FH->tell(), "Missimg $sigName Signature";
$localEntry->crc32( out_V "CRC");
$localEntry->compressedSize( out_Q "Compressed Size");
$localEntry->uncompressedSize( out_Q "Uncompressed Size");
if (! $localEntry->zip64 && ( $cdEntry && ! $cdEntry->zip64))
{
error $here, "'$sigName': expected 32-bit values, got 64-bit";
}
return $FH->tell();
}
}
seekTo($here);
error $here, "Missing $sigName";
return 0;
}
sub getcompressionMethodName
{
my $id = shift ;
" '" . ($ZIP_CompressionMethods{$id} || "Unknown Method") . "'" ;
}
sub compressionMethod
{
my $id = shift ;
Value_v($id) . getcompressionMethodName($id);
}
sub LocalHeader
{
my $signature = shift ;
my $data = shift ;
my $startRecordOffset = shift ;
my $locHeaderOffset = $FH->tell() -4 ;
++ $LocalHeaderCount;
print "\n";
out $data, "LOCAL HEADER #$LocalHeaderCount" , Value_V($signature);
need 26, Signatures::name($signature);
my $buffer;
my $orphan = 0;
my ($loc, $CDcompressedSize, $cdZip64, $zip64Sizes, $cdIndex, $cdEntryOffset) ;
my $CentralEntryExists = $CentralDirectory->localOffset($startRecordOffset);
my $localEntry = LocalDirectoryEntry->new();
my $cdEntry;
if (! $opt_scan && ! $opt_walk && $CentralEntryExists)
{
$cdEntry = $CentralDirectory->getByLocalOffset($startRecordOffset);
if (! $cdEntry)
{
out1 "Orphan Entry: No matching central directory" ;
$orphan = 1 ;
}
$cdZip64 = $cdEntry->zip64ExtraPresent;
$zip64Sizes = $cdEntry->zip64SizesPresent;
$cdEntryOffset = $cdEntry->centralHeaderOffset ;
$localEntry->addCdEntry($cdEntry) ;
if ($cdIndex && $cdIndex != $LocalHeaderCount)
{
# fatal undef, "$cdIndex != $LocalHeaderCount"
}
}
my $extractVer = out_C "Extract Zip Spec", \&decodeZipVer;
out_C "Extract OS", \&decodeOS;
my ($bgp, $gpFlag) = read_v();
my ($bcm, $compressedMethod) = read_v();
out $bgp, "General Purpose Flag", Value_v($gpFlag) ;
GeneralPurposeBits($compressedMethod, $gpFlag);
my $LanguageEncodingFlag = $gpFlag & ZIP_GP_FLAG_LANGUAGE_ENCODING ;
my $streaming = $gpFlag & ZIP_GP_FLAG_STREAMING_MASK ;
$localEntry->languageEncodingFlag($LanguageEncodingFlag) ;
out $bcm, "Compression Method", compressionMethod($compressedMethod) ;
info $FH->tell() - 2, "Unknown 'Compression Method' ID " . decimalHex0x($compressedMethod, 2)
if ! defined $ZIP_CompressionMethods{$compressedMethod} ;
my $lastMod = out_V "Modification Time", sub { LastModTime($_[0]) };
my $crc = out_V "CRC";
warning $FH->tell() - 4, "CRC field should be zero when streaming is enabled"
if $streaming && $crc != 0 ;
my $compressedSize = out_V "Compressed Size";
# warning $FH->tell(), "Compressed Size should be zero when streaming is enabled";
my $uncompressedSize = out_V "Uncompressed Size";
# warning $FH->tell(), "Uncompressed Size should be zero when streaming is enabled";
my $filenameLength = out_v "Filename Length";
if ($filenameLength == 0)
{
info $FH->tell()- 2, "Zero Length filename";
}
my $extraLength = out_v "Extra Length";
my $filename = '';
if ($filenameLength)
{
need $filenameLength, Signatures::name($signature), 'Filename';
myRead(my $raw_filename, $filenameLength);
$localEntry->filename($raw_filename) ;
$filename = outputFilename($raw_filename, $LanguageEncodingFlag);
$localEntry->outputFilename($filename);
}
$localEntry->localHeaderOffset($locHeaderOffset) ;
$localEntry->offsetStart($locHeaderOffset) ;
$localEntry->compressedSize($compressedSize) ;
$localEntry->uncompressedSize($uncompressedSize) ;
$localEntry->extractVersion($extractVer);
$localEntry->generalPurposeFlags($gpFlag);
$localEntry->lastModDateTime($lastMod);
$localEntry->crc32($crc) ;
$localEntry->zip64ExtraPresent($cdZip64) ;
$localEntry->zip64SizesPresent($zip64Sizes) ;
$localEntry->compressedMethod($compressedMethod) ;
$localEntry->streamed($gpFlag & ZIP_GP_FLAG_STREAMING_MASK) ;
$localEntry->std_localHeaderOffset($locHeaderOffset + $PREFIX_DELTA) ;
$localEntry->std_compressedSize($compressedSize) ;
$localEntry->std_uncompressedSize($uncompressedSize) ;
$localEntry->std_diskNumber(0) ;
if ($extraLength)
{
need $extraLength, Signatures::name($signature), 'Extra';
walkExtra($extraLength, $localEntry);
}
# APPNOTE 6.3.10, sec 4.3.8
warning $FH->tell - $filenameLength, "Directory '$filename' must not have a payload"
if ! $streaming && $filename =~ m#/$# && $localEntry->uncompressedSize ;
my @msg ;
# if ($cdZip64 && ! $ZIP64)
# {
# # Central directory said this was Zip64
# # some zip files don't have the Zip64 field in the local header
# # seems to be a streaming issue.
# push @msg, "Missing Zip64 extra field in Local Header #$hexHdrCount\n";
# if (! $zip64Sizes)
# {
# # Central has a ZIP64 entry that doesn't have sizes
# # Local doesn't have a Zip 64 at all
# push @msg, "Unzip may complain about 'overlapped components' #$hexHdrCount\n";
# }
# else
# {
# $ZIP64 = 1
# }
# }
my $minizip_encrypted = $localEntry->minizip_secure;
my $pk_encrypted = ($gpFlag & ZIP_GP_FLAG_STRONG_ENCRYPTED_MASK) && $compressedMethod != 99 && ! $minizip_encrypted;
# Detecting PK strong encryption from a local header is a bit convoluted.
# Cannot just use ZIP_GP_FLAG_ENCRYPTED_CD because minizip also uses this bit.
# so jump through some hoops
# extract ver is >= 5.0'
# all the encryption flags are set in gpflags
# TODO - add zero lengths for crc, compresssed & uncompressed
if (($gpFlag & ZIP_GP_FLAG_ALL_ENCRYPT) == ZIP_GP_FLAG_ALL_ENCRYPT && $extractVer >= 0x32 )
{
$CentralDirectory->setPkEncryptedCD()
}
my $size = 0;
# If no CD scanned, get compressed Size from local header.
# Zip64 extra field takes priority
my $cdl = defined $cdEntry
? $cdEntry->compressedSize()
: undef;
$CDcompressedSize = $localEntry->compressedSize ;
$CDcompressedSize = $cdl
if defined $cdl && $gpFlag & ZIP_GP_FLAG_STREAMING_MASK;
my $cdu = defined $CentralDirectory->{byLocalOffset}{$locHeaderOffset}
? $CentralDirectory->{byLocalOffset}{$locHeaderOffset}{uncompressedSize}
: undef;
my $CDuncompressedSize = $localEntry->uncompressedSize ;
$CDuncompressedSize = $cdu
if defined $cdu && $gpFlag & ZIP_GP_FLAG_STREAMING_MASK;
my $fullCompressedSize = $CDcompressedSize;
my $payloadOffset = $FH->tell();
$localEntry->payloadOffset($payloadOffset) ;
$localEntry->offsetEnd($payloadOffset + $fullCompressedSize -1) ;
if ($CDcompressedSize)
{
# check if enough left in file for the payload
my $available = $FILELEN - $FH->tell;
if ($available < $CDcompressedSize )
{
error $FH->tell,
"file truncated while reading 'PAYLOAD'",
expectedMessage($CDcompressedSize, $available);
$CDcompressedSize = $available;
}
}
# Next block can decrement the CDcompressedSize
# possiblty to zero. Need to remember if it started out
# as a non-zero value
my $haveCDcompressedSize = $CDcompressedSize;
if ($compressedMethod == 99 && $localEntry->aesValid) # AES Encryption
{
$CDcompressedSize -= printAes($localEntry)
}
elsif (($gpFlag & ZIP_GP_FLAG_ALL_ENCRYPT) == 0)
{
if ($compressedMethod == ZIP_CM_LZMA)
{
$size = printLzmaProperties()
}
$CDcompressedSize -= $size;
}
elsif ($pk_encrypted)
{
$CDcompressedSize -= DecryptionHeader();
}
if ($haveCDcompressedSize) {
if ($compressedMethod == 92 && $CDcompressedSize == 20) {
# Payload for a Reference is the SHA-1 hash of the uncompressed content
myRead(my $sha1, 20);
out $sha1, "PAYLOAD", "SHA-1 Hash: " . hexDump($sha1);
}
elsif ($compressedMethod == 99 && $localEntry->aesValid ) {
outSomeData($CDcompressedSize, "PAYLOAD", $opt_Redact) ;
my $auth ;
myRead($auth, 10);
out $auth, "AES Auth", hexDump16($auth);
}
else {
outSomeData($CDcompressedSize, "PAYLOAD", $opt_Redact) ;
}
}
print "WARNING: $_"
for @msg;
push @Messages, @msg ;
$LocalDirectory->addEntry($localEntry);
return {
'localHeader' => 1,
'streamed' => $gpFlag & ZIP_GP_FLAG_STREAMING_MASK,
'offset' => $startRecordOffset,
'length' => $FH->tell() - $startRecordOffset,
'payloadLength' => $fullCompressedSize,
'payloadOffset' => $payloadOffset,
'entry' => $localEntry,
} ;
}
use constant Pack_ZIP_DIGITAL_SIGNATURE_SIG => pack("V", ZIP_DIGITAL_SIGNATURE_SIG);
sub findDigitalSignature
{
my $cdSize = shift;
my $here = $FH->tell();
my $data ;
myRead($data, $cdSize);
seekTo($here);
# find SIG
my $ix = index($data, Pack_ZIP_DIGITAL_SIGNATURE_SIG);
if ($ix > -1)
{
# check size of signature meaans it is directly after the encrypted CD
my $sigSize = unpack "v", substr($data, $ix+4, 2);
if ($ix + 4 + 2 + $sigSize == $cdSize)
{
# return size of digital signature record
return 4 + 2 + $sigSize ;
}
}
return 0;
}
sub displayEncryptedCD
{
# First thing in the encrypted CD is the Decryption Header
my $decryptHeaderSize = DecryptionHeader(1);
# Check for digital signature record in the CD
# It needs to be the very last thing in the CD
my $delta = deltaToNextSignature();
print "\n";
outSomeData($delta, "ENCRYPTED CENTRAL DIRECTORY")
if $delta;
}
sub DecryptionHeader
{
# APPNOTE 6.3.10, sec 7.2.4
# -Decryption Header:
# Value Size Description
# ----- ---- -----------
# IVSize 2 bytes Size of initialization vector (IV)
# IVData IVSize Initialization vector for this file
# Size 4 bytes Size of remaining decryption header data
# Format 2 bytes Format definition for this record
# AlgID 2 bytes Encryption algorithm identifier
# Bitlen 2 bytes Bit length of encryption key
# Flags 2 bytes Processing flags
# ErdSize 2 bytes Size of Encrypted Random Data
# ErdData ErdSize Encrypted Random Data
# Reserved1 4 bytes Reserved certificate processing data
# Reserved2 (var) Reserved for certificate processing data
# VSize 2 bytes Size of password validation data
# VData VSize-4 Password validation data
# VCRC32 4 bytes Standard ZIP CRC32 of password validation data
my $central = shift ;
if ($central)
{
print "\n";
out "", "CENTRAL HEADER DECRYPTION RECORD";
}
else
{
print "\n";
out "", "DECRYPTION HEADER RECORD";
}
my $bytecount = 2;
my $IVSize = out_v "IVSize";
outHexdump($IVSize, "IVData");
$bytecount += $IVSize;
my $Size = out_V "Size";
$bytecount += $Size + 4;
out_v "Format";
out_v "AlgId", sub { $AlgIdLookup{ $_[0] } // "Unknown algorithm" } ;
out_v "BitLen";
out_v "Flags", sub { $FlagsLookup{ $_[0] } // "Reserved for certificate processing" } ;
my $ErdSize = out_v "ErdSize";
outHexdump($ErdSize, "ErdData");
my $Reserved1_RCount = out_V "RCount";
Reserved2($Reserved1_RCount);
my $VSize = out_v "VSize";
outHexdump($VSize-4, "VData");
out_V "VCRC32";
return $bytecount ;
}
sub Reserved2
{
# APPNOTE 6.3.10, sec 7.4.3 & 7.4.4
my $recipients = shift;
return 0
if $recipients == 0;
out_v "HashAlg", sub { $HashAlgLookup{ $_[0] } // "Unknown algorithm" } ;
my $HSize = out_v "HSize" ;
my $ix = 1;
for (0 .. $recipients-1)
{
my $hex = sprintf("Key #%X", $ix) ;
my $RESize = out_v "RESize $hex";
outHexdump($HSize, "REHData $hex");
outHexdump($RESize - $HSize, "REKData $hex");
++ $ix;
}
}
sub redactData
{
my $data = shift;
# Redact everything apart from directory seperators
$data =~ s(.)(X)g
if $opt_Redact;
return $data;
}
sub redactFilename
{
my $filename = shift;
# Redact everything apart from directory seperators
$filename =~ s(.)(X)g
if $opt_Redact;
return $filename;
}
sub validateDirectory
{
# Check that Directries are stored correctly
#
# 1. Filename MUST end with a "/"
# see APPNOTE 6.3.10, sec 4.3.8
# 2. Uncompressed size == 0
# see APPNOTE 6.3.10, sec 4.3.8
# 3. warn if compressed size > 0 and Uncompressed size == 0
# 4. check for presence of DOS directory attrib in External Attributes
# 5. Check for Unix extrnal attribute S_IFDIR
my $offset = shift ;
my $filename = shift ;
my $extractVersion = shift;
my $versionMadeBy = shift;
my $compressedSize = shift;
my $uncompressedSize = shift;
my $externalAttributes = shift;
my $dosAttributes = $externalAttributes & 0xFFFF;
my $otherAttributes = ($externalAttributes >> 16 ) & 0xFFFF;
my $probablyDirectory = 0;
my $filenameOK = 0;
my $attributesSet = 0;
my $dosAttributeSet = 0;
my $unixAttributeSet = 0;
if ($filename =~ m#/$#)
{
# filename claims it is a directory.
$probablyDirectory = 1;
$filenameOK = 1;
}
if ($dosAttributes & 0x0010) # ATTR_DIRECTORY
{
$probablyDirectory = 1;
$attributesSet = 1 ;
$dosAttributeSet = 1 ;
}
if ($versionMadeBy == 3 && $otherAttributes & 0x4000) # Unix & S_IFDIR
{
$probablyDirectory = 1;
$attributesSet = 1;
$unixAttributeSet = 1;
}
return
unless $probablyDirectory ;
error $offset + CentralDirectoryEntry::Offset_Filename(),
"Directory '$filename' must end in a '/'",
"'External Attributes' flag this as a directory"
if ! $filenameOK && $uncompressedSize == 0;
info $offset + CentralDirectoryEntry::Offset_ExternalAttributes(),
"DOS Directory flag not set in 'External Attributes' for Directory '$filename'"
if $filenameOK && ! $dosAttributeSet;
info $offset + CentralDirectoryEntry::Offset_ExternalAttributes(),
"Unix Directory flag not set in 'External Attributes' for Directory '$filename'"
if $filenameOK && $versionMadeBy == 3 && ! $unixAttributeSet;
if ($uncompressedSize != 0)
{
# APPNOTE 6.3.10, sec 4.3.8
error $offset + CentralDirectoryEntry::Offset_UncompressedSize(),
"Directory '$filename' must not have a payload"
}
elsif ($compressedSize != 0)
{
info $offset + CentralDirectoryEntry::Offset_CompressedSize(),
"Directory '$filename' has compressed payload that uncompresses to nothing"
}
if ($extractVersion < 20)
{
# APPNOTE 6.3.10, sec 4.4.3.2
my $got = decodeZipVer($extractVersion);
warning $offset + CentralDirectoryEntry::Offset_VersionNeededToExtract(),
"'Extract Zip Spec' is '$got'. Need value >= '2.0' for Directory '$filename'"
}
}
sub validateFilename
{
my $filename = shift ;
return "Zero length filename"
if $filename eq '' ;
# TODO
# - check length of filename
# getconf NAME_MAX . and getconf PATH_MAX . on Linux
# Start with APPNOTE restrictions
# APPNOTE 6.3.10, sec 4.4.17.1
#
# No absolute path
# No backslash delimeters
# No drive letters
return "Filename must not be an absolute path"
if $filename =~ m#^/#;
return ["Backslash detected in filename", "Possible Windows path."]
if $filename =~ m#\\#;
return "Windows Drive Letter '$1' not allowed in filename"
if $filename =~ /^([a-z]:)/i ;
# Slip Vulnerability with use of ".." in a relative path
# https://security.snyk.io/research/zip-slip-vulnerability
return ["Use of '..' in filename is a Zip Slip Vulnerability",
"See https://security.snyk.io/research/zip-slip-vulnerability" ]
if $filename =~ m#^\.\./# || $filename =~ m#/\.\./# || $filename =~ m#/\.\.# ;
# Cannot have "." or ".." as the full filename
return "Use of current-directory filename '.' may not unzip correctly"
if $filename eq '.' ;
return "Use of parent-directory filename '..' may not unzip correctly"
if $filename eq '..' ;
# Portability (mostly with Windows)
{
# see https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file
state $badDosFilename = join '|', map { quotemeta }
qw(CON PRN AUX NUL
COM1 COM2 COM3 COM4 COM5 COM6 COM7 COM8 COM9
LPT1 LPT2 LPT3 LPT4 LPT5 LPT6 LPT7 LPT8 LPT9
) ;
# if $filename contains any invalid codepoints, we will get a warning like this
#
# Operation "pattern match (m//)" returns its argument for non-Unicode code point
#
# so silence it for now.
no warnings;
return "Portability Issue: '$1' is a reserved Windows device name"
if $filename =~ /^($badDosFilename)$/io ;
# Can't have the device name with an extension either
return "Portability Issue: '$1' is a reserved Windows device name"
if $filename =~ /^($badDosFilename)\./io ;
}
state $illegal_windows_chars = join '|', map { quotemeta } qw( < > : " | ? * );
return "Portability Issue: Windows filename cannot contain '$1'"
if $filename =~ /($illegal_windows_chars)/o ;
return "Portability Issue: Null character '\\x00' is not allowed in a Windows or Linux filename"
if $filename =~ /\x00/ ;
return sprintf "Portability Issue: Control character '\\x%02X' is not allowed in a Windows filename", ord($1)
if $filename =~ /([\x00-\x1F])/ ;
return undef;
}
sub getOutputFilename
{
my $raw_filename = shift;
my $LanguageEncodingFlag = shift;
my $message = shift // "Filename";
my $filename ;
my $decoded_filename;
if ($raw_filename eq '')
{
if ($message eq 'Filename')
{
warning $FH->tell() ,
"Filename ''",
"Zero Length Filename" ;
}
return '', '', 0;
}
elsif ($opt_Redact)
{
return redactFilename($raw_filename), '', 0 ;
}
else
{
$decoded_filename = TextEncoding::decode($raw_filename, $message, $LanguageEncodingFlag) ;
$filename = TextEncoding::encode($decoded_filename, $message, $LanguageEncodingFlag) ;
}
return $filename, $decoded_filename, $filename ne $raw_filename ;
}
sub outputFilename
{
my $raw_filename = shift;
my $LanguageEncodingFlag = shift;
my $message = shift // "Filename";
my ($filename, $decoded_filename, $modified) = getOutputFilename($raw_filename, $LanguageEncodingFlag);
out $raw_filename, $message, "'". $filename . "'";
if (! $opt_Redact && TextEncoding::debugEncoding())
{
# use Devel::Peek;
# print "READ " ; Dump($raw_filename);
# print "INTERNAL " ; Dump($decoded_filename);
# print "OUTPUT " ; Dump($filename);
debug $FH->tell() - length($raw_filename),
"$message Encoding Change"
if $modified ;
# use Unicode::Normalize;
# my $NormaizedForm ;
# if (defined $decoded_filename)
# {
# $NormaizedForm .= Unicode::Normalize::checkNFD $decoded_filename ? 'NFD ' : '';
# $NormaizedForm .= Unicode::Normalize::checkNFC $decoded_filename ? 'NFC ' : '';
# $NormaizedForm .= Unicode::Normalize::checkNFKD $decoded_filename ? 'NFKD ' : '';
# $NormaizedForm .= Unicode::Normalize::checkNFKC $decoded_filename ? 'NFKC ' : '';
# $NormaizedForm .= Unicode::Normalize::checkFCD $decoded_filename ? 'FCD ' : '';
# $NormaizedForm .= Unicode::Normalize::checkFCC $decoded_filename ? 'FCC ' : '';
# }
debug $FH->tell() - length($raw_filename),
"Encoding Debug for $message",
"Octets Read from File [$raw_filename][" . length($raw_filename). "] [" . charDump2($raw_filename) . "]",
"Via Unicode Codepoints [$decoded_filename][" . length($decoded_filename) . "] [" . charDump($decoded_filename) . "]",
# "Unicode Normalization $NormaizedForm",
"Octets Written [$filename][" . length($filename). "] [" . charDump2($filename) . "]";
}
if ($message eq 'Filename' && $opt_want_warning_mesages)
{
# Check for bad, unsafe & not portable filenames
my $v = validateFilename($decoded_filename);
if ($v)
{
my @v = ref $v eq 'ARRAY'
? @$v
: $v;
warning $FH->tell() - length($raw_filename),
"Filename '$filename'",
@v
}
}
return $filename;
}
sub CentralHeader
{
my $signature = shift ;
my $data = shift ;
my $startRecordOffset = shift ;
my $cdEntryOffset = $FH->tell() - 4 ;
++ $CentralHeaderCount;
print "\n";
out $data, "CENTRAL HEADER #$CentralHeaderCount", Value_V($signature);
my $buffer;
need 42, Signatures::name($signature);
out_C "Created Zip Spec", \&decodeZipVer;
my $made_by = out_C "Created OS", \&decodeOS;
my $extractVer = out_C "Extract Zip Spec", \&decodeZipVer;
out_C "Extract OS", \&decodeOS;
my ($bgp, $gpFlag) = read_v();
my ($bcm, $compressedMethod) = read_v();
my $cdEntry = CentralDirectoryEntry->new($cdEntryOffset);
out $bgp, "General Purpose Flag", Value_v($gpFlag) ;
GeneralPurposeBits($compressedMethod, $gpFlag);
my $LanguageEncodingFlag = $gpFlag & ZIP_GP_FLAG_LANGUAGE_ENCODING ;
$cdEntry->languageEncodingFlag($LanguageEncodingFlag) ;
out $bcm, "Compression Method", compressionMethod($compressedMethod) ;
info $FH->tell() - 2, "Unknown 'Compression Method' ID " . decimalHex0x($compressedMethod, 2)
if ! defined $ZIP_CompressionMethods{$compressedMethod} ;
my $lastMod = out_V "Modification Time", sub { LastModTime($_[0]) };
my $crc = out_V "CRC";
my $compressedSize = out_V "Compressed Size";
my $std_compressedSize = $compressedSize;
my $uncompressedSize = out_V "Uncompressed Size";
my $std_uncompressedSize = $uncompressedSize;
my $filenameLength = out_v "Filename Length";
if ($filenameLength == 0)
{
info $FH->tell()- 2, "Zero Length filename";
}
my $extraLength = out_v "Extra Length";
my $comment_length = out_v "Comment Length";
my $disk_start = out_v "Disk Start";
my $std_disk_start = $disk_start;
my $int_file_attrib = out_v "Int File Attributes";
out1 "[Bit 0]", $int_file_attrib & 1 ? "1 'Text Data'" : "0 'Binary Data'";
out1 "[Bits 1-15]", Value_v($int_file_attrib & 0xFE) . " 'Unknown'"
if $int_file_attrib & 0xFE ;
my $ext_file_attrib = out_V "Ext File Attributes";
{
# MS-DOS Attributes are bottom two bytes
my $dos_attrib = $ext_file_attrib & 0xFFFF;
# See https://learn.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants
# and https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-smb/65e0c225-5925-44b0-8104-6b91339c709f
out1 "[Bit 0]", "Read-Only" if $dos_attrib & 0x0001 ;
out1 "[Bit 1]", "Hidden" if $dos_attrib & 0x0002 ;
out1 "[Bit 2]", "System" if $dos_attrib & 0x0004 ;
out1 "[Bit 3]", "Label" if $dos_attrib & 0x0008 ;
out1 "[Bit 4]", "Directory" if $dos_attrib & 0x0010 ;
out1 "[Bit 5]", "Archive" if $dos_attrib & 0x0020 ;
out1 "[Bit 6]", "Device" if $dos_attrib & 0x0040 ;
out1 "[Bit 7]", "Normal" if $dos_attrib & 0x0080 ;
out1 "[Bit 8]", "Temporary" if $dos_attrib & 0x0100 ;
out1 "[Bit 9]", "Sparse" if $dos_attrib & 0x0200 ;
out1 "[Bit 10]", "Reparse Point" if $dos_attrib & 0x0400 ;
out1 "[Bit 11]", "Compressed" if $dos_attrib & 0x0800 ;
out1 "[Bit 12]", "Offline" if $dos_attrib & 0x1000 ;
out1 "[Bit 13]", "Not Indexed" if $dos_attrib & 0x2000 ;
# Zip files created on Mac seem to set this bit. Not clear why.
out1 "[Bit 14]", "Possible Mac Flag" if $dos_attrib & 0x4000 ;
# p7Zip & 7z set this bit to flag that the high 16-bits are Unix attributes
out1 "[Bit 15]", "Possible p7zip/7z Unix Flag" if $dos_attrib & 0x8000 ;
}
my $native_attrib = ($ext_file_attrib >> 16 ) & 0xFFFF;
if ($made_by == 3) # Unix
{
state $mask = {
0 => '---',
1 => '--x',
2 => '-w-',
3 => '-wx',
4 => 'r--',
5 => 'r-x',
6 => 'rw-',
7 => 'rwx',
} ;
my $rwx = ($native_attrib & 0777);
if ($rwx)
{
my $output = '';
$output .= $mask->{ ($rwx >> 6) & 07 } ;
$output .= $mask->{ ($rwx >> 3) & 07 } ;
$output .= $mask->{ ($rwx >> 0) & 07 } ;
out1 "[Bits 16-24]", Value_v($rwx) . " 'Unix attrib: $output'" ;
out1 "[Bit 25]", "1 'Sticky'"
if $rwx & 0x200 ;
out1 "[Bit 26]", "1 'Set GID'"
if $rwx & 0x400 ;
out1 "[Bit 27]", "1 'Set UID'"
if $rwx & 0x800 ;
my $not_rwx = (($native_attrib >> 12) & 0xF);
if ($not_rwx)
{
state $masks = {
0x0C => 'Socket', # 0x0C 0b1100
0x0A => 'Symbolic Link', # 0x0A 0b1010
0x08 => 'Regular File', # 0x08 0b1000
0x06 => 'Block Device', # 0x06 0b0110
0x04 => 'Directory', # 0x04 0b0100
0x02 => 'Character Device', # 0x02 0b0010
0x01 => 'FIFO', # 0x01 0b0001
};
my $got = $masks->{$not_rwx} // 'Unknown Unix attrib' ;
out1 "[Bits 28-31]", Value_C($not_rwx) . " '$got'"
}
}
}
elsif ($native_attrib)
{
out1 "[Bits 24-31]", Value_v($native_attrib) . " 'Unknown attributes for OS ID $made_by'"
}
my ($d, $locHeaderOffset) = read_V();
my $out = Value_V($locHeaderOffset);
my $std_localHeaderOffset = $locHeaderOffset;
if ($locHeaderOffset != MAX32)
{
testPossiblePrefix($locHeaderOffset, ZIP_LOCAL_HDR_SIG);
if ($PREFIX_DELTA)
{
$out .= " [Actual Offset is " . Value_V($locHeaderOffset + $PREFIX_DELTA) . "]"
}
}
out $d, "Local Header Offset", $out;
if ($locHeaderOffset != MAX32)
{
my $commonMessage = "'Local Header Offset' field in '" . Signatures::name($signature) . "' is invalid";
$locHeaderOffset = checkOffsetValue($locHeaderOffset, $startRecordOffset, 0, $commonMessage, $startRecordOffset + CentralDirectoryEntry::Offset_RelativeOffsetToLocal(), ZIP_LOCAL_HDR_SIG) ;
}
my $filename = '';
if ($filenameLength)
{
need $filenameLength, Signatures::name($signature), 'Filename';
myRead(my $raw_filename, $filenameLength);
$cdEntry->filename($raw_filename) ;
$filename = outputFilename($raw_filename, $LanguageEncodingFlag);
$cdEntry->outputFilename($filename);
}
$cdEntry->centralHeaderOffset($cdEntryOffset) ;
$cdEntry->localHeaderOffset($locHeaderOffset) ;
$cdEntry->compressedSize($compressedSize) ;
$cdEntry->uncompressedSize($uncompressedSize) ;
$cdEntry->zip64ExtraPresent(undef) ; #$cdZip64; ### FIX ME
$cdEntry->zip64SizesPresent(undef) ; # $zip64Sizes; ### FIX ME
$cdEntry->extractVersion($extractVer);
$cdEntry->generalPurposeFlags($gpFlag);
$cdEntry->compressedMethod($compressedMethod) ;
$cdEntry->lastModDateTime($lastMod);
$cdEntry->crc32($crc) ;
$cdEntry->inCentralDir(1) ;
$cdEntry->std_localHeaderOffset($std_localHeaderOffset) ;
$cdEntry->std_compressedSize($std_compressedSize) ;
$cdEntry->std_uncompressedSize($std_uncompressedSize) ;
$cdEntry->std_diskNumber($std_disk_start) ;
if ($extraLength)
{
need $extraLength, Signatures::name($signature), 'Extra';
walkExtra($extraLength, $cdEntry);
}
# $cdEntry->endCentralHeaderOffset($FH->tell() - 1);
# Can only validate for directory after zip64 data is read
validateDirectory($cdEntryOffset, $filename, $extractVer, $made_by,
$cdEntry->compressedSize, $cdEntry->uncompressedSize, $ext_file_attrib);
if ($comment_length)
{
need $comment_length, Signatures::name($signature), 'Comment';
my $comment ;
myRead($comment, $comment_length);
outputFilename $comment, $LanguageEncodingFlag, "Comment";
$cdEntry->comment($comment);
}
$cdEntry->offsetStart($cdEntryOffset) ;
$cdEntry->offsetEnd($FH->tell() - 1) ;
$CentralDirectory->addEntry($cdEntry);
return { 'encapsulated' => $cdEntry ? $cdEntry->encapsulated() : 0};
}
sub decodeZipVer
{
my $ver = shift ;
return ""
if ! defined $ver;
my $sHi = int($ver /10) ;
my $sLo = $ver % 10 ;
"$sHi.$sLo";
}
sub decodeOS
{
my $ver = shift ;
$OS_Lookup{$ver} || "Unknown" ;
}
sub Zip64EndCentralHeader
{
# Extra ID is 0x0001
# APPNOTE 6.3.10, section 4.3.14, 7.3.3, 7.3.4 & APPENDIX C
# TODO - APPNOTE allows an extensible data sector at end of this record (see APPNOTE 6.3.10, section 4.3.14.4)
# The code below does NOT take this into account.
my $signature = shift ;
my $data = shift ;
my $startRecordOffset = shift ;
print "\n";
out $data, "ZIP64 END CENTRAL DIR RECORD", Value_V($signature);
need 8, Signatures::name($signature);
my $size = out_Q "Size of record";
need $size, Signatures::name($signature);
out_C "Created Zip Spec", \&decodeZipVer;
out_C "Created OS", \&decodeOS;
my $extractSpec = out_C "Extract Zip Spec", \&decodeZipVer;
out_C "Extract OS", \&decodeOS;
my $diskNumber = out_V "Number of this disk";
my $cdDiskNumber = out_V "Central Dir Disk no";
my $entriesOnThisDisk = out_Q "Entries in this disk";
my $totalEntries = out_Q "Total Entries";
my $centralDirSize = out_Q "Size of Central Dir";
my ($d, $centralDirOffset) = read_Q();
my $out = Value_Q($centralDirOffset);
testPossiblePrefix($centralDirOffset, ZIP_CENTRAL_HDR_SIG);
$out .= " [Actual Offset is " . Value_Q($centralDirOffset + $PREFIX_DELTA) . "]"
if $PREFIX_DELTA ;
out $d, "Offset to Central dir", $out;
if (! emptyArchive($startRecordOffset, $diskNumber, $cdDiskNumber, $entriesOnThisDisk, $totalEntries, $centralDirSize, $centralDirOffset))
{
my $commonMessage = "'Offset to Central Directory' field in '" . Signatures::name($signature) . "' is invalid";
$centralDirOffset = checkOffsetValue($centralDirOffset, $startRecordOffset, $centralDirSize, $commonMessage, $startRecordOffset + 48, ZIP_CENTRAL_HDR_SIG, 0, $extractSpec < 0x3E) ;
}
# Length of 44 means typical version 1 header
return
if $size == 44 ;
my $remaining = $size - 44;
# pkzip sets the extract zip spec to 6.2 (0x3E) to signal a v2 record
# See APPNOTE 6.3.10, section, 7.3.3
if ($extractSpec >= 0x3E)
{
# Version 2 header (see APPNOTE 6.3.7, section 7.3.4, )
# Can use version 2 header to infer presence of encrypted CD
$CentralDirectory->setPkEncryptedCD();
# Compression Method 2 bytes Method used to compress the
# Central Directory
# Compressed Size 8 bytes Size of the compressed data
# Original Size 8 bytes Original uncompressed size
# AlgId 2 bytes Encryption algorithm ID
# BitLen 2 bytes Encryption key length
# Flags 2 bytes Encryption flags
# HashID 2 bytes Hash algorithm identifier
# Hash Length 2 bytes Length of hash data
# Hash Data (variable) Hash data
my ($bcm, $compressedMethod) = read_v();
out $bcm, "Compression Method", compressionMethod($compressedMethod) ;
info $FH->tell() - 2, "Unknown 'Compression Method' ID " . decimalHex0x($compressedMethod, 2)
if ! defined $ZIP_CompressionMethods{$compressedMethod} ;
out_Q "Compressed Size";
out_Q "Uncompressed Size";
out_v "AlgId", sub { $AlgIdLookup{ $_[0] } // "Unknown algorithm" } ;
out_v "BitLen";
out_v "Flags", sub { $FlagsLookup{ $_[0] } // "reserved for certificate processing" } ;
out_v "HashID", sub { $HashIDLookup{ $_[0] } // "Unknown ID" } ;
my $hashLen = out_v "Hash Length ";
outHexdump($hashLen, "Hash Data");
$remaining -= $hashLen + 28;
}
my $entry = Zip64EndCentralHeaderEntry->new();
if ($remaining)
{
# Handle 'zip64 extensible data sector' here
# See APPNOTE 6.3.10, section 4.3.14.3, 4.3.14.4 & APPENDIX C
# Not seen a real example of this. Tested with hand crafted files.
walkExtra($remaining, $entry);
}
return {};
}
sub Zip64EndCentralLocator
{
# APPNOTE 6.3.10, sec 4.3.15
my $signature = shift ;
my $data = shift ;
my $startRecordOffset = shift ;
print "\n";
out $data, "ZIP64 END CENTRAL DIR LOCATOR", Value_V($signature);
need 16, Signatures::name($signature);
# my ($nextRecord, $deltaActuallyAvailable) = $HeaderOffsetIndex->checkForOverlap(16);
# if ($deltaActuallyAvailable)
# {
# fatal_truncated_record(
# sprintf("ZIP64 END CENTRAL DIR LOCATOR \@%X truncated", $FH->tell() - 4),
# sprintf("Need 0x%X bytes, have 0x%X available", 16, $deltaActuallyAvailable),
# sprintf("Next Record is %s \@0x%X", $nextRecord->name(), $nextRecord->offset())
# )
# }
# TODO - check values for traces of multi-part + crazy offsets
out_V "Central Dir Disk no";
my ($d, $zip64EndCentralDirOffset) = read_Q();
my $out = Value_Q($zip64EndCentralDirOffset);
testPossiblePrefix($zip64EndCentralDirOffset, ZIP64_END_CENTRAL_REC_HDR_SIG);
$out .= " [Actual Offset is " . Value_Q($zip64EndCentralDirOffset + $PREFIX_DELTA) . "]"
if $PREFIX_DELTA ;
out $d, "Offset to Zip64 EOCD", $out;
my $totalDisks = out_V "Total no of Disks";
if ($totalDisks > 0)
{
my $commonMessage = "'Offset to Zip64 End of Central Directory Record' field in '" . Signatures::name($signature) . "' is invalid";
$zip64EndCentralDirOffset = checkOffsetValue($zip64EndCentralDirOffset, $startRecordOffset, 0, $commonMessage, $FH->tell() - 12, ZIP64_END_CENTRAL_REC_HDR_SIG) ;
}
return {};
}
sub needZip64EOCDLocator
{
# zip64 end of central directory field needed if any of the fields
# in the End Central Header record are maxed out
my $diskNumber = shift ;
my $cdDiskNumber = shift ;
my $entriesOnThisDisk = shift ;
my $totalEntries = shift ;
my $centralDirSize = shift ;
my $centralDirOffset = shift ;
return (full16($diskNumber) || # 4.4.19
full16($cdDiskNumber) || # 4.4.20
full16($entriesOnThisDisk) || # 4.4.21
full16($totalEntries) || # 4.4.22
full32($centralDirSize) || # 4.4.23
full32($centralDirOffset) # 4.4.24
) ;
}
sub emptyArchive
{
my $offset = shift;
my $diskNumber = shift ;
my $cdDiskNumber = shift ;
my $entriesOnThisDisk = shift ;
my $totalEntries = shift ;
my $centralDirSize = shift ;
my $centralDirOffset = shift ;
return (#$offset == 0 &&
$diskNumber == 0 &&
$cdDiskNumber == 0 &&
$entriesOnThisDisk == 0 &&
$totalEntries == 0 &&
$centralDirSize == 0 &&
$centralDirOffset== 0
) ;
}
sub EndCentralHeader
{
# APPNOTE 6.3.10, sec 4.3.16
my $signature = shift ;
my $data = shift ;
my $startRecordOffset = shift ;
print "\n";
out $data, "END CENTRAL HEADER", Value_V($signature);
need 18, Signatures::name($signature);
# TODO - check values for traces of multi-part + crazy values
my $diskNumber = out_v "Number of this disk";
my $cdDiskNumber = out_v "Central Dir Disk no";
my $entriesOnThisDisk = out_v "Entries in this disk";
my $totalEntries = out_v "Total Entries";
my $centralDirSize = out_V "Size of Central Dir";
my ($d, $centralDirOffset) = read_V();
my $out = Value_V($centralDirOffset);
testPossiblePrefix($centralDirOffset, ZIP_CENTRAL_HDR_SIG);
$out .= " [Actual Offset is " . Value_V($centralDirOffset + $PREFIX_DELTA) . "]"
if $PREFIX_DELTA && $centralDirOffset != MAX32 ;
out $d, "Offset to Central Dir", $out;
my $comment_length = out_v "Comment Length";
if ($comment_length)
{
my $here = $FH->tell() ;
my $available = $FILELEN - $here ;
if ($available < $comment_length)
{
error $here,
"file truncated while reading 'Comment' field in '" . Signatures::name($signature) . "'",
expectedMessage($comment_length, $available);
$comment_length = $available;
}
if ($comment_length)
{
my $comment ;
myRead($comment, $comment_length);
outputFilename $comment, 0, "Comment";
}
}
if ( ! Nesting::isNested($startRecordOffset, $FH->tell() -1))
{
# Not nested
if (! needZip64EOCDLocator($diskNumber, $cdDiskNumber, $entriesOnThisDisk, $totalEntries, $centralDirSize, $centralDirOffset) &&
! emptyArchive($startRecordOffset, $diskNumber, $cdDiskNumber, $entriesOnThisDisk, $totalEntries, $centralDirSize, $centralDirOffset))
{
my $commonMessage = "'Offset to Central Directory' field in '" . Signatures::name($signature) . "' is invalid";
$centralDirOffset = checkOffsetValue($centralDirOffset, $startRecordOffset, $centralDirSize, $commonMessage, $startRecordOffset + 16, ZIP_CENTRAL_HDR_SIG) ;
}
}
# else do nothing
return {};
}
sub DataDescriptor
{
# Data header record or Spanned archive marker.
#
# ZIP_DATA_HDR_SIG at start of file flags a spanned zip file.
# If it is a true marker, the next four bytes MUST be a ZIP_LOCAL_HDR_SIG
# See APPNOTE 6.3.10, sec 8.5.3, 8.5.4 & 8.5.5
# If not at start of file, assume a Data Header Record
# See APPNOTE 6.3.10, sec 4.3.9 & 4.3.9.3
my $signature = shift ;
my $data = shift ;
my $startRecordOffset = shift ;
my $here = $FH->tell();
if ($here == 4)
{
# Spanned Archive Marker
out $data, "SPLIT ARCHIVE MULTI-SEGMENT MARKER", Value_V($signature);
return;
# my (undef, $next_sig) = read_V();
# seekTo(0);
# if ($next_sig == ZIP_LOCAL_HDR_SIG)
# {
# print "\n";
# out $data, "SPLIT ARCHIVE MULTI-SEGMENT MARKER", Value_V($signature);
# seekTo($here);
# return;
# }
}
my $sigName = Signatures::titleName(ZIP_DATA_HDR_SIG);
print "\n";
out $data, $sigName, Value_V($signature);
need 24, Signatures::name($signature);
# Ignore header payload if nested (assume 64-bit descriptor)
if (Nesting::isNested( $here - 4, $here - 4 + 24 - 1))
{
out "", "Skipping Nested Payload";
return {};
}
my $compressedSize;
my $uncompressedSize;
my $localEntry = $LocalDirectory->lastStreamedEntryAdded();
my $centralEntry = $localEntry && $localEntry->getCdEntry ;
if (!$localEntry)
{
# found a Data Descriptor without a local header
out "", "Skipping Data Descriptor", "No matching Local header with streaming bit set";
error $here - 4, "Orphan '$sigName' found", "No matching Local header with streaming bit set";
return {};
}
my $crc = out_V "CRC";
my $payloadLength = $here - 4 - $localEntry->payloadOffset;
my $deltaToNext = deltaToNextSignature();
my $cl32 = unpack "V", peekAtOffset($here + 4, 4);
my $cl64 = unpack "Q<", peekAtOffset($here + 4, 8);
# use delta to next header & payload length
# deals with use case where the payload length < 32 bit
# will use a 32-bit value rather than the 64-bit value
# see if delta & payload size match
if ($deltaToNext == 16 && $cl64 == $payloadLength)
{
if (! $localEntry->zip64 && ($centralEntry && ! $centralEntry->zip64))
{
error $here, "'$sigName': expected 32-bit values, got 64-bit";
}
$compressedSize = out_Q "Compressed Size" ;
$uncompressedSize = out_Q "Uncompressed Size" ;
}
elsif ($deltaToNext == 8 && $cl32 == $payloadLength)
{
if ($localEntry->zip64)
{
error $here, "'$sigName': expected 64-bit values, got 32-bit";
}
$compressedSize = out_V "Compressed Size" ;
$uncompressedSize = out_V "Uncompressed Size" ;
}
# Try matching juast payload lengths
elsif ($cl32 == $payloadLength)
{
if ($localEntry->zip64)
{
error $here, "'$sigName': expected 64-bit values, got 32-bit";
}
$compressedSize = out_V "Compressed Size" ;
$uncompressedSize = out_V "Uncompressed Size" ;
warning $here, "'$sigName': Zip Header not directly after Data Descriptor";
}
elsif ($cl64 == $payloadLength)
{
if (! $localEntry->zip64 && ($centralEntry && ! $centralEntry->zip64))
{
error $here, "'$sigName': expected 32-bit values, got 64-bit";
}
$compressedSize = out_Q "Compressed Size" ;
$uncompressedSize = out_Q "Uncompressed Size" ;
warning $here, "'$sigName': Zip Header not directly after Data Descriptor";
}
# payloads don't match, so try delta
elsif ($deltaToNext == 16)
{
if (! $localEntry->zip64 && ($centralEntry && ! $centralEntry->zip64))
{
error $here, "'$sigName': expected 32-bit values, got 64-bit";
}
$compressedSize = out_Q "Compressed Size" ;
# compressed size is wrong
error $here, "'$sigName': Compressed size" . decimalHex0x($compressedSize) . " doesn't match with payload size " . decimalHex0x($payloadLength);
$uncompressedSize = out_Q "Uncompressed Size" ;
}
elsif ($deltaToNext == 8 )
{
if ($localEntry->zip64)
{
error $here, "'$sigName': expected 64-bit values, got 32-bit";
}
$compressedSize = out_V "Compressed Size" ;
# compressed size is wrong
error $here, "'$sigName': Compressed Size " . decimalHex0x($compressedSize) . " doesn't match with payload size " . decimalHex0x($payloadLength);
$uncompressedSize = out_V "Uncompressed Size" ;
}
# no payoad or delta match at all, so likely a false positive or data corruption
else
{
warning $here, "Cannot determine size of Data Descriptor record";
}
# TODO - neither payload size or delta to next signature match
if ($localEntry)
{
$localEntry->readDataDescriptor(1) ;
$localEntry->crc32($crc) ;
$localEntry->compressedSize($compressedSize) ;
$localEntry->uncompressedSize($uncompressedSize) ;
}
# APPNOTE 6.3.10, sec 4.3.8
my $filename = $localEntry->filename;
warning undef, "Directory '$filename' must not have a payload"
if $filename =~ m#/$# && $uncompressedSize ;
return {
crc => $crc,
compressedSize => $compressedSize,
uncompressedSize => $uncompressedSize,
};
}
sub SingleSegmentMarker
{
# ZIP_SINGLE_SEGMENT_MARKER at start of file flags a spanned zip file.
# If this ia a true marker, the next four bytes MUST be a ZIP_LOCAL_HDR_SIG
# See APPNOTE 6.3.10, sec 8.5.3, 8.5.4 & 8.5.5
my $signature = shift ;
my $data = shift ;
my $startRecordOffset = shift ;
my $here = $FH->tell();
if ($here == 4)
{
my (undef, $next_sig) = read_V();
if ($next_sig == ZIP_LOCAL_HDR_SIG)
{
print "\n";
out $data, "SPLIT ARCHIVE SINGLE-SEGMENT MARKER", Value_V($signature);
}
seekTo($here);
}
return {};
}
sub ArchiveExtraDataRecord
{
# TODO - not seen an example of this record
# APPNOTE 6.3.10, sec 4.3.11
my $signature = shift ;
my $data = shift ;
my $startRecordOffset = shift ;
out $data, "ARCHIVE EXTRA DATA RECORD", Value_V($signature);
need 2, Signatures::name($signature);
my $size = out_v "Size of record";
need $size, Signatures::name($signature);
outHexdump($size, "Field data", 1);
return {};
}
sub DigitalSignature
{
my $signature = shift ;
my $data = shift ;
my $startRecordOffset = shift ;
print "\n";
out $data, "DIGITAL SIGNATURE RECORD", Value_V($signature);
need 2, Signatures::name($signature);
my $Size = out_v "Size of record";
need $Size, Signatures::name($signature);
myRead(my $payload, $Size);
out $payload, "Signature", hexDump16($payload);
return {};
}
sub GeneralPurposeBits
{
my $method = shift;
my $gp = shift;
out1 "[Bit 0]", "1 'Encryption'" if $gp & ZIP_GP_FLAG_ENCRYPTED_MASK;
my %lookup = (
0 => "Normal Compression",
1 => "Maximum Compression",
2 => "Fast Compression",
3 => "Super Fast Compression");
if ($method == ZIP_CM_DEFLATE)
{
my $mid = ($gp >> 1) & 0x03 ;
out1 "[Bits 1-2]", "$mid '$lookup{$mid}'";
}
if ($method == ZIP_CM_LZMA)
{
if ($gp & ZIP_GP_FLAG_LZMA_EOS_PRESENT) {
out1 "[Bit 1]", "1 'LZMA EOS Marker Present'" ;
}
else {
out1 "[Bit 1]", "0 'LZMA EOS Marker Not Present'" ;
}
}
if ($method == ZIP_CM_IMPLODE) # Imploding
{
out1 "[Bit 1]", ($gp & (1 << 1) ? "1 '8k" : "0 '4k") . " Sliding Dictionary'" ;
out1 "[Bit 2]", ($gp & (2 << 1) ? "1 '3" : "0 '2" ) . " Shannon-Fano Trees'" ;
}
out1 "[Bit 3]", "1 'Streamed'" if $gp & ZIP_GP_FLAG_STREAMING_MASK;
out1 "[Bit 4]", "1 'Enhanced Deflating'" if $gp & 1 << 4;
out1 "[Bit 5]", "1 'Compressed Patched'" if $gp & ZIP_GP_FLAG_PATCHED_MASK ;
out1 "[Bit 6]", "1 'Strong Encryption'" if $gp & ZIP_GP_FLAG_STRONG_ENCRYPTED_MASK;
out1 "[Bit 11]", "1 'Language Encoding'" if $gp & ZIP_GP_FLAG_LANGUAGE_ENCODING;
out1 "[Bit 12]", "1 'Pkware Enhanced Compression'" if $gp & ZIP_GP_FLAG_PKWARE_ENHANCED_COMP ;
out1 "[Bit 13]", "1 'Encrypted Central Dir'" if $gp & ZIP_GP_FLAG_ENCRYPTED_CD ;
return ();
}
sub seekSet
{
my $fh = $_[0] ;
my $size = $_[1];
use Fcntl qw(SEEK_SET);
seek($fh, $size, SEEK_SET);
}
sub skip
{
my $fh = $_[0] ;
my $size = $_[1];
use Fcntl qw(SEEK_CUR);
seek($fh, $size, SEEK_CUR);
}
sub myRead
{
my $got = \$_[0] ;
my $size = $_[1];
my $wantSize = $size;
$$got = '';
if ($size == 0)
{
return ;
}
if ($size > 0)
{
my $buff ;
my $status = $FH->read($buff, $size);
return $status
if $status < 0;
$$got .= $buff ;
}
my $len = length $$got;
# fatal undef, "Truncated file (got $len, wanted $wantSize): $!"
fatal undef, "Unexpected zip file truncation",
expectedMessage($wantSize, $len)
if length $$got != $wantSize;
}
sub expectedMessage
{
my $expected = shift;
my $got = shift;
return "Expected " . decimalHex0x($expected) . " bytes, but only " . decimalHex0x($got) . " available"
}
sub need
{
my $byteCount = shift ;
my $message = shift ;
my $field = shift // '';
# return $FILELEN - $FH->tell() >= $byteCount;
my $here = $FH->tell() ;
my $available = $FILELEN - $here ;
if ($available < $byteCount)
{
my @message ;
if ($field)
{
push @message, "Unexpected zip file truncation while reading '$field' field in '$message'";
}
else
{
push @message, "Unexpected zip file truncation while reading '$message'";
}
push @message, expectedMessage($byteCount, $available);
# push @message, sprintf("Expected 0x%X bytes, but only 0x%X available", $byteCount, $available);
push @message, "Try running with --walk' or '--scan' options"
if ! $opt_scan && ! $opt_walk ;
fatal $here, @message;
}
}
sub testPossiblePrefix
{
my $offset = shift;
my $expectedSignature = shift ;
if (testPossiblePrefixNoPREFIX_DELTA($offset, $expectedSignature))
{
$PREFIX_DELTA = $POSSIBLE_PREFIX_DELTA;
$POSSIBLE_PREFIX_DELTA = 0;
reportPrefixData();
return 1
}
return 0
}
sub testPossiblePrefixNoPREFIX_DELTA
{
my $offset = shift;
my $expectedSignature = shift ;
return 0
if $offset + 4 > $FILELEN || ! $POSSIBLE_PREFIX_DELTA || $PREFIX_DELTA;
my $currentOFFSET = $OFFSET;
my $gotSig = readSignatureFromOffset($offset);
if ($gotSig == $expectedSignature)
{
# do have possible prefix data, but the offset is correct
$POSSIBLE_PREFIX_DELTA = $PREFIX_DELTA = 0;
$OFFSET = $currentOFFSET;
return 0;
}
$gotSig = readSignatureFromOffset($offset + $POSSIBLE_PREFIX_DELTA);
$OFFSET = $currentOFFSET;
return ($gotSig == $expectedSignature) ;
}
sub offsetIsValid
{
my $offset = shift;
my $headerStart = shift;
my $centralDirSize = shift;
my $commonMessage = shift ;
my $expectedSignature = shift ;
my $dereferencePointer = shift;
my $must_point_back = 1;
my $delta = $offset - $FILELEN + 1 ;
$offset += $PREFIX_DELTA
if $PREFIX_DELTA ;
return sprintf("value %s is %s bytes past EOF", decimalHex0x($offset), decimalHex0x($delta))
if $delta > 0 ;
return sprintf "value %s must be less that %s", decimalHex0x($offset), decimalHex0x($headerStart)
if $must_point_back && $offset >= $headerStart;
if ($dereferencePointer)
{
my $actual = $headerStart - $centralDirSize;
my $cdSizeOK = ($actual == $offset);
my $possibleDelta = $actual - $offset;
if ($centralDirSize && ! $cdSizeOK && $possibleDelta > 0 && readSignatureFromOffset($possibleDelta) == ZIP_LOCAL_HDR_SIG)
{
# If testing end of central dir, check if the location of the first CD header
# is consistent with the central dir size.
# Common use case is a SFX zip file
my $gotSig = readSignatureFromOffset($actual);
my $v = hexValue32($gotSig);
return 'value @ ' . hexValue($actual) . " should decode to signature for " . Signatures::nameAndHex($expectedSignature) . ". Got $v" # . hexValue32($gotSig)
if $gotSig != $expectedSignature ;
$PREFIX_DELTA = $possibleDelta;
reportPrefixData();
return undef;
}
else
{
my $gotSig = readSignatureFromOffset($offset);
my $v = hexValue32($gotSig);
return 'value @ ' . hexValue($offset) . " should decode to signature for " . Signatures::nameAndHex($expectedSignature) . ". Got $v" # . hexValue32($gotSig)
if $gotSig != $expectedSignature ;
}
}
return undef ;
}
sub checkOffsetValue
{
my $offset = shift;
my $headerStart = shift;
my $centralDirSize = shift;
my $commonMessage = shift ;
my $messageOffset = shift;
my $expectedSignature = shift ;
my $fatal = shift // 0;
my $dereferencePointer = shift // 1;
my $keepOFFSET = $OFFSET ;
my $message = offsetIsValid($offset, $headerStart, $centralDirSize, $commonMessage, $expectedSignature, $dereferencePointer);
if ($message)
{
fatal_tryWalk($messageOffset, $commonMessage, $message)
if $fatal;
error $messageOffset, $commonMessage, $message
if ! $fatal;
}
$OFFSET = $keepOFFSET;
return $offset + $PREFIX_DELTA;
}
sub fatal_tryWalk
{
my $offset = shift ;
my $message = shift;
fatal($offset, $message, @_, "Try running with --walk' or '--scan' options");
}
sub fatal
{
my $offset = shift ;
my $message = shift;
return if $fatalDisabled;
if (defined $offset)
{
warn "#\n# FATAL: Offset " . hexValue($offset) . ": $message\n";
}
else
{
warn "#\n# FATAL: $message\n";
}
warn "# $_ . \n"
for @_;
warn "#\n" ;
exit 1;
}
sub disableFatal
{
$fatalDisabled = 1 ;
}
sub enableFatal
{
$fatalDisabled = 0 ;
}
sub topLevelFatal
{
my $message = shift ;
no warnings 'utf8';
warn "FATAL: $message\n";
warn "$_ . \n"
for @_;
exit 1;
}
sub internalFatal
{
my $offset = shift ;
my $message = shift;
no warnings 'utf8';
if (defined $offset)
{
warn "# FATAL: Offset " . hexValue($offset) . ": Internal Error: $message\n";
}
else
{
warn "# FATAL: Internal Error: $message\n";
}
warn "# $_ \n"
for @_;
warn "# Please report error at https://github.com/pmqs/zipdetails/issues\n";
exit 1;
}
sub warning
{
my $offset = shift ;
my $message = shift;
no warnings 'utf8';
return
unless $opt_want_warning_mesages ;
say "#"
unless $lastWasMessage ++ ;
if (defined $offset)
{
say "# WARNING: Offset " . hexValue($offset) . ": $message";
}
else
{
say "# WARNING: $message";
}
say "# $_" for @_ ;
say "#";
++ $WarningCount ;
$exit_status_code |= 2
if $opt_want_message_exit_status ;
}
sub error
{
my $offset = shift ;
my $message = shift;
no warnings 'utf8';
return
unless $opt_want_error_mesages ;
say "#"
unless $lastWasMessage ++ ;
if (defined $offset)
{
say "# ERROR: Offset " . hexValue($offset) . ": $message";
}
else
{
say "# ERROR: $message";
}
say "# $_" for @_ ;
say "#";
++ $ErrorCount ;
$exit_status_code |= 4
if $opt_want_message_exit_status ;
}
sub debug
{
my $offset = shift ;
my $message = shift;
no warnings 'utf8';
say "#"
unless $lastWasMessage ++ ;
if (defined $offset)
{
say "# DEBUG: Offset " . hexValue($offset) . ": $message";
}
else
{
say "# DEBUG: $message";
}
say "# $_" for @_ ;
say "#";
}
sub internalError
{
my $message = shift;
no warnings 'utf8';
say "#";
say "# ERROR: $message";
say "# $_" for @_ ;
say "# Please report error at https://github.com/pmqs/zipdetails/issues";
say "#";
++ $ErrorCount ;
}
sub reportPrefixData
{
my $delta = shift // $PREFIX_DELTA ;
state $reported = 0;
return if $reported || $delta == 0;
info 0, "found " . decimalHex0x($delta) . " bytes before beginning of zipfile" ;
$reported = 1;
}
sub info
{
my $offset = shift;
my $message = shift;
no warnings 'utf8';
return
unless $opt_want_info_mesages ;
say "#"
unless $lastWasMessage ++ ;
if (defined $offset)
{
say "# INFO: Offset " . hexValue($offset) . ": $message";
}
else
{
say "# INFO: $message";
}
say "# $_" for @_ ;
say "#";
++ $InfoCount ;
$exit_status_code |= 1
if $opt_want_message_exit_status ;
}
sub walkExtra
{
# APPNOTE 6.3.10, sec 4.4.11, 4.4.28, 4.5
my $XLEN = shift;
my $entry = shift;
# Caller has determined that there are $XLEN bytes available to read
my $buff ;
my $offset = 0 ;
my $id;
my $subLen;
my $payload ;
my $count = 0 ;
my $endExtraOffset = $FH->tell() + $XLEN ;
while ($offset < $XLEN) {
++ $count;
# Detect if there is not enough data for an extra ID and length.
# Android zipalign and zipflinger are prime candidates for these
# non-standard extra sub-fields.
my $remaining = $XLEN - $offset;
if ($remaining < ZIP_EXTRA_SUBFIELD_HEADER_SIZE) {
# There is not enough left.
# Consume whatever is there and return so parsing
# can continue.
myRead($payload, $remaining);
my $data = hexDump($payload);
if ($payload =~ /^\x00+$/)
{
# All nulls
out $payload, "Null Padding in Extra";
info $FH->tell() - length($payload), decimalHex0x(length $payload) . " Null Padding Bytes in Extra Field" ;
}
else
{
out $payload, "Extra Data", $data;
error $FH->tell() - length($payload), "'Extra Data' Malformed";
}
return undef;
}
myRead($id, ZIP_EXTRA_SUBFIELD_ID_SIZE);
$offset += ZIP_EXTRA_SUBFIELD_ID_SIZE;
my $lookID = unpack "v", $id ;
if ($lookID == 0)
{
# check for null padding at end of extra
my $here = $FH->tell();
my $rest;
myRead($rest, $XLEN - $offset);
if ($rest =~ /^\x00+$/)
{
my $len = length ($id . $rest) ;
out $id . $rest, "Null Padding in Extra";
info $FH->tell() - $len, decimalHex0x($len) . " Null Padding Bytes in Extra Field";
return undef;
}
seekTo($here);
}
my ($who, $decoder, $local_min, $local_max, $central_min, $central_max) = @{ $Extras{$lookID} // ['', undef, undef, undef, undef, undef ] };
my $idString = Value_v($lookID) ;
$idString .= " '$who'"
if $who;
out $id, "Extra ID #$count", $idString ;
info $FH->tell() - 2, "Unknown Extra ID $idString"
if ! exists $Extras{$lookID} ;
myRead($buff, ZIP_EXTRA_SUBFIELD_LEN_SIZE);
$offset += ZIP_EXTRA_SUBFIELD_LEN_SIZE;
$subLen = unpack("v", $buff);
out2 $buff, "Length", Value_v($subLen) ;
$remaining = $XLEN - $offset;
if ($subLen > $remaining )
{
error $FH->tell() -2,
extraFieldIdentifier($lookID) . ": 'Length' field invalid",
sprintf("value %s > %s bytes remaining", decimalHex0x($subLen), decimalHex0x($remaining));
outSomeData $remaining, " Extra Payload";
return undef;
}
if (! defined $decoder)
{
if ($subLen)
{
myRead($payload, $subLen);
my $data = hexDump16($payload);
out2 $payload, "Extra Payload", $data;
}
}
else
{
if (testExtraLimits($lookID, $subLen, $entry->inCentralDir))
{
my $endExtraOffset = $FH->tell() + $subLen;
$decoder->($lookID, $subLen, $entry) ;
# Belt & Braces - should now be at $endExtraOffset
# error here means issue in an extra handler
# should noy happen, but just in case
# TODO -- need tests for this
my $here = $FH->tell() ;
if ($here > $endExtraOffset)
{
# gone too far, so need to bomb out now
internalFatal $here, "Overflow processing " . extraFieldIdentifier($lookID) . ".",
sprintf("Should be at offset %s, actually at %s", decimalHex0x($endExtraOffset), decimalHex0x($here));
}
elsif ($here < $endExtraOffset)
{
# not gone far enough, can recover
error $here,
sprintf("Expected to be at offset %s after processing %s, actually at %s", decimalHex0x($endExtraOffset), extraFieldIdentifier($lookID), decimalHex0x($here)),
"Skipping " . decimalHex0x($endExtraOffset - $here) . " bytes";
outSomeData $endExtraOffset - $here, " Extra Data";
}
}
}
$offset += $subLen ;
}
return undef ;
}
sub testExtraLimits
{
my $lookID = shift;
my $size = shift;
my $inCentralDir = shift;
my ($who, undef, $local_min, $local_max, $central_min, $central_max) = @{ $Extras{$lookID} // ['', undef, undef, undef, undef, undef ] };
my ($min, $max) = $inCentralDir
? ($central_min, $central_max)
: ($local_min, $local_max) ;
return 1
if ! defined $min && ! defined $max ;
if (defined $min && defined $max)
{
# both the same
if ($min == $max)
{
if ($size != $min)
{
error $FH->tell() -2, sprintf "%s: 'Length' field invalid: expected %s, got %s", extraFieldIdentifier($lookID), decimalHex0x($min), decimalHex0x($size);
outSomeData $size, " Extra Payload" if $size;
return 0;
}
}
else # min != max
{
if ($size < $min || $size > $max)
{
error $FH->tell() -2, sprintf "%s: 'Length' field invalid: value must be betweem %s and %s, got %s", extraFieldIdentifier($lookID), decimalHex0x($min), decimalHex0x($max), decimalHex0x($size);
outSomeData $size, " Extra Payload" if $size ;
return 0;
}
}
}
else # must be defined $min & undefined max
{
if ($size < $min)
{
error $FH->tell() -2, sprintf "%s: 'Length' field invalid: value must be at least %s, got %s", extraFieldIdentifier($lookID), decimalHex0x($min), decimalHex0x($size);
outSomeData $size, " Extra Payload" if $size;
return 0;
}
}
return 1;
}
sub full32
{
return ($_[0] // 0) == MAX32 ;
}
sub full16
{
return ($_[0] // 0) == MAX16 ;
}
sub decode_Zip64
{
my $extraID = shift ;
my $len = shift;
my $entry = shift;
myRead(my $payload, $len);
if ($entry->inCentralDir() )
{
walk_Zip64_in_CD($extraID, $payload, $entry, 1) ;
}
else
{
walk_Zip64_in_LD($extraID, $payload, $entry, 1) ;
}
}
sub walk_Zip64_in_LD
{
my $extraID = shift ;
my $zip64Extended = shift;
my $entry = shift;
my $display = shift // 1 ;
my $fieldStart = $FH->tell() - length $zip64Extended;
my $fieldOffset = $fieldStart ;
$ZIP64 = 1;
$entry->zip64(1);
if (length $zip64Extended == 0)
{
info $fieldOffset, extraFieldIdentifier($extraID) . ": Length is Zero";
return;
}
my $assumeLengthsPresent = (length($zip64Extended) == 16) ;
my $assumeAllFieldsPresent = (length($zip64Extended) == 28) ;
if ($assumeLengthsPresent || $assumeAllFieldsPresent || full32 $entry->std_uncompressedSize )
{
# TODO defer a warning if in local header & central/local don't have std_uncompressedSizeset to 0xffffffff
if (length $zip64Extended < 8)
{
my $message = extraFieldIdentifier($extraID) . ": Expected " . decimalHex0x(8) . " bytes for 'Uncompressed Size': only " . decimalHex0x(length $zip64Extended) . " bytes present";
error $fieldOffset, $message;
out2 $zip64Extended, $message;
return;
}
$fieldOffset += 8;
my $data = substr($zip64Extended, 0, 8, "") ;
$entry->uncompressedSize(unpack "Q<", $data);
out2 $data, "Uncompressed Size", Value_Q($entry->uncompressedSize)
if $display;
}
if ($assumeLengthsPresent || $assumeAllFieldsPresent || full32 $entry->std_compressedSize)
{
if (length $zip64Extended < 8)
{
my $message = extraFieldIdentifier($extraID) . ": Expected " . decimalHex0x(8) . " bytes for 'Compressed Size': only " . decimalHex0x(length $zip64Extended) . " bytes present";
error $fieldOffset, $message;
out2 $zip64Extended, $message;
return;
}
$fieldOffset += 8;
my $data = substr($zip64Extended, 0, 8, "") ;
$entry->compressedSize( unpack "Q<", $data);
out2 $data, "Compressed Size", Value_Q($entry->compressedSize)
if $display;
}
# Zip64 in local header should not have localHeaderOffset or disk number
# but some zip files do
if ($assumeAllFieldsPresent)
{
$fieldOffset += 8;
my $data = substr($zip64Extended, 0, 8, "") ;
my $localHeaderOffset = unpack "Q<", $data;
out2 $data, "Offset to Local Dir", Value_Q($localHeaderOffset)
if $display;
}
if ($assumeAllFieldsPresent)
{
$fieldOffset += 4;
my $data = substr($zip64Extended, 0, 4, "") ;
my $diskNumber = unpack "v", $data;
out2 $data, "Disk Number", Value_V($diskNumber)
if $display;
}
if (length $zip64Extended)
{
if ($display)
{
out2 $zip64Extended, "Unexpected Data", hexDump16 $zip64Extended ;
info $fieldOffset, extraFieldIdentifier($extraID) . ": Unexpected Data: " . decimalHex0x(length $zip64Extended) . " bytes";
}
}
}
sub walk_Zip64_in_CD
{
my $extraID = shift ;
my $zip64Extended = shift;
my $entry = shift;
my $display = shift // 1 ;
my $fieldStart = $FH->tell() - length $zip64Extended;
my $fieldOffset = $fieldStart ;
$ZIP64 = 1;
$entry->zip64(1);
if (length $zip64Extended == 0)
{
info $fieldOffset, extraFieldIdentifier($extraID) . ": Length is Zero";
return;
}
my $assumeAllFieldsPresent = (length($zip64Extended) == 28) ;
if ($assumeAllFieldsPresent || full32 $entry->std_uncompressedSize )
{
if (length $zip64Extended < 8)
{
my $message = extraFieldIdentifier($extraID) . ": Expected " . decimalHex0x(8) . " bytes for 'Uncompressed Size': only " . decimalHex0x(length $zip64Extended) . " bytes present";
error $fieldOffset, $message;
out2 $zip64Extended, $message;
return;
}
$fieldOffset += 8;
my $data = substr($zip64Extended, 0, 8, "") ;
$entry->uncompressedSize(unpack "Q<", $data);
out2 $data, "Uncompressed Size", Value_Q($entry->uncompressedSize)
if $display;
}
if ($assumeAllFieldsPresent || full32 $entry->std_compressedSize)
{
if (length $zip64Extended < 8)
{
my $message = extraFieldIdentifier($extraID) . ": Expected " . decimalHex0x(8) . " bytes for 'Compressed Size': only " . decimalHex0x(length $zip64Extended) . " bytes present";
error $fieldOffset, $message;
out2 $zip64Extended, $message;
return;
}
$fieldOffset += 8;
my $data = substr($zip64Extended, 0, 8, "") ;
$entry->compressedSize(unpack "Q<", $data);
out2 $data, "Compressed Size", Value_Q($entry->compressedSize)
if $display;
}
if ($assumeAllFieldsPresent || full32 $entry->std_localHeaderOffset)
{
if (length $zip64Extended < 8)
{
my $message = extraFieldIdentifier($extraID) . ": Expected " . decimalHex0x(8) . " bytes for 'Offset to Local Dir': only " . decimalHex0x(length $zip64Extended) . " bytes present";
error $fieldOffset, $message;
out2 $zip64Extended, $message;
return;
}
$fieldOffset += 8;
my $here = $FH->tell();
my $data = substr($zip64Extended, 0, 8, "") ;
$entry->localHeaderOffset(unpack "Q<", $data);
out2 $data, "Offset to Local Dir", Value_Q($entry->localHeaderOffset)
if $display;
my $commonMessage = "'Offset to Local Dir' field in 'Zip64 Extra Field' is invalid";
$entry->localHeaderOffset(checkOffsetValue($entry->localHeaderOffset, $fieldStart, 0, $commonMessage, $fieldStart, ZIP_LOCAL_HDR_SIG, 0) );
}
if ($assumeAllFieldsPresent || full16 $entry->std_diskNumber)
{
if (length $zip64Extended < 4)
{
my $message = extraFieldIdentifier($extraID) . ": Expected " . decimalHex0x(4) . " bytes for 'Disk Number': only " . decimalHex0x(length $zip64Extended) . " bytes present";
error $fieldOffset, $message;
out2 $zip64Extended, $message;
return;
}
$fieldOffset += 4;
my $here = $FH->tell();
my $data = substr($zip64Extended, 0, 4, "") ;
$entry->diskNumber(unpack "v", $data);
out2 $data, "Disk Number", Value_V($entry->diskNumber)
if $display;
$entry->zip64_diskNumberPresent(1);
}
if (length $zip64Extended)
{
if ($display)
{
out2 $zip64Extended, "Unexpected Data", hexDump16 $zip64Extended ;
info $fieldOffset, extraFieldIdentifier($extraID) . ": Unexpected Data: " . decimalHex0x(length $zip64Extended) . " bytes";
}
}
}
sub Ntfs2Unix
{
my $m = shift;
my $v = shift;
# NTFS offset is 19DB1DED53E8000
my $hex = Value_Q($v) ;
# Treat empty value as special case
# Could decode to 1 Jan 1601
return "$hex 'No Date/Time'"
if $v == 0;
$v -= 0x19DB1DED53E8000 ;
my $ns = ($v % 10000000) * 100;
my $elapse = int ($v/10000000);
return "$hex '" . getT($elapse) .
" " . sprintf("%0dns'", $ns);
}
sub decode_NTFS_Filetimes
{
my $extraID = shift ;
my $len = shift;
my $entry = shift;
out_V " Reserved";
out_v " Tag1";
out_v " Size1" ;
my ($m, $s1) = read_Q;
out $m, " Mtime", Ntfs2Unix($m, $s1);
my ($a, $s3) = read_Q;
out $a, " Atime", Ntfs2Unix($a, $s3);
my ($c, $s2) = read_Q;
out $c, " Ctime", Ntfs2Unix($c, $s2);
}
sub OpenVMS_DateTime
{
my $ix = shift;
my $tag = shift;
my $size = shift;
# VMS epoch is 17 Nov 1858
# Offset to Unix Epoch is -0x7C95674C3DA5C0 (-35067168005400000)
my ($data, $value) = read_Q();
my $datetime = "No Date Time'";
if ($value != 0)
{
my $v = $value - 0x007C95674C3DA5C0 ;
my $ns = ($v % 10000000) * 100 ;
my $seconds = int($v / 10000000) ;
$datetime = getT($seconds) .
" " . sprintf("%0dns'", $ns);
}
out2 $data, " Attribute", Value_Q($value) . " '$datetime";
}
sub OpenVMS_DumpBytes
{
my $ix = shift;
my $tag = shift;
my $size = shift;
myRead(my $data, $size);
out($data, " Attribute", hexDump16($data));
}
sub OpenVMS_4ByteValue
{
my $ix = shift;
my $tag = shift;
my $size = shift;
my ($data, $value) = read_V();
out2 $data, " Attribute", Value_V($value);
}
sub OpenVMS_UCHAR
{
my $ix = shift;
my $tag = shift;
my $size = shift;
state $FCH = {
0 => 'FCH$M_WASCONTIG',
1 => 'FCH$M_NOBACKUP',
2 => 'FCH$M_WRITEBACK',
3 => 'FCH$M_READCHECK',
4 => 'FCH$M_WRITCHECK',
5 => 'FCH$M_CONTIGB',
6 => 'FCH$M_LOCKED',
6 => 'FCH$M_CONTIG',
11 => 'FCH$M_BADACL',
12 => 'FCH$M_SPOOL',
13 => 'FCH$M_DIRECTORY',
14 => 'FCH$M_BADBLOCK',
15 => 'FCH$M_MARKDEL',
16 => 'FCH$M_NOCHARGE',
17 => 'FCH$M_ERASE',
18 => 'FCH$M_SHELVED',
20 => 'FCH$M_SCRATCH',
21 => 'FCH$M_NOMOVE',
22 => 'FCH$M_NOSHELVABLE',
} ;
my ($data, $value) = read_V();
out2 $data, " Attribute", Value_V($value);
for my $bit ( sort { $a <=> $b } keys %{ $FCH } )
{
# print "$bit\n";
if ($value & (1 << $bit) )
{
out1 " [Bit $bit]", $FCH->{$bit} ;
}
}
}
sub OpenVMS_2ByteValue
{
my $ix = shift;
my $tag = shift;
my $size = shift;
my ($data, $value) = read_v();
out2 $data, " Attribute", Value_v($value);
}
sub OpenVMS_revision
{
my $ix = shift;
my $tag = shift;
my $size = shift;
my ($data, $value) = read_v();
out2 $data, " Attribute", Value_v($value) . "'Revision Count " . Value_v($value) . "'";
}
sub decode_OpenVMS
{
my $extraID = shift ;
my $len = shift;
my $entry = shift;
state $openVMS_tags = {
0x04 => [ 'ATR$C_RECATTR', \&OpenVMS_DumpBytes ],
0x03 => [ 'ATR$C_UCHAR', \&OpenVMS_UCHAR ],
0x11 => [ 'ATR$C_CREDATE', \&OpenVMS_DateTime ],
0x12 => [ 'ATR$C_REVDATE', \&OpenVMS_DateTime ],
0x13 => [ 'ATR$C_EXPDATE', \&OpenVMS_DateTime ],
0x14 => [ 'ATR$C_BAKDATE', \&OpenVMS_DateTime ],
0x0D => [ 'ATR$C_ASCDATES', \&OpenVMS_revision ],
0x15 => [ 'ATR$C_UIC', \&OpenVMS_4ByteValue ],
0x16 => [ 'ATR$C_FPRO', \&OpenVMS_DumpBytes ],
0x17 => [ 'ATR$C_RPRO', \&OpenVMS_2ByteValue ],
0x1D => [ 'ATR$C_JOURNAL', \&OpenVMS_DumpBytes ],
0x1F => [ 'ATR$C_ADDACLENT', \&OpenVMS_DumpBytes ],
} ;
out_V " CRC";
$len -= 4;
my $ix = 1;
while ($len)
{
my ($data, $tag) = read_v();
my $tagname = 'Unknown Tag';
my $decoder = undef;
if ($openVMS_tags->{$tag})
{
($tagname, $decoder) = @{ $openVMS_tags->{$tag} } ;
}
out2 $data, "Tag #$ix", Value_v($tag) . " '" . $tagname . "'" ;
my $size = out_v " Size";
if (defined $decoder)
{
$decoder->($ix, $tag, $size) ;
}
else
{
outSomeData($size, " Attribute");
}
++ $ix;
$len -= $size + 2 + 2;
}
}
sub getT
{
my $time = shift ;
if ($opt_utc)
{ return scalar gmtime($time) // 'Unknown'}
else
{ return scalar localtime($time) // 'Unknown' }
}
sub getTime
{
my $time = shift ;
return "'Invalid Date or Time'"
if ! defined $time;
return "'" . getT($time) . "'";
}
sub LastModTime
{
my $value = shift ;
return "'No Date/Time'"
if $value == 0;
return getTime(_dosToUnixTime($value))
}
sub _dosToUnixTime
{
my $dt = shift;
# Mozilla xpi files have empty datetime
# This is not a valid Dos datetime value
return 0 if $dt == 0 ;
my $year = ( ( $dt >> 25 ) & 0x7f ) + 80;
my $mon = ( ( $dt >> 21 ) & 0x0f ) - 1;
my $mday = ( ( $dt >> 16 ) & 0x1f );
my $hour = ( ( $dt >> 11 ) & 0x1f );
my $min = ( ( $dt >> 5 ) & 0x3f );
my $sec = ( ( $dt << 1 ) & 0x3e );
use Time::Local ;
my $time_t;
eval
{
# Use eval to catch crazy dates
$time_t = Time::Local::timegm( $sec, $min, $hour, $mday, $mon, $year);
}
or do
{
my $dosDecode = $year+1900 . sprintf "-%02u-%02u %02u:%02u:%02u", $mon, $mday, $hour, $min, $sec;
warning $FH->tell(), "'Modification Time' value " . decimalHex0x($dt, 4) . " decodes to '$dosDecode': not a valid DOS date/time" ;
return undef
};
return $time_t;
}
sub decode_UT
{
# 0x5455 'UT: Extended Timestamp'
my $extraID = shift ;
my $len = shift;
my $entry = shift;
# Definition in IZ APPNOTE
# NOTE: Although the IZ appnote says that the central directory
# doesn't store the Acces & Creation times, there are
# some implementations that do poopulate the CD incorrectly.
# Caller has determined that at least one byte is available
# When $full is true assume all timestamps are present
my $full = ($len == 13) ;
my $remaining = $len;
my ($data, $flags) = read_C();
my $v = Value_C $flags;
my @f ;
push @f, "Modification" if $flags & 1;
push @f, "Access" if $flags & 2;
push @f, "Creation" if $flags & 4;
$v .= " '" . join(' ', @f) . "'"
if @f;
out $data, " Flags", $v;
info $FH->tell() - 1, extraFieldIdentifier($extraID) . ": Reserved bits set in 'Flags' field"
if $flags & ~0x7;
-- $remaining;
if ($flags & 1 || $full)
{
if ($remaining == 0 )
{
# Central Dir only has Modification Time
error $FH->tell(), extraFieldIdentifier($extraID) . ": Missing field 'Modification Time'" ;
return;
}
else
{
info $FH->tell(), extraFieldIdentifier($extraID) . ": Unexpected 'Modification Time' present"
if ! ($flags & 1) ;
if ($remaining < 4)
{
outSomeData $remaining, " Extra Data";
error $FH->tell() - $remaining,
extraFieldIdentifier($extraID) . ": Truncated reading 'Modification Time'",
expectedMessage(4, $remaining);
return;
}
my ($data, $time) = read_V();
out2 $data, "Modification Time", Value_V($time) . " " . getTime($time) ;
$remaining -= 4 ;
}
}
# The remaining sub-fields are only present in the Local Header
if ($flags & 2 || $full)
{
if ($remaining == 0 && $entry->inCentralDir)
{
# Central Dir doesn't have access time
}
else
{
info $FH->tell(), extraFieldIdentifier($extraID) . ": Unexpected 'Access Time' present"
if ! ($flags & 2) || $entry->inCentralDir ;
if ($remaining < 4)
{
outSomeData $remaining, " Extra Data";
error $FH->tell() - $remaining,
extraFieldIdentifier($extraID) . ": Truncated reading 'Access Time'" ,
expectedMessage(4, $remaining);
return;
}
my ($data, $time) = read_V();
out2 $data, "Access Time", Value_V($time) . " " . getTime($time) ;
$remaining -= 4 ;
}
}
if ($flags & 4 || $full)
{
if ($remaining == 0 && $entry->inCentralDir)
{
# Central Dir doesn't have creation time
}
else
{
info $FH->tell(), extraFieldIdentifier($extraID) . ": Unexpected 'Creation Time' present"
if ! ($flags & 4) || $entry->inCentralDir ;
if ($remaining < 4)
{
outSomeData $remaining, " Extra Data";
error $FH->tell() - $remaining,
extraFieldIdentifier($extraID) . ": Truncated reading 'Creation Time'" ,
expectedMessage(4, $remaining);
return;
}
my ($data, $time) = read_V();
out2 $data, "Creation Time", Value_V($time) . " " . getTime($time) ;
}
}
}
sub decode_Minizip_Signature
{
# 0x10c5 Minizip CMS Signature
my $extraID = shift ;
my $len = shift;
my $entry = shift;
# Definition in https://github.com/zlib-ng/minizip-ng/blob/master/doc/mz_extrafield.md#cms-signature-0x10c5
$CentralDirectory->setMiniZipEncrypted();
if ($len == 0)
{
info $FH->tell() - 2, extraFieldIdentifier($extraID) . ": Zero length Signature";
return;
}
outHexdump($len, " Signature");
}
sub decode_Minizip_Hash
{
# 0x1a51 Minizip Hash
# Definition in https://github.com/zlib-ng/minizip-ng/blob/master/doc/mz_extrafield.md#hash-0x1a51
# caller ckecks there are at least 4 bytes available
my $extraID = shift ;
my $len = shift;
my $entry = shift;
state $Algorithm = {
10 => 'MD5',
20 => 'SHA1',
23 => 'SHA256',
};
my $remaining = $len;
$CentralDirectory->setMiniZipEncrypted();
my ($data, $alg) = read_v();
my $algorithm = $Algorithm->{$alg} // "Unknown";
out $data, " Algorithm", Value_v($alg) . " '$algorithm'";
if (! exists $Algorithm->{$alg})
{
info $FH->tell() - 2, extraFieldIdentifier($extraID) . ": Unknown algorithm ID " .Value_v($alg);
}
my ($d, $digestSize) = read_v();
out $d, " Digest Size", Value_v($digestSize);
$remaining -= 4;
if ($digestSize == 0)
{
info $FH->tell() - 2, extraFieldIdentifier($extraID) . ": Zero length Digest";
}
elsif ($digestSize > $remaining)
{
error $FH->tell() - 2, extraFieldIdentifier($extraID) . ": Digest Size " . decimalHex0x($digestSize) . " > " . decimalHex0x($remaining) . " bytes remaining in extra field" ;
$digestSize = $remaining ;
}
outHexdump($digestSize, " Digest");
$remaining -= $digestSize;
if ($remaining)
{
outHexdump($remaining, " Unexpected Data");
error $FH->tell() - $remaining, extraFieldIdentifier($extraID) . ": " . decimalHex0x($remaining) . " unexpected trailing bytes" ;
}
}
sub decode_Minizip_CD
{
# 0xcdcd Minizip Central Directory
# Definition in https://github.com/zlib-ng/minizip-ng/blob/master/doc/mz_extrafield.md#central-directory-0xcdcd
my $extraID = shift ;
my $len = shift;
my $entry = shift;
$entry->minizip_secure(1);
$CentralDirectory->setMiniZipEncrypted();
my $size = out_Q " Entries";
}
sub decode_AES
{
# ref https://www.winzip.com/en/support/aes-encryption/
# Document version: 1.04
# Last modified: January 30, 2009
my $extraID = shift ;
my $len = shift;
my $entry = shift;
return if $len == 0 ;
my $validAES = 1;
state $lookup = { 1 => "AE-1", 2 => "AE-2" };
my $vendorVersion = out_v " Vendor Version", sub { $lookup->{$_[0]} || "Unknown" } ;
if (! $lookup->{$vendorVersion})
{
$validAES = 0;
warning $FH->tell() - 2, extraFieldIdentifier($extraID) . ": Unknown 'Vendor Version' $vendorVersion. Valid values are 1,2"
}
my $id ;
myRead($id, 2);
my $idValue = out $id, " Vendor ID", unpackValue_v($id) . " '$id'";
if ($id ne 'AE')
{
$validAES = 0;
warning $FH->tell() - 2, extraFieldIdentifier($extraID) . ": Unknown 'Vendor ID' '$idValue'. Valid value is 'AE'"
}
state $strengths = {1 => "128-bit encryption key",
2 => "192-bit encryption key",
3 => "256-bit encryption key",
};
my $strength = out_C " Encryption Strength", sub {$strengths->{$_[0]} || "Unknown" } ;
if (! $strengths->{$strength})
{
$validAES = 0;
warning $FH->tell() - 1, extraFieldIdentifier($extraID) . ": Unknown 'Encryption Strength' $strength. Valid values are 1,2,3"
}
my ($bmethod, $method) = read_v();
out $bmethod, " Compression Method", compressionMethod($method) ;
if (! defined $ZIP_CompressionMethods{$method})
{
$validAES = 0;
warning $FH->tell() - 2, extraFieldIdentifier($extraID) . ": Unknown 'Compression Method' ID " . decimalHex0x($method, 2)
}
$entry->aesStrength($strength) ;
$entry->aesValid($validAES) ;
}
sub decode_Reference
{
# ref https://www.winzip.com/en/support/compression-methods/
my $len = shift;
my $entry = shift;
out_V " CRC";
myRead(my $uuid, 16);
# UUID is big endian
out2 $uuid, "UUID",
unpack('H*', substr($uuid, 0, 4)) . '-' .
unpack('H*', substr($uuid, 4, 2)) . '-' .
unpack('H*', substr($uuid, 6, 2)) . '-' .
unpack('H*', substr($uuid, 8, 2)) . '-' .
unpack('H*', substr($uuid, 10, 6)) ;
}
sub decode_DUMMY
{
my $extraID = shift ;
my $len = shift;
my $entry = shift;
out_V " Data";
}
sub decode_GrowthHint
{
# APPNOTE 6.3.10, sec 4.6.10
my $extraID = shift ;
my $len = shift;
my $entry = shift;
# caller has checked that 4 bytes are available,
# so can output values without checking available space
out_v " Signature" ;
out_v " Initial Value";
my $padding;
myRead($padding, $len - 4);
out2 $padding, "Padding", hexDump16($padding);
if ($padding !~ /^\x00+$/)
{
info $FH->tell(), extraFieldIdentifier($extraID) . ": 'Padding' is not all NULL bytes";
}
}
sub decode_DataStreamAlignment
{
# APPNOTE 6.3.10, sec 4.6.11
my $extraID = shift ;
my $len = shift;
my $entry = shift;
my $inCentralHdr = $entry->inCentralDir ;
return if $len == 0 ;
my ($data, $alignment) = read_v();
out $data, " Alignment", Value_v($alignment) ;
my $recompress_value = $alignment & 0x8000 ? 1 : 0;
my $recompressing = $recompress_value ? "True" : "False";
$alignment &= 0x7FFF ;
my $hexAl = sprintf("%X", $alignment);
out1 " [Bit 15]", "$recompress_value 'Recompress $recompressing'";
out1 " [Bits 0-14]", "$hexAl 'Minimal Alignment $alignment'";
if (! $inCentralHdr && $len - 2 > 0)
{
my $padding;
myRead($padding, $len - 2);
out2 $padding, "Padding", hexDump16($padding);
}
}
sub decode_UX
{
my $extraID = shift ;
my $len = shift;
my $entry = shift;
my $inCentralHdr = $entry->inCentralDir ;
return if $len == 0 ;
my ($data, $time) = read_V();
out2 $data, "Access Time", Value_V($time) . " " . getTime($time) ;
($data, $time) = read_V();
out2 $data, "Modification Time", Value_V($time) . " " . getTime($time) ;
if (! $inCentralHdr ) {
out_v " UID" ;
out_v " GID";
}
}
sub decode_Ux
{
my $extraID = shift ;
my $len = shift;
my $entry = shift;
return if $len == 0 ;
out_v " UID" ;
out_v " GID";
}
sub decodeLitteEndian
{
my $value = shift ;
if (length $value == 8)
{
return unpackValueQ ($value)
}
elsif (length $value == 4)
{
return unpackValue_V ($value)
}
elsif (length $value == 2)
{
return unpackValue_v ($value)
}
elsif (length $value == 1)
{
return unpackValue_C ($value)
}
else {
# TODO - fix this
internalFatal undef, "unsupported decodeLitteEndian length '" . length ($value) . "'";
}
}
sub decode_ux
{
my $extraID = shift ;
my $len = shift;
my $entry = shift;
# caller has checked that 3 bytes are available
return if $len == 0 ;
my $version = out_C " Version" ;
info $FH->tell() - 1, extraFieldIdentifier($extraID) . ": 'Version' should be " . decimalHex0x(1) . ", got " . decimalHex0x($version, 1)
if $version != 1 ;
my $available = $len - 1 ;
my $uidSize = out_C " UID Size";
$available -= 1;
if ($uidSize)
{
if ($available < $uidSize)
{
outSomeData($available, " Bad Extra Data");
error $FH->tell() - $available,
extraFieldIdentifier($extraID) . ": truncated reading 'UID'",
expectedMessage($uidSize, $available);
return;
}
myRead(my $data, $uidSize);
out2 $data, "UID", decodeLitteEndian($data);
$available -= $uidSize ;
}
if ($available < 1)
{
error $FH->tell(),
extraFieldIdentifier($extraID) . ": truncated reading 'GID Size'",
expectedMessage($uidSize, $available);
return ;
}
my $gidSize = out_C " GID Size";
$available -= 1 ;
if ($gidSize)
{
if ($available < $gidSize)
{
outSomeData($available, " Bad Extra Data");
error $FH->tell() - $available,
extraFieldIdentifier($extraID) . ": truncated reading 'GID'",
expectedMessage($gidSize, $available);
return;
}
myRead(my $data, $gidSize);
out2 $data, "GID", decodeLitteEndian($data);
$available -= $gidSize ;
}
}
sub decode_Java_exe
{
my $extraID = shift ;
my $len = shift;
my $entry = shift;
}
sub decode_up
{
# APPNOTE 6.3.10, sec 4.6.9
my $extraID = shift ;
my $len = shift;
my $entry = shift;
out_C " Version";
out_V " NameCRC32";
if ($len - 5 > 0)
{
myRead(my $data, $len - 5);
outputFilename($data, 1, " UnicodeName");
}
}
sub decode_ASi_Unix
{
my $extraID = shift ;
my $len = shift;
my $entry = shift;
# https://stackoverflow.com/questions/76581811/why-does-unzip-ignore-my-zip64-end-of-central-directory-record
out_V " CRC";
my $native_attrib = out_v " Mode";
# TODO - move to separate sub & tidy
if (1) # Unix
{
state $mask = {
0 => '---',
1 => '--x',
2 => '-w-',
3 => '-wx',
4 => 'r--',
5 => 'r-x',
6 => 'rw-',
7 => 'rwx',
} ;
my $rwx = ($native_attrib & 0777);
if ($rwx)
{
my $output = '';
$output .= $mask->{ ($rwx >> 6) & 07 } ;
$output .= $mask->{ ($rwx >> 3) & 07 } ;
$output .= $mask->{ ($rwx >> 0) & 07 } ;
out1 " [Bits 0-8]", Value_v($rwx) . " 'Unix attrib: $output'" ;
out1 " [Bit 9]", "1 'Sticky'"
if $rwx & 0x200 ;
out1 " [Bit 10]", "1 'Set GID'"
if $rwx & 0x400 ;
out1 " [Bit 11]", "1 'Set UID'"
if $rwx & 0x800 ;
my $not_rwx = (($native_attrib >> 12) & 0xF);
if ($not_rwx)
{
state $masks = {
0x0C => 'Socket', # 0x0C 0b1100
0x0A => 'Symbolic Link', # 0x0A 0b1010
0x08 => 'Regular File', # 0x08 0b1000
0x06 => 'Block Device', # 0x06 0b0110
0x04 => 'Directory', # 0x04 0b0100
0x02 => 'Character Device', # 0x02 0b0010
0x01 => 'FIFO', # 0x01 0b0001
};
my $got = $masks->{$not_rwx} // 'Unknown Unix attrib' ;
out1 " [Bits 12-15]", Value_C($not_rwx) . " '$got'"
}
}
}
my $s = out_V " SizDev";
out_v " UID";
out_v " GID";
}
sub decode_uc
{
# APPNOTE 6.3.10, sec 4.6.8
my $extraID = shift ;
my $len = shift;
my $entry = shift;
out_C " Version";
out_V " ComCRC32";
if ($len - 5 > 0)
{
myRead(my $data, $len - 5);
outputFilename($data, 1, " UnicodeCom");
}
}
sub decode_Xceed_unicode
{
# 0x554e
my $extraID = shift ;
my $len = shift;
my $entry = shift;
my $data ;
my $remaining = $len;
# No public definition available, so reverse engineer the content.
# See https://github.com/pmqs/zipdetails/issues/13 for C# source that populates
# this field.
# Fiddler https://www.telerik.com/fiddler) creates this field.
# Local Header only has UTF16LE filename
#
# Field definition
# 4 bytes Signature always XCUN
# 2 bytes Filename Length (divided by 2)
# Filename
# Central has UTF16LE filename & comment
#
# Field definition
# 4 bytes Signature always XCUN
# 2 bytes Filename Length (divided by 2)
# 2 bytes Comment Length (divided by 2)
# Filename
# Comment
# First 4 bytes appear to be little-endian "XCUN" all the time
# Just double check
my ($idb, $id) = read_V();
$remaining -= 4;
my $outid = decimalHex0x($id);
$outid .= " 'XCUN'"
if $idb eq 'NUCX';
out $idb, " ID", $outid;
# Next 2 bytes contains a count of the filename length divided by 2
# Dividing by 2 gives the number of UTF-16 characters.
my $filenameLength = out_v " Filename Length";
$filenameLength *= 2; # Double to get number of bytes to read
$remaining -= 2;
my $commentLength = 0;
if ($entry->inCentralDir)
{
# Comment length only in Central Directory
# Again stored divided by 2.
$commentLength = out_v " Comment Length";
$commentLength *= 2; # Double to get number of bytes to read
$remaining -= 2;
}
# next is a UTF16 encoded filename
if ($filenameLength)
{
if ($filenameLength > $remaining )
{
myRead($data, $remaining);
out redactData($data), " UTF16LE Filename", "'" . redactFilename(decode("UTF16LE", $data)) . "'";
error $FH->tell() - $remaining,
extraFieldIdentifier($extraID) . ": Truncated reading 'UTF16LE Filename'",
expectedMessage($filenameLength, $remaining);
return undef;
}
myRead($data, $filenameLength);
out redactData($data), " UTF16LE Filename", "'" . redactFilename(decode("UTF16LE", $data)) . "'";
$remaining -= $filenameLength;
}
# next is a UTF16 encoded comment
if ($commentLength)
{
if ($commentLength > $remaining )
{
myRead($data, $remaining);
out redactData($data), " UTF16LE Comment", "'" . redactFilename(decode("UTF16LE", $data)) . "'";
error $FH->tell() - $remaining,
extraFieldIdentifier($extraID) . ": Truncated reading 'UTF16LE Comment'",
expectedMessage($filenameLength, $remaining);
return undef;
}
myRead($data, $commentLength);
out redactData($data), " UTF16LE Comment", "'" . redactFilename(decode("UTF16LE", $data)) . "'";
$remaining -= $commentLength;
}
if ($remaining)
{
outHexdump($remaining, " Unexpected Data");
error $FH->tell() - $remaining, extraFieldIdentifier($extraID) . ": " . decimalHex0x($remaining) . " unexpected trailing bytes" ;
}
}
sub decode_Key_Value_Pair
{
# 0x564B 'KV'
# https://github.com/sozip/keyvaluepairs-spec/blob/master/zip_keyvalue_extra_field_specification.md
my $extraID = shift ;
my $len = shift;
my $entry = shift;
my $remaining = $len;
myRead(my $signature, 13);
$remaining -= 13;
if ($signature ne 'KeyValuePairs')
{
error $FH->tell() - 13, extraFieldIdentifier($extraID) . ": 'Signature' field not 'KeyValuePairs'" ;
myRead(my $payload, $remaining);
my $data = hexDump16($signature . $payload);
out2 $signature . $payload, "Extra Payload", $data;
return ;
}
out $signature, ' Signature', "'KeyValuePairs'";
my $kvPairs = out_C " KV Count";
$remaining -= 1;
for my $index (1 .. $kvPairs)
{
my $key;
my $klen = out_v " Key size #$index";
$remaining -= 4;
myRead($key, $klen);
outputFilename $key, 1, " Key #$index";
$remaining -= $klen;
my $value;
my $vlen = out_v " Value size #$index";
$remaining -= 4;
myRead($value, $vlen);
outputFilename $value, 1, " Value #$index";
$remaining -= $vlen;
}
# TODO check that
# * count of kv pairs is accurate
# * no truncation in middle of kv data
# * no trailing data
}
sub decode_NT_security
{
# IZ Appnote
my $extraID = shift ;
my $len = shift;
my $entry = shift;
my $inCentralHdr = $entry->inCentralDir ;
out_V " Uncompressed Size" ;
if (! $inCentralHdr) {
out_C " Version" ;
out_v " CType", sub { "'" . ($ZIP_CompressionMethods{$_[0]} || "Unknown Method") . "'" };
out_V " CRC" ;
my $plen = $len - 4 - 1 - 2 - 4;
outHexdump $plen, " Extra Payload";
}
}
sub decode_MVS
{
# APPNOTE 6.3.10, Appendix
my $extraID = shift ;
my $len = shift;
my $entry = shift;
# data in Big-Endian
myRead(my $data, $len);
my $ID = unpack("N", $data);
if ($ID == 0xE9F3F9F0) # EBCDIC for "Z390"
{
my $d = substr($data, 0, 4, '') ;
out($d, " ID", "'Z390'");
}
out($data, " Extra Payload", hexDump16($data));
}
sub decode_strong_encryption
{
# APPNOTE 6.3.10, sec 4.5.12 & 7.4.2
my $extraID = shift ;
my $len = shift;
my $entry = shift;
# TODO check for overflow is contents > $len
out_v " Format";
out_v " AlgId", sub { $AlgIdLookup{ $_[0] } // "Unknown algorithm" } ;
out_v " BitLen";
out_v " Flags", sub { $FlagsLookup{ $_[0] } // "reserved for certificate processing" } ;
# see APPNOTE 6.3.10, sec 7.4.2 for this part
my $recipients = out_V " Recipients";
my $available = $len - 12;
if ($recipients)
{
if ($available < 2)
{
outSomeData($available, " Badly formed extra data");
# TODO - need warning
return;
}
out_v " HashAlg", sub { $HashAlgLookup{ $_[0] } // "Unknown algorithm" } ;
$available -= 2;
if ($available < 2)
{
outSomeData($available, " Badly formed extra data");
# TODO - need warning
return;
}
my $HSize = out_v " HSize" ;
$available -= 2;
# should have $recipients * $HSize bytes available
if ($recipients * $HSize != $available)
{
outSomeData($available, " Badly formed extra data");
# TODO - need warning
return;
}
my $ix = 1;
for (0 .. $recipients-1)
{
myRead(my $payload, $HSize);
my $data = hexDump16($payload);
out2 $payload, sprintf("Key #%X", $ix), $data;
++ $ix;
}
}
}
sub printAes
{
# ref https://www.winzip.com/en/support/aes-encryption/
my $entry = shift;
return 0
if ! $entry->aesValid;
my %saltSize = (
1 => 8,
2 => 12,
3 => 16,
);
myRead(my $salt, $saltSize{$entry->aesStrength } // 0);
out $salt, "AES Salt", hexDump16($salt);
myRead(my $pwv, 2);
out $pwv, "AES Pwd Ver", hexDump16($pwv);
return $saltSize{$entry->aesStrength} + 2 + 10;
}
sub printLzmaProperties
{
my $len = 0;
my $b1;
my $b2;
my $buffer;
myRead($b1, 2);
my ($verHi, $verLow) = unpack ("CC", $b1);
out $b1, "LZMA Version", sprintf("%02X%02X", $verHi, $verLow) . " '$verHi.$verLow'";
my $LzmaPropertiesSize = out_v "LZMA Properties Size";
$len += 4;
my $LzmaInfo = out_C "LZMA Info", sub { $_[0] == 93 ? "(Default)" : ""};
my $PosStateBits = 0;
my $LiteralPosStateBits = 0;
my $LiteralContextBits = 0;
$PosStateBits = int($LzmaInfo / (9 * 5));
$LzmaInfo -= $PosStateBits * 9 * 5;
$LiteralPosStateBits = int($LzmaInfo / 9);
$LiteralContextBits = $LzmaInfo - $LiteralPosStateBits * 9;
out1 " PosStateBits", $PosStateBits;
out1 " LiteralPosStateBits", $LiteralPosStateBits;
out1 " LiteralContextBits", $LiteralContextBits;
out_V "LZMA Dictionary Size";
# TODO - assumption that this is 5
$len += $LzmaPropertiesSize;
skip($FH, $LzmaPropertiesSize - 5)
if $LzmaPropertiesSize != 5 ;
return $len;
}
sub peekAtOffset
{
# my $fh = shift;
my $offset = shift;
my $len = shift;
my $here = $FH->tell();
seekTo($offset) ;
my $buffer;
myRead($buffer, $len);
seekTo($here);
length $buffer == $len
or return '';
return $buffer;
}
sub readFromOffset
{
# my $fh = shift;
my $offset = shift;
my $len = shift;
seekTo($offset) ;
my $buffer;
myRead($buffer, $len);
length $buffer == $len
or return '';
return $buffer;
}
sub readSignatureFromOffset
{
my $offset = shift ;
# catch use case where attempting to read past EOF
# sub is expecting to return a 32-bit value so return 54-bit out-of-bound value
return MAX64
if $offset + 4 > $FILELEN ;
my $here = $FH->tell();
my $buffer = readFromOffset($offset, 4);
my $gotSig = unpack("V", $buffer) ;
seekTo($here);
return $gotSig;
}
sub chckForAPKSigningBlock
{
my $fh = shift;
my $cdOffset = shift;
my $cdSize = shift;
# APK Signing Block comes directy before the Central directory
# See https://source.android.com/security/apksigning/v2
# If offset available is less than 44, it isn't an APK signing block
#
# len1 8
# id 4
# kv with zero len 8
# len1 8
# magic 16
# ----------
# 44
return (0, 0, '')
if $cdOffset < 44 || $FILELEN - $cdSize < 44 ;
# Step 1 - 16 bytes before CD is literal string "APK Sig Block 42"
my $magicOffset = $cdOffset - 16;
my $buffer = readFromOffset($magicOffset, 16);
return (0, 0, '')
if $buffer ne "APK Sig Block 42" ;
# Step 2 - read the second length field
# and check that it looks ok
$buffer = readFromOffset($cdOffset - 16 - 8, 8);
my $len2 = unpack("Q<", $buffer);
return (0, 0, '')
if $len2 == 0 || $len2 > $FILELEN;
# Step 3 - read the first length field.
# It should be identical to the second one.
my $startApkOffset = $cdOffset - 8 - $len2 ;
$buffer = readFromOffset($startApkOffset, 8);
my $len1 = unpack("Q<", $buffer);
return (0, 0, '')
if $len1 != $len2;
return ($startApkOffset, $cdOffset - 16 - 8, $buffer);
}
sub scanApkBlock
{
state $IDs = {
0x7109871a => "APK Signature v2",
0xf05368c0 => "APK Signature v3",
0x42726577 => "Verity Padding Block", # from https://android.googlesource.com/platform/tools/apksig/+/master/src/main/java/com/android/apksig/internal/apk/ApkSigningBlockUtils.java
0x6dff800d => "Source Stamp",
0x504b4453 => "Dependency Info",
0x71777777 => "APK Channel Block",
0xff3b5998 => "Zero Block",
0x2146444e => "Play Metadata",
} ;
seekTo($FH->tell() - 4) ;
print "\n";
out "", "APK SIGNING BLOCK";
scanApkPadding();
out_Q "Block Length Copy #1";
my $ix = 1;
while ($FH->tell() < $APK - 8)
{
my ($bytes, $id, $len);
($bytes, $len) = read_Q ;
out $bytes, "ID/Value Length #" . sprintf("%X", $ix), Value_Q($len);
($bytes, $id) = read_V;
out $bytes, " ID", Value_V($id) . " '" . ($IDs->{$id} // 'Unknown ID') . "'";
outSomeData($len-4, " Value");
++ $ix;
}
out_Q "Block Length Copy #2";
my $magic ;
myRead($magic, 16);
out $magic, "Magic", qq['$magic'];
}
sub scanApkPadding
{
my $here = $FH->tell();
return
if $here == $START_APK;
# found some padding
my $delta = $START_APK - $here;
my $padding = peekAtOffset($here, $delta);
if ($padding =~ /^\x00+$/)
{
outSomeData($delta, "Null Padding");
}
else
{
outHexdump($delta, "Unexpected Padding");
}
}
sub scanCentralDirectory
{
my $fh = shift;
my $here = $fh->tell();
# Use cases
# 1 32-bit CD
# 2 64-bit CD
my ($offset, $size) = findCentralDirectoryOffset($fh);
$CentralDirectory->{CentralDirectoryOffset} = $offset;
$CentralDirectory->{CentralDirectorySize} = $size;
return ()
if ! defined $offset;
$fh->seek($offset, SEEK_SET) ;
# Now walk the Central Directory Records
my $buffer ;
my $cdIndex = 0;
my $cdEntryOffset = 0;
while ($fh->read($buffer, ZIP_CD_FILENAME_OFFSET) == ZIP_CD_FILENAME_OFFSET &&
unpack("V", $buffer) == ZIP_CENTRAL_HDR_SIG) {
my $startHeader = $fh->tell() - ZIP_CD_FILENAME_OFFSET;
my $cdEntryOffset = $fh->tell() - ZIP_CD_FILENAME_OFFSET;
$HeaderOffsetIndex->addOffsetNoPrefix($cdEntryOffset, ZIP_CENTRAL_HDR_SIG) ;
++ $cdIndex ;
my $extractVer = unpack("v", substr($buffer, 6, 1));
my $gpFlag = unpack("v", substr($buffer, 8, 2));
my $lastMod = unpack("V", substr($buffer, 10, 4));
my $crc = unpack("V", substr($buffer, 16, 4));
my $compressedSize = unpack("V", substr($buffer, 20, 4));
my $uncompressedSize = unpack("V", substr($buffer, 24, 4));
my $filename_length = unpack("v", substr($buffer, 28, 2));
my $extra_length = unpack("v", substr($buffer, 30, 2));
my $comment_length = unpack("v", substr($buffer, 32, 2));
my $diskNumber = unpack("v", substr($buffer, 34, 2));
my $locHeaderOffset = unpack("V", substr($buffer, 42, 4));
my $cdZip64 = 0;
my $zip64Sizes = 0;
if (! full32 $locHeaderOffset)
{
# Check for corrupt offset
# 1. ponting paset EOF
# 2. offset points forward in the file
# 3. value at offset is not a CD record signature
my $commonMessage = "'Local Header Offset' field in '" . Signatures::name(ZIP_CENTRAL_HDR_SIG) . "' is invalid";
checkOffsetValue($locHeaderOffset, $startHeader, 0, $commonMessage,
$startHeader + CentralDirectoryEntry::Offset_RelativeOffsetToLocal(),
ZIP_LOCAL_HDR_SIG, 1) ;
}
$fh->read(my $filename, $filename_length) ;
my $cdEntry = CentralDirectoryEntry->new();
$cdEntry->centralHeaderOffset($startHeader) ;
$cdEntry->localHeaderOffset($locHeaderOffset) ;
$cdEntry->compressedSize($compressedSize) ;
$cdEntry->uncompressedSize($uncompressedSize) ;
$cdEntry->extractVersion($extractVer);
$cdEntry->generalPurposeFlags($gpFlag);
$cdEntry->filename($filename) ;
$cdEntry->lastModDateTime($lastMod);
$cdEntry->languageEncodingFlag($gpFlag & ZIP_GP_FLAG_LANGUAGE_ENCODING) ;
$cdEntry->diskNumber($diskNumber) ;
$cdEntry->crc32($crc) ;
$cdEntry->zip64ExtraPresent($cdZip64) ;
$cdEntry->std_localHeaderOffset($locHeaderOffset) ;
$cdEntry->std_compressedSize($compressedSize) ;
$cdEntry->std_uncompressedSize($uncompressedSize) ;
$cdEntry->std_diskNumber($diskNumber) ;
if ($extra_length)
{
$fh->read(my $extraField, $extra_length) ;
# Check for Zip64
my $zip64Extended = findID(0x0001, $extraField);
if ($zip64Extended)
{
$cdZip64 = 1;
walk_Zip64_in_CD(1, $zip64Extended, $cdEntry, 0);
}
}
$cdEntry->offsetStart($startHeader) ;
$cdEntry->offsetEnd($FH->tell() - 1);
# don't call addEntry until after the extra fields have been scanned
# the localheader offset value may be updated in th ezip64 extra field.
$CentralDirectory->addEntry($cdEntry);
$HeaderOffsetIndex->addOffset($cdEntry->localHeaderOffset, ZIP_LOCAL_HDR_SIG) ;
skip($fh, $comment_length ) ;
}
$FH->seek($fh->tell() - ZIP_CD_FILENAME_OFFSET, SEEK_SET);
# Check for Digital Signature
$HeaderOffsetIndex->addOffset($fh->tell() - 4, ZIP_DIGITAL_SIGNATURE_SIG)
if $fh->read($buffer, 4) == 4 &&
unpack("V", $buffer) == ZIP_DIGITAL_SIGNATURE_SIG ;
$CentralDirectory->sortByLocalOffset();
$HeaderOffsetIndex->sortOffsets();
$fh->seek($here, SEEK_SET) ;
}
use constant ZIP64_END_CENTRAL_LOC_HDR_SIZE => 20;
use constant ZIP64_END_CENTRAL_REC_HDR_MIN_SIZE => 56;
sub offsetFromZip64
{
my $fh = shift ;
my $here = shift;
my $eocdSize = shift;
#### Zip64 end of central directory locator
# check enough bytes available for zip64 locator record
fatal_tryWalk undef, "Cannot find signature for " . Signatures::nameAndHex(ZIP64_END_CENTRAL_LOC_HDR_SIG), # 'Zip64 end of central directory locator': 0x07064b50"
"Possible truncated or corrupt zip file"
if $here < ZIP64_END_CENTRAL_LOC_HDR_SIZE ;
$fh->seek($here - ZIP64_END_CENTRAL_LOC_HDR_SIZE, SEEK_SET) ;
$here = $FH->tell();
my $buffer;
my $got = 0;
$fh->read($buffer, ZIP64_END_CENTRAL_LOC_HDR_SIZE);
my $gotSig = unpack("V", $buffer);
fatal_tryWalk $here - 4, sprintf("Expected signature for " . Signatures::nameAndHex(ZIP64_END_CENTRAL_LOC_HDR_SIG) . " not found, got 0x%X", $gotSig)
if $gotSig != ZIP64_END_CENTRAL_LOC_HDR_SIG ;
$HeaderOffsetIndex->addOffset($fh->tell() - ZIP64_END_CENTRAL_LOC_HDR_SIZE, ZIP64_END_CENTRAL_LOC_HDR_SIG) ;
my $cd64 = unpack "Q<", substr($buffer, 8, 8);
my $totalDisks = unpack "V", substr($buffer, 16, 4);
testPossiblePrefix($cd64, ZIP64_END_CENTRAL_REC_HDR_SIG);
if ($totalDisks > 0)
{
my $commonMessage = "'Offset to Zip64 End of Central Directory Record' field in '" . Signatures::name(ZIP64_END_CENTRAL_LOC_HDR_SIG) . "' is invalid";
$cd64 = checkOffsetValue($cd64, $here, 0, $commonMessage, $here + 8, ZIP64_END_CENTRAL_REC_HDR_SIG, 1) ;
}
my $delta = $here - $cd64;
#### Zip64 end of central directory record
my $zip64eocd_name = "'" . Signatures::name(ZIP64_END_CENTRAL_REC_HDR_SIG) . "'";
my $zip64eocd_name_value = Signatures::nameAndHex(ZIP64_END_CENTRAL_REC_HDR_SIG);
my $zip64eocd_value = Signatures::hexValue(ZIP64_END_CENTRAL_REC_HDR_SIG);
# check enough bytes available
# fatal_tryWalk sprintf "Size of 'Zip64 End of Central Directory Record' 0x%X too small", $cd64
fatal_tryWalk undef, sprintf "Size of $zip64eocd_name 0x%X too small", $cd64
if $delta < ZIP64_END_CENTRAL_REC_HDR_MIN_SIZE;
# Seek to Zip64 End of Central Directory Record
$fh->seek($cd64, SEEK_SET) ;
$HeaderOffsetIndex->addOffsetNoPrefix($fh->tell(), ZIP64_END_CENTRAL_REC_HDR_SIG) ;
$fh->read($buffer, ZIP64_END_CENTRAL_REC_HDR_MIN_SIZE) ;
my $sig = unpack("V", substr($buffer, 0, 4)) ;
fatal_tryWalk undef, sprintf "Cannot find $zip64eocd_name: expected $zip64eocd_value but got 0x%X", $sig
if $sig != ZIP64_END_CENTRAL_REC_HDR_SIG ;
# pkzip sets the extract zip spec to 6.2 (0x3E) to signal a v2 record
# See APPNOTE 6.3.10, section, 7.3.3
# Version 1 header is 44 bytes (assuming no extensible data sector)
# Version 2 header (see APPNOTE 6.3.7, section) is > 44 bytes
my $extractSpec = unpack "C", substr($buffer, 14, 1);
my $diskNumber = unpack "V", substr($buffer, 16, 4);
my $cdDiskNumber = unpack "V", substr($buffer, 20, 4);
my $entriesOnThisDisk = unpack "Q<", substr($buffer, 24, 8);
my $totalEntries = unpack "Q<", substr($buffer, 32, 8);
my $centralDirSize = unpack "Q<", substr($buffer, 40, 8);
my $centralDirOffset = unpack "Q<", substr($buffer, 48, 8);
if ($extractSpec >= 0x3E)
{
$opt_walk = 1;
$CentralDirectory->setPkEncryptedCD();
}
if (! emptyArchive($here, $diskNumber, $cdDiskNumber, $entriesOnThisDisk, $totalEntries, $centralDirSize, $centralDirOffset))
{
my $commonMessage = "'Offset to Central Directory' field in $zip64eocd_name is invalid";
$centralDirOffset = checkOffsetValue($centralDirOffset, $here, 0, $commonMessage, $here + 48, ZIP_CENTRAL_HDR_SIG, 1, $extractSpec < 0x3E) ;
}
# TODO - APPNOTE allows an extensible data sector here (see APPNOTE 6.3.10, section 4.3.14.2) -- need to take this into account
return ($centralDirOffset, $centralDirSize) ;
}
use constant Pack_ZIP_END_CENTRAL_HDR_SIG => pack("V", ZIP_END_CENTRAL_HDR_SIG);
sub findCentralDirectoryOffset
{
my $fh = shift ;
# Most common use-case is where there is no comment, so
# know exactly where the end of central directory record
# should be.
need ZIP_EOCD_MIN_SIZE, Signatures::name(ZIP_END_CENTRAL_HDR_SIG);
$fh->seek(-ZIP_EOCD_MIN_SIZE(), SEEK_END) ;
my $here = $fh->tell();
my $is64bit = $here > MAX32;
my $over64bit = $here & (~ MAX32);
my $buffer;
$fh->read($buffer, ZIP_EOCD_MIN_SIZE);
my $zip64 = 0;
my $diskNumber ;
my $cdDiskNumber ;
my $entriesOnThisDisk ;
my $totalEntries ;
my $centralDirSize ;
my $centralDirOffset ;
my $commentLength = 0;
my $trailingBytes = 0;
if ( unpack("V", $buffer) == ZIP_END_CENTRAL_HDR_SIG ) {
$HeaderOffsetIndex->addOffset($here + $PREFIX_DELTA, ZIP_END_CENTRAL_HDR_SIG) ;
$diskNumber = unpack("v", substr($buffer, 4, 2));
$cdDiskNumber = unpack("v", substr($buffer, 6, 2));
$entriesOnThisDisk= unpack("v", substr($buffer, 8, 2));
$totalEntries = unpack("v", substr($buffer, 10, 2));
$centralDirSize = unpack("V", substr($buffer, 12, 4));
$centralDirOffset = unpack("V", substr($buffer, 16, 4));
$commentLength = unpack("v", substr($buffer, 20, 2));
}
else {
$fh->seek(0, SEEK_END) ;
my $fileLen = $fh->tell();
my $want = 0 ;
while(1) {
$want += 1024 * 32;
my $seekTo = $fileLen - $want;
if ($seekTo < 0 ) {
$seekTo = 0;
$want = $fileLen ;
}
$fh->seek( $seekTo, SEEK_SET);
$fh->read($buffer, $want) ;
my $pos = rindex( $buffer, Pack_ZIP_END_CENTRAL_HDR_SIG);
if ($pos >= 0 && $want - $pos > ZIP_EOCD_MIN_SIZE) {
$here = $seekTo + $pos ;
$HeaderOffsetIndex->addOffset($here + $PREFIX_DELTA, ZIP_END_CENTRAL_HDR_SIG) ;
$diskNumber = unpack("v", substr($buffer, $pos + 4, 2));
$cdDiskNumber = unpack("v", substr($buffer, $pos + 6, 2));
$entriesOnThisDisk= unpack("v", substr($buffer, $pos + 8, 2));
$totalEntries = unpack("v", substr($buffer, $pos + 10, 2));
$centralDirSize = unpack("V", substr($buffer, $pos + 12, 4));
$centralDirOffset = unpack("V", substr($buffer, $pos + 16, 4));
$commentLength = unpack("v", substr($buffer, $pos + 20, 2)) // 0;
my $expectedEof = $fileLen - $want + $pos + ZIP_EOCD_MIN_SIZE + $commentLength ;
# check for trailing data after end of zip
if ($expectedEof < $fileLen ) {
$TRAILING = $expectedEof ;
$trailingBytes = $FILELEN - $expectedEof ;
}
last ;
}
return undef
if $want == $fileLen;
}
}
$EOCD_Present = 1;
# Empty zip file can just contain an EOCD record
return (0, 0)
if ZIP_EOCD_MIN_SIZE + $commentLength + $trailingBytes == $FILELEN ;
if (needZip64EOCDLocator($diskNumber, $cdDiskNumber, $entriesOnThisDisk, $totalEntries, $centralDirOffset, $centralDirSize) &&
! emptyArchive($here, $diskNumber, $cdDiskNumber, $entriesOnThisDisk, $totalEntries, $centralDirOffset, $centralDirSize))
{
($centralDirOffset, $centralDirSize) = offsetFromZip64($fh, $here, ZIP_EOCD_MIN_SIZE + $commentLength + $trailingBytes)
}
elsif ($is64bit)
{
# use-case is where a 64-bit zip file doesn't use the 64-bit
# extensions.
# print "EOCD not 64-bit $centralDirOffset ($here)\n" ;
fatal_tryWalk $here, "Zip file > 4Gig. Expected 'Offset to Central Dir' to be 0xFFFFFFFF, got " . hexValue($centralDirOffset);
$centralDirOffset += $over64bit;
$is64In32 = 1;
}
else
{
if ($centralDirSize)
{
my $commonMessage = "'Offset to Central Directory' field in '" . Signatures::name(ZIP_END_CENTRAL_HDR_SIG) . "' is invalid";
$centralDirOffset = checkOffsetValue($centralDirOffset, $here, $centralDirSize, $commonMessage, $here + 16, ZIP_CENTRAL_HDR_SIG, 1) ;
}
}
return (0, 0)
if $totalEntries == 0 && $entriesOnThisDisk == 0;
# APK Signing Block is directly before the first CD entry
# Check if it is present
($START_APK, $APK, $APK_LEN) = chckForAPKSigningBlock($fh, $centralDirOffset, ZIP_EOCD_MIN_SIZE + $commentLength);
return ($centralDirOffset, $centralDirSize) ;
}
sub findID
{
my $id_want = shift ;
my $data = shift;
my $XLEN = length $data ;
my $offset = 0 ;
while ($offset < $XLEN) {
return undef
if $offset + ZIP_EXTRA_SUBFIELD_HEADER_SIZE > $XLEN ;
my $id = substr($data, $offset, ZIP_EXTRA_SUBFIELD_ID_SIZE);
$id = unpack("v", $id);
$offset += ZIP_EXTRA_SUBFIELD_ID_SIZE;
my $subLen = unpack("v", substr($data, $offset,
ZIP_EXTRA_SUBFIELD_LEN_SIZE));
$offset += ZIP_EXTRA_SUBFIELD_LEN_SIZE ;
return undef
if $offset + $subLen > $XLEN ;
return substr($data, $offset, $subLen)
if $id eq $id_want ;
$offset += $subLen ;
}
return undef ;
}
sub nibbles
{
my @nibbles = (
[ 16 => 0x1000000000000000 ],
[ 15 => 0x100000000000000 ],
[ 14 => 0x10000000000000 ],
[ 13 => 0x1000000000000 ],
[ 12 => 0x100000000000 ],
[ 11 => 0x10000000000 ],
[ 10 => 0x1000000000 ],
[ 9 => 0x100000000 ],
[ 8 => 0x10000000 ],
[ 7 => 0x1000000 ],
[ 6 => 0x100000 ],
[ 5 => 0x10000 ],
[ 4 => 0x1000 ],
[ 4 => 0x100 ],
[ 4 => 0x10 ],
[ 4 => 0x1 ],
);
my $value = shift ;
for my $pair (@nibbles)
{
my ($count, $limit) = @{ $pair };
return $count
if $value >= $limit ;
}
}
{
package HeaderOffsetEntry;
sub new
{
my $class = shift ;
my $offset = shift ;
my $signature = shift;
bless [ $offset, $signature, Signatures::name($signature)] , $class;
}
sub offset
{
my $self = shift;
return $self->[0];
}
sub signature
{
my $self = shift;
return $self->[1];
}
sub name
{
my $self = shift;
return $self->[2];
}
}
{
package HeaderOffsetIndex;
# Store a list of header offsets recorded when scannning the central directory
sub new
{
my $class = shift ;
my %object = (
'offsetIndex' => [],
'offset2Index' => {},
'offset2Signature' => {},
'currentIndex' => -1,
'currentSignature' => 0,
# 'sigNames' => $sigNames,
) ;
bless \%object, $class;
}
sub sortOffsets
{
my $self = shift ;
@{ $self->{offsetIndex} } = sort { $a->[0] <=> $b->[0] }
@{ $self->{offsetIndex} };
my $ix = 0;
$self->{offset2Index}{$_} = $ix++
for @{ $self->{offsetIndex} } ;
}
sub addOffset
{
my $self = shift ;
my $offset = shift ;
my $signature = shift ;
$offset += $PREFIX_DELTA ;
$self->addOffsetNoPrefix($offset, $signature);
}
sub addOffsetNoPrefix
{
my $self = shift ;
my $offset = shift ;
my $signature = shift ;
my $name = Signatures::name($signature);
if (! defined $self->{offset2Signature}{$offset})
{
push @{ $self->{offsetIndex} }, HeaderOffsetEntry->new($offset, $signature) ;
$self->{offset2Signature}{$offset} = $signature;
}
}
sub getNextIndex
{
my $self = shift ;
my $offset = shift ;
$self->{currentIndex} ++;
return ${ $self->{offsetIndex} }[$self->{currentIndex}] // undef
}
sub rewindIndex
{
my $self = shift ;
my $offset = shift ;
$self->{currentIndex} --;
}
sub dump
{
my $self = shift;
say "### HeaderOffsetIndex";
say "### Offset\tSignature";
for my $x ( @{ $self->{offsetIndex} } )
{
my ($offset, $sig) = @$x;
printf "### %X %d\t\t" . $x->name() . "\n", $x->offset(), $x->offset();
}
}
sub checkForOverlap
{
my $self = shift ;
my $need = shift;
my $needOffset = $FH->tell() + $need;
for my $hdrOffset (@{ $self->{offsetIndex} })
{
my $delta = $hdrOffset - $needOffset;
return [$self->{offsetIndex}{$hdrOffset}, $needOffset - $hdrOffset]
if $delta <= 0 ;
}
return [undef, undef];
}
}
{
package FieldsAndAccessors;
sub Add
{
use Data::Dumper ;
my $classname = shift;
my $object = shift;
my $fields = shift ;
my $no_handler = shift // {};
state $done = {};
while (my ($name, $value) = each %$fields)
{
my $method = "${classname}::$name";
$object->{$name} = $value;
# don't auto-create a handler
next
if $no_handler->{$name};
no strict 'refs';
# Don't use lvalue sub for now - vscode debugger breaks with it enabled.
# https://github.com/richterger/Perl-LanguageServer/issues/194
# *$method = sub : lvalue {
# $_[0]->{$name} ;
# }
# unless defined $done->{$method};
# Auto-generate getter/setter
*$method = sub {
$_[0]->{$name} = $_[1]
if @_ == 2;
return $_[0]->{$name} ;
}
unless defined $done->{$method};
++ $done->{$method};
}
}
}
{
package BaseEntry ;
sub new
{
my $class = shift ;
state $index = 0;
my %fields = (
'index' => $index ++,
'zip64' => 0,
'offsetStart' => 0,
'offsetEnd' => 0,
'inCentralDir' => 0,
'encapsulated' => 0, # enclosed in outer zip
'childrenCount' => 0, # this entry is a zip with enclosed children
'streamed' => 0,
'languageEncodingFlag' => 0,
'entryType' => 0,
) ;
my $self = bless {}, $class;
FieldsAndAccessors::Add($class, $self, \%fields) ;
return $self;
}
sub increment_childrenCount
{
my $self = shift;
$self->{childrenCount} ++;
}
}
{
package LocalCentralEntryBase ;
use parent -norequire , 'BaseEntry' ;
sub new
{
my $class = shift ;
my $self = $class->SUPER::new();
my %fields = (
# fields from the header
'centralHeaderOffset' => 0,
'localHeaderOffset' => 0,
'extractVersion' => 0,
'generalPurposeFlags' => 0,
'compressedMethod' => 0,
'lastModDateTime' => 0,
'crc32' => 0,
'compressedSize' => 0,
'uncompressedSize' => 0,
'filename' => '',
'outputFilename' => '',
# inferred data
# 'InCentralDir' => 0,
# 'zip64' => 0,
'zip64ExtraPresent' => 0,
'zip64SizesPresent' => 0,
'payloadOffset' => 0,
# zip64 extra
'zip64_compressedSize' => undef,
'zip64_uncompressedSize' => undef,
'zip64_localHeaderOffset' => undef,
'zip64_diskNumber' => undef,
'zip64_diskNumberPresent' => 0,
# Values direct from the header before merging any Zip64 values
'std_compressedSize' => undef,
'std_uncompressedSize' => undef,
'std_localHeaderOffset' => undef,
'std_diskNumber' => undef,
# AES
'aesStrength' => 0,
'aesValid' => 0,
# Minizip CD encryption
'minizip_secure' => 0,
) ;
FieldsAndAccessors::Add($class, $self, \%fields) ;
return $self;
}
}
{
package Zip64EndCentralHeaderEntry ;
use parent -norequire , 'LocalCentralEntryBase' ;
sub new
{
my $class = shift ;
my $self = $class->SUPER::new();
my %fields = (
'inCentralDir' => 1,
) ;
FieldsAndAccessors::Add($class, $self, \%fields) ;
return $self;
}
}
{
package CentralDirectoryEntry;
use parent -norequire , 'LocalCentralEntryBase' ;
use constant Offset_VersionMadeBy => 4;
use constant Offset_VersionNeededToExtract => 6;
use constant Offset_GeneralPurposeFlags => 8;
use constant Offset_CompressionMethod => 10;
use constant Offset_ModificationTime => 12;
use constant Offset_ModificationDate => 14;
use constant Offset_CRC32 => 16;
use constant Offset_CompressedSize => 20;
use constant Offset_UncompressedSize => 24;
use constant Offset_FilenameLength => 28;
use constant Offset_ExtraFieldLength => 30;
use constant Offset_FileCommentLength => 32;
use constant Offset_DiskNumber => 34;
use constant Offset_InternalAttributes => 36;
use constant Offset_ExternalAttributes => 38;
use constant Offset_RelativeOffsetToLocal => 42;
use constant Offset_Filename => 46;
sub new
{
my $class = shift ;
my $offset = shift;
# check for existing entry
return $CentralDirectory->{byCentralOffset}{$offset}
if defined $offset && defined $CentralDirectory->{byCentralOffset}{$offset} ;
my $self = $class->SUPER::new();
my %fields = (
'diskNumber' => 0,
'comment' => "",
'ldEntry' => undef,
) ;
FieldsAndAccessors::Add($class, $self, \%fields) ;
$self->inCentralDir(1) ;
$self->entryType(::ZIP_CENTRAL_HDR_SIG) ;
return $self;
}
}
{
package CentralDirectory;
sub new
{
my $class = shift ;
my %object = (
'entries' => [],
'count' => 0,
'byLocalOffset' => {},
'byCentralOffset' => {},
'byName' => {},
'offset2Index' => {},
'normalized_filenames' => {},
'CentralDirectoryOffset' => 0,
'CentralDirectorySize' => 0,
'zip64' => 0,
'encryptedCD' => 0,
'minizip_secure' => 0,
'alreadyScanned' => 0,
) ;
bless \%object, $class;
}
sub addEntry
{
my $self = shift ;
my $entry = shift ;
my $localHeaderOffset = $entry->localHeaderOffset ;
my $CentralDirectoryOffset = $entry->centralHeaderOffset ;
my $filename = $entry->filename ;
Nesting::add($entry);
# Create a reference from Central to Local header entries
my $ldEntry = Nesting::getLdEntryByOffset($localHeaderOffset);
if ($ldEntry)
{
$entry->ldEntry($ldEntry) ;
# LD -> CD
# can have multiple LD entries point to same CD
# so need to keep a list
$ldEntry->addCdEntry($entry);
}
# only check for duplicate in real CD scan
if ($self->{alreadyScanned} && ! $entry->encapsulated )
{
my $existing = $self->{byName}{$filename} ;
if ($existing && $existing->centralHeaderOffset != $entry->centralHeaderOffset)
{
::error $CentralDirectoryOffset,
"Duplicate Central Directory entries for filename '$filename'",
"Current Central Directory entry at offset " . ::decimalHex0x($CentralDirectoryOffset),
"Duplicate Central Directory entry at offset " . ::decimalHex0x($self->{byName}{$filename}{centralHeaderOffset});
# not strictly illegal to have duplicate filename, so save this one
}
else
{
my $existingNormalizedEntry = $self->normalize_filename($entry, $filename);
if ($existingNormalizedEntry)
{
::warning $CentralDirectoryOffset,
"Portability Issue: Found case-insensitive duplicate for filename '$filename'",
"Current Central Directory entry at offset " . ::decimalHex0x($CentralDirectoryOffset),
"Duplicate Central Directory entry for filename '" . $existingNormalizedEntry->outputFilename . "' at offset " . ::decimalHex0x($existingNormalizedEntry->centralHeaderOffset);
}
}
}
# CD can get processed twice, so return if already processed
return
if $self->{byCentralOffset}{$CentralDirectoryOffset} ;
if (! $entry->encapsulated )
{
push @{ $self->{entries} }, $entry;
$self->{byLocalOffset}{$localHeaderOffset} = $entry;
$self->{byCentralOffset}{$CentralDirectoryOffset} = $entry;
$self->{byName}{ $filename } = $entry;
$self->{offset2Index} = $self->{count} ++;
}
}
sub exists
{
my $self = shift ;
return scalar @{ $self->{entries} };
}
sub sortByLocalOffset
{
my $self = shift ;
@{ $self->{entries} } = sort { $a->localHeaderOffset() <=> $b->localHeaderOffset() }
@{ $self->{entries} };
}
sub getByLocalOffset
{
my $self = shift ;
my $offset = shift ;
# TODO - what happens if none exists?
my $entry = $self->{byLocalOffset}{$offset - $PREFIX_DELTA} ;
return $entry ;
}
sub localOffset
{
my $self = shift ;
my $offset = shift ;
# TODO - what happens if none exists?
return $self->{byLocalOffset}{$offset - $PREFIX_DELTA} ;
}
sub getNextLocalOffset
{
my $self = shift ;
my $offset = shift ;
my $index = $self->{offset2Index} ;
if ($index + 1 >= $self->{count})
{
return 0;
}
return ${ $self->{entries} }[$index+1]->localHeaderOffset() ;
}
sub inCD
{
my $self = shift ;
$FH->tell() >= $self->{CentralDirectoryOffset};
}
sub setPkEncryptedCD
{
my $self = shift ;
$self->{encryptedCD} = 1 ;
}
sub setMiniZipEncrypted
{
my $self = shift ;
$self->{minizip_secure} = 1 ;
}
sub isMiniZipEncrypted
{
my $self = shift ;
return $self->{minizip_secure};
}
sub isEncryptedCD
{
my $self = shift ;
return $self->{encryptedCD} && ! $self->{minizip_secure};
}
sub normalize_filename
{
# check if there is a filename that already exists
# with the same name when normalized to lower case
my $self = shift ;
my $entry = shift;
my $filename = shift;
my $nFilename = lc $filename;
my $lookup = $self->{normalized_filenames}{$nFilename};
# if ($lookup && $lookup ne $filename)
if ($lookup)
{
return $lookup,
}
$self->{normalized_filenames}{$nFilename} = $entry;
return undef;
}
}
{
package LocalDirectoryEntry;
use parent -norequire , 'LocalCentralEntryBase' ;
use constant Offset_VersionNeededToExtract => 4;
use constant Offset_GeneralPurposeFlags => 6;
use constant Offset_CompressionMethod => 8;
use constant Offset_ModificationTime => 10;
use constant Offset_ModificationDate => 12;
use constant Offset_CRC32 => 14;
use constant Offset_CompressedSize => 18;
use constant Offset_UncompressedSize => 22;
use constant Offset_FilenameLength => 26;
use constant Offset_ExtraFieldLength => 27;
use constant Offset_Filename => 30;
sub new
{
my $class = shift ;
my $self = $class->SUPER::new();
my %fields = (
'streamedMatch' => 0,
'readDataDescriptor' => 0,
'cdEntryIndex' => {},
'cdEntryList' => [],
) ;
FieldsAndAccessors::Add($class, $self, \%fields) ;
$self->inCentralDir(0) ;
$self->entryType(::ZIP_LOCAL_HDR_SIG) ;
return $self;
}
sub addCdEntry
{
my $self = shift ;
my $entry = shift;
# don't want encapsulated entries
# and protect against duplicates
return
if $entry->encapsulated ||
$self->{cdEntryIndex}{$entry->index} ++ >= 1;
push @{ $self->{cdEntryList} }, $entry ;
}
sub getCdEntry
{
my $self = shift ;
return []
if ! $self->{cdEntryList} ;
return $self->{cdEntryList}[0] ;
}
sub getCdEntries
{
my $self = shift ;
return $self->{cdEntryList} ;
}
}
{
package LocalDirectory;
sub new
{
my $class = shift ;
my %object = (
'entries' => [],
'count' => 0,
'byLocalOffset' => {},
'byName' => {},
'offset2Index' => {},
'normalized_filenames' => {},
'CentralDirectoryOffset' => 0,
'CentralDirectorySize' => 0,
'zip64' => 0,
'encryptedCD' => 0,
'streamedPresent' => 0,
) ;
bless \%object, $class;
}
sub isLocalEntryNested
{
my $self = shift ;
my $localEntry = shift;
return Nesting::getFirstEncapsulation($localEntry);
}
sub addEntry
{
my $self = shift ;
my $localEntry = shift ;
my $filename = $localEntry->filename ;
my $localHeaderOffset = $localEntry->localHeaderOffset;
my $payloadOffset = $localEntry->payloadOffset ;
my $existingEntry = $self->{byName}{$filename} ;
my $endSurfaceArea = $payloadOffset + ($localEntry->compressedSize // 0) ;
if ($existingEntry)
{
::error $localHeaderOffset,
"Duplicate Local Directory entry for filename '$filename'",
"Current Local Directory entry at offset " . ::decimalHex0x($localHeaderOffset),
"Duplicate Local Directory entry at offset " . ::decimalHex0x($existingEntry->localHeaderOffset),
}
else
{
my ($existing_filename, $offset) = $self->normalize_filename($filename);
if ($existing_filename)
{
::warning $localHeaderOffset,
"Portability Issue: Found case-insensitive duplicate for filename '$filename'",
"Current Local Directory entry at offset " . ::decimalHex0x($localHeaderOffset),
"Duplicate Local Directory entry for filename '$existing_filename' at offset " . ::decimalHex0x($offset);
}
}
# keep nested local entries for zipbomb deteection
push @{ $self->{entries} }, $localEntry;
$self->{byLocalOffset}{$localHeaderOffset} = $localEntry;
$self->{byName}{ $filename } = $localEntry;
$self->{streamedPresent} ++
if $localEntry->streamed;
Nesting::add($localEntry);
}
sub exists
{
my $self = shift ;
return scalar @{ $self->{entries} };
}
sub sortByLocalOffset
{
my $self = shift ;
@{ $self->{entries} } = sort { $a->localHeaderOffset() <=> $b->localHeaderOffset() }
@{ $self->{entries} };
}
sub localOffset
{
my $self = shift ;
my $offset = shift ;
return $self->{byLocalOffset}{$offset} ;
}
sub getByLocalOffset
{
my $self = shift ;
my $offset = shift ;
# TODO - what happens if none exists?
my $entry = $self->{byLocalOffset}{$offset} ;
return $entry ;
}
sub getNextLocalOffset
{
my $self = shift ;
my $offset = shift ;
my $index = $self->{offset2Index} ;
if ($index + 1 >= $self->{count})
{
return 0;
}
return ${ $self->{entries} }[$index+1]->localHeaderOffset ;
}
sub lastStreamedEntryAdded
{
my $self = shift ;
my $offset = shift ;
for my $entry ( reverse @{ $self->{entries} } )
{
if ($entry->streamed)# && ! $entry->streamedMatch)
{
$entry->streamedMatch($entry->streamedMatch + 1) ;
return $entry;
}
}
return undef;
}
sub inCD
{
my $self = shift ;
$FH->tell() >= $self->{CentralDirectoryOffset};
}
sub setPkEncryptedCD
{
my $self = shift ;
$self->{encryptedCD} = 1 ;
}
sub isEncryptedCD
{
my $self = shift ;
return $self->{encryptedCD} ;
}
sub anyStreamedEntries
{
my $self = shift ;
return $self->{streamedPresent} ;
}
sub normalize_filename
{
# check if there is a filename that already exists
# with the same name when normalized to lower case
my $self = shift ;
my $filename = shift;
my $nFilename = lc $filename;
my $lookup = $self->{normalized_filenames}{$nFilename};
if ($lookup && $lookup ne $filename)
{
return $self->{byName}{$lookup}{outputFilename},
$self->{byName}{$lookup}{localHeaderOffset}
}
$self->{normalized_filenames}{$nFilename} = $filename;
return undef, undef;
}
}
{
package Eocd ;
sub new
{
my $class = shift ;
my %object = (
'zip64' => 0,
) ;
bless \%object, $class;
}
}
sub displayFileInfo
{
return;
my $filename = shift;
info undef,
"Filename : '$filename'",
"Size : " . (-s $filename) . " (" . decimalHex0x(-s $filename) . ")",
# "Native Encoding: '" . TextEncoding::getNativeLocaleName() . "'",
}
{
package TextEncoding;
my $nativeLocaleEncoding = getNativeLocale();
my $opt_EncodingFrom = $nativeLocaleEncoding;
my $opt_EncodingTo = $nativeLocaleEncoding ;
my $opt_Encoding_Enabled;
my $opt_Debug_Encoding;
my $opt_use_LanguageEncodingFlag;
sub setDefaults
{
$nativeLocaleEncoding = getNativeLocale();
$opt_EncodingFrom = $nativeLocaleEncoding;
$opt_EncodingTo = $nativeLocaleEncoding ;
$opt_Encoding_Enabled = 1;
$opt_Debug_Encoding = 0;
$opt_use_LanguageEncodingFlag = 1;
}
sub getNativeLocale
{
state $enc;
if (! defined $enc)
{
eval
{
require encoding ;
my $encoding = encoding::_get_locale_encoding() ;
if (! $encoding)
{
# CP437 is the legacy default for zip files
$encoding = 'cp437';
# ::warning undef, "Cannot determine system charset: defaulting to '$encoding'"
}
$enc = Encode::find_encoding($encoding) ;
} ;
}
return $enc;
}
sub getNativeLocaleName
{
state $name;
return $name
if defined $name ;
if (! defined $name)
{
my $enc = getNativeLocale();
if ($enc)
{
$name = $enc->name()
}
else
{
$name = 'unknown'
}
}
return $name ;
}
sub parseEncodingOption
{
my $opt_name = shift;
my $opt_value = shift;
my $enc = Encode::find_encoding($opt_value) ;
die "Encoding '$opt_value' not found for option '$opt_name'\n"
unless ref $enc;
if ($opt_name eq 'encoding')
{
$opt_EncodingFrom = $enc;
}
elsif ($opt_name eq 'output-encoding')
{
$opt_EncodingTo = $enc;
}
else
{
die "Unknown option $opt_name\n"
}
}
sub NoEncoding
{
my $opt_name = shift;
my $opt_value = shift;
$opt_Encoding_Enabled = 0 ;
}
sub LanguageEncodingFlag
{
my $opt_name = shift;
my $opt_value = shift;
$opt_use_LanguageEncodingFlag = $opt_value ;
}
sub debugEncoding
{
if (@_)
{
$opt_Debug_Encoding = 1 ;
}
return $opt_Debug_Encoding ;
}
sub encodingInfo
{
return
unless $opt_Encoding_Enabled && $opt_Debug_Encoding ;
my $enc = TextEncoding::getNativeLocaleName();
my $from = $opt_EncodingFrom->name();
my $to = $opt_EncodingTo->name();
::debug undef, "Debug Encoding Enabled",
"System Default Encoding: '$enc'",
"Encoding used when reading from zip file: '$from'",
"Encoding used for display output: '$to'";
}
sub cleanEval
{
chomp $_[0] ;
$_[0] =~ s/ at .+ line \d+\.$// ;
return $_[0];
}
sub decode
{
my $name = shift ;
my $type = shift ;
my $LanguageEncodingFlag = shift ;
return $name
if ! $opt_Encoding_Enabled ;
# TODO - check for badly formed content
if ($LanguageEncodingFlag && $opt_use_LanguageEncodingFlag)
{
# use "utf-8-strict" to catch invalid codepoints
eval { $name = Encode::decode('utf-8-strict', $name, Encode::FB_CROAK ) } ;
::warning $FH->tell() - length $name, "Could not decode 'UTF-8' $type: " . cleanEval $@
if $@ ;
}
else
{
eval { $name = $opt_EncodingFrom->decode($name, Encode::FB_CROAK ) } ;
::warning $FH->tell() - length $name, "Could not decode '" . $opt_EncodingFrom->name() . "' $type: " . cleanEval $@
if $@;
}
# remove any BOM
$name =~ s/^\x{FEFF}//;
return $name ;
}
sub encode
{
my $name = shift ;
my $type = shift ;
my $LanguageEncodingFlag = shift ;
return $name
if ! $opt_Encoding_Enabled;
if ($LanguageEncodingFlag && $opt_use_LanguageEncodingFlag)
{
eval { $name = Encode::encode('utf8', $name, Encode::FB_CROAK ) } ;
::warning $FH->tell() - length $name, "Could not encode 'utf8' $type: " . cleanEval $@
if $@ ;
}
else
{
eval { $name = $opt_EncodingTo->encode($name, Encode::FB_CROAK ) } ;
::warning $FH->tell() - length $name, "Could not encode '" . $opt_EncodingTo->name() . "' $type: " . cleanEval $@
if $@;
}
return $name;
}
}
{
package Nesting;
use Data::Dumper;
my @nestingStack = ();
my %encapsulations;
my %inner2outer;
my $encapsulationCount = 0;
my %index2entry ;
my %offset2entry ;
# my %localOffset2cdEntry;
sub clearStack
{
@nestingStack = ();
%encapsulations = ();
%inner2outer = ();
%index2entry = ();
%offset2entry = ();
$encapsulationCount = 0;
}
sub dump
{
my $indent = shift // 0;
for my $offset (sort {$a <=> $b} keys %offset2entry)
{
my $leading = " " x $indent ;
say $leading . "\nOffset $offset" ;
say Dumper($offset2entry{$offset})
}
}
sub add
{
my $entry = shift;
getEnclosingEntry($entry);
push @nestingStack, $entry;
$index2entry{ $entry->index } = $entry;
$offset2entry{ $entry->offsetStart } = $entry;
}
sub getEnclosingEntry
{
my $entry = shift;
my $filename = $entry->filename;
pop @nestingStack
while @nestingStack && $entry->offsetStart > $nestingStack[-1]->offsetEnd ;
my $match = undef;
if (@nestingStack &&
$entry->offsetStart >= $nestingStack[-1]->offsetStart &&
$entry->offsetEnd <= $nestingStack[-1]->offsetEnd &&
$entry->index != $nestingStack[-1]->index)
{
# Nested entry found
$match = $nestingStack[-1];
push @{ $encapsulations{ $match->index } }, $entry;
$inner2outer{ $entry->index} = $match->index;
++ $encapsulationCount;
$entry->encapsulated(1) ;
$match->increment_childrenCount();
if ($NESTING_DEBUG)
{
say "#### nesting " . (caller(1))[3] . " index #" . $entry->index . ' "' .
$entry->outputFilename . '" [' . $entry->offsetStart . "->" . $entry->offsetEnd . "]" .
" in #" . $match->index . ' "' .
$match->outputFilename . '" [' . $match->offsetStart . "->" . $match->offsetEnd . "]" ;
}
}
return $match;
}
sub isNested
{
my $offsetStart = shift;
my $offsetEnd = shift;
if ($NESTING_DEBUG)
{
say "### Want: offsetStart " . ::decimalHex0x($offsetStart) . " offsetEnd " . ::decimalHex0x($offsetEnd);
for my $entry (@nestingStack)
{
say "### Have: offsetStart " . ::decimalHex0x($entry->offsetStart) . " offsetEnd " . ::decimalHex0x($entry->offsetEnd);
}
}
return 0
unless @nestingStack ;
my @copy = @nestingStack ;
pop @copy
while @copy && $offsetStart > $copy[-1]->offsetEnd ;
return @copy &&
$offsetStart >= $copy[-1]->offsetStart &&
$offsetEnd <= $copy[-1]->offsetEnd ;
}
sub getOuterEncapsulation
{
my $entry = shift;
my $outerIndex = $inner2outer{ $entry->index } ;
return undef
if ! defined $outerIndex ;
return $index2entry{$outerIndex} // undef;
}
sub getEncapsulations
{
my $entry = shift;
return $encapsulations{ $entry->index } ;
}
sub getFirstEncapsulation
{
my $entry = shift;
my $got = $encapsulations{ $entry->index } ;
return defined $got ? $$got[0] : undef;
}
sub encapsulations
{
return \%encapsulations;
}
sub encapsulationCount
{
return $encapsulationCount;
}
sub childrenInCentralDir
{
# find local header entries that have children that are not referenced in the CD
# tis means it is likely a benign nextd zip file
my $entry = shift;
for my $child (@{ $encapsulations{$entry->index} } )
{
next
unless $child->entryType == ::ZIP_LOCAL_HDR_SIG ;
return 1
if @{ $child->cdEntryList };
}
return 0;
}
sub entryByIndex
{
my $index = shift;
return $index2entry{$index};
}
sub getEntryByOffset
{
my $offset = shift;
return $offset2entry{$offset};
}
sub getLdEntryByOffset
{
my $offset = shift;
my $entry = $offset2entry{$offset};
return $entry
if $entry && $entry->entryType == ::ZIP_LOCAL_HDR_SIG;
return undef;
}
sub getEntriesByOffset
{
return \%offset2entry ;
}
}
{
package SimpleTable ;
use List::Util qw(max sum);
sub new
{
my $class = shift;
my %object = (
header => [],
data => [],
columns => 0,
prefix => '# ',
);
bless \%object, $class;
}
sub addHeaderRow
{
my $self = shift;
push @{ $self->{header} }, [ @_ ] ;
$self->{columns} = max($self->{columns}, scalar @_ ) ;
}
sub addDataRow
{
my $self = shift;
push @{ $self->{data} }, [ @_ ] ;
$self->{columns} = max($self->{columns}, scalar @_ ) ;
}
sub hasData
{
my $self = shift;
return scalar @{ $self->{data} } ;
}
sub display
{
my $self = shift;
# work out the column widths
my @colW = (0) x $self->{columns} ;
for my $row (@{ $self->{data} }, @{ $self->{header} })
{
my @r = @$row;
for my $ix (0 .. $self->{columns} -1)
{
$colW[$ix] = max($colW[$ix],
3 + length( $r[$ix] )
);
}
}
my $width = sum(@colW) ; #+ @colW ;
my @template ;
for my $w (@colW)
{
push @template, ' ' x ($w - 3);
}
print $self->{prefix} . '-' x ($width + 1) . "\n";
for my $row (@{ $self->{header} })
{
my @outputRow = @template;
print $self->{prefix} . '| ';
for my $ix (0 .. $self->{columns} -1)
{
my $field = $template[$ix] ;
substr($field, 0, length($row->[$ix]), $row->[$ix]);
print $field . ' | ';
}
print "\n";
}
print $self->{prefix} . '-' x ($width + 1) . "\n";
for my $row (@{ $self->{data} })
{
my @outputRow = @template;
print $self->{prefix} . '| ';
for my $ix (0 .. $self->{columns} -1)
{
my $field = $template[$ix] ;
substr($field, 0, length($row->[$ix]), $row->[$ix]);
print $field . ' | ';
}
print "\n";
}
print $self->{prefix} . '-' x ($width + 1) . "\n";
print "#\n";
}
}
sub Usage
{
my $enc = TextEncoding::getNativeLocaleName();
my $message = <<EOM;
zipdetails [OPTIONS] file
Display details about the internal structure of a Zip file.
OPTIONS
General Options
-h, --help
Display help
--redact
Hide filename and payload data in the output
--scan
Enable pessimistic scanning mode.
Blindly scan the file looking for zip headers
Expect false-positives.
--utc
Display date/time fields in UTC. Default is local time
-v
Enable verbose mode -- output more stuff
--version
Print zipdetails version number
This is version $VERSION
--walk
Enable optimistic scanning mode.
Blindly scan the file looking for zip headers
Expect false-positives.
Filename/Comment Encoding
--encoding e
Use encoding "e" when reading filename/comments from the zip file
Uses system encoding ('$enc') by default
--no-encoding
Disable filename & comment encoding. Default disabled.
--output-encoding e
Use encoding "e" when writing filename/comments to the display
Uses system encoding ('$enc') by default
--debug-encoding
Display eatra info when a filename/comment encoding has changed
--language-encoding, --no-language-encoding
Enable/disable support for the zip file "Language Encoding" flag.
When this flag is set in a zip file the filename/comment is assumed
to be encoded in UTF8.
Default is enabled
Message Control
--messages, --no-messages
Enable/disable all info/warning/error messages. Default enabled.
--exit-bitmask, --no-exit-bitmask
Enable/disable exit status bitmask for messages. Default disabled.
Bitmask values are
Info 1
Warning 2
Error 4
Copyright (c) 2011-2024 Paul Marquess. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
EOM
if (@_)
{
warn "$_\n"
for @_ ;
warn "\n";
die $message ;
}
print $message ;
exit 0;
}
1;
__END__
=head1 NAME
zipdetails - display the internal structure of zip files
=head1 SYNOPSIS
zipdetails [options] zipfile.zip
=head1 DESCRIPTION
This program creates a detailed report on the internal structure of zip
files. For each item of metadata within a zip file the program will output
=over 5
=item the offset into the zip file where the item is located.
=item a textual representation for the item.
=item an optional hex dump of the item.
=back
The program assumes a prior understanding of the internal structure of Zip
files. You should have a copy of the zip file definition,
L<APPNOTE.TXT|https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT>,
at hand to help understand the output from this program.
=head2 Default Behaviour
By default the program expects to be given a well-formed zip file. It will
navigate the zip file by first parsing the zip C<Central Directory> at the end
of the file. If the C<Central Directory> is found, it will then walk
sequentally through the zip records starting at the beginning of the file.
See L<Advanced Analysis> for other processing options.
If the program finds any structural or portability issues with the zip file
it will print a message at the point it finds the issue and/or in a summary
at the end of the output report. Whilst the set of issues that can be
detected it exhaustive, don't assume that this program can find I<all> the
possible issues in a zip file - there are likely edge conditions that need
to be addressed.
If you have suggestions for use-cases where this could be enhanced please
consider creating an enhancement request (see L<"SUPPORT">).
=head3 Date & Time fields
Date/time fields found in zip files are displayed in local time. Use the
C<--utc> option to display these fields in Coordinated Universal Time (UTC).
=head3 Filenames & Comments
Filenames and comments are decoded/encoded using the default system
encoding of the host running C<zipdetails>. When the sytem encoding cannot
be determined C<cp437> will be used.
The exceptions are
=over 5
=item *
when the C<Language Encoding Flag> is set in the zip file, the
filename/comment fields are assumed to be encoded in UTF-8.
=item *
the definition for the metadata field implies UTF-8 charset encoding
=back
See L<"Filename Encoding Issues"> and L<Filename & Comment Encoding
Options> for ways to control the encoding of filename/comment fields.
=head2 OPTIONS
=head3 General Options
=over 5
=item C<-h>, C<--help>
Display help
=item C<--redact>
Obscure filenames and payload data in the output. Handy for the use case
where the zip files contains sensitive data that cannot be shared.
=item C<--scan>
Pessimistically scan the zip file loking for possible zip records. Can be
error-prone. For very large zip files this option is slow. Consider using
the C<--walk> option first. See L<"Advanced Analysis Options">
=item C<--utc>
By default, date/time fields are displayed in local time. Use this option to
display them in in Coordinated Universal Time (UTC).
=item C<-v>
Enable Verbose mode. See L<"Verbose Output">.
=item C<--version>
Display version number of the program and exit.
=item C<--walk>
Optimistically walk the zip file looking for possible zip records.
See L<"Advanced Analysis Options">
=back
=head3 Filename & Comment Encoding Options
See L<"Filename Encoding Issues">
=over 5
=item C<--encoding name>
Use encoding "name" when reading filenames/comments from the zip file.
When this option is not specified the default the system encoding is used.
=item C< --no-encoding>
Disable all filename & comment encoding/decoding. Filenames/comments are
processed as byte streams.
This option is not enabled by default.
=item C<--output-encoding name>
Use encoding "name" when writing filename/comments to the display. By
default the system encoding will be used.
=item C<--language-encoding>, C<--no-language-encoding>
Modern zip files set a metadata entry in zip files, called the "Language
encoding flag", when they write filenames/comments encoded in UTF-8.
Occasionally some applications set the C<Language Encoding Flag> but write
data that is not UTF-8 in the filename/comment fields of the zip file. This
will usually result in garbled text being output for the
filenames/comments.
To deal with this use-case, set the C<--no-language-encoding> option and,
if needed, set the C<--encoding name> option to encoding actually used.
Default is C<--language-encoding>.
=item C<--debug-encoding>
Display extra debugging info when a filename/comment encoding has changed.
=back
=head3 Message Control Options
=over 5
=item C<--messages>, C<--no-messages>
Enable/disable the output of all info/warning/error messages.
Disabling messages means that no checks are carried out to check that the
zip file is well-formed.
Default is enabled.
=item C<--exit-bitmask>, C<--no-exit-bitmask>
Enable/disable exit status bitmask for messages. Default disabled.
Bitmask values are: 1 for info, 2 for warning and 4 for error.
=back
=head2 Default Output
By default C<zipdetails> will output each metadata field from the zip file
in three columns.
=over 5
=item 1
The offset, in hex, to the start of the field relative to the beginning of
the file.
=item 2
The name of the field.
=item 3
Detailed information about the contents of the field. The format depends on
the type of data:
=over 5
=item * Numeric Values
If the field contains an 8-bit, 16-bit, 32-bit or 64-bit numeric value, it
will be displayed in both hex and decimal -- for example "C<002A (42)>".
Note that Zip files store most numeric values in I<little-endian> encoding
(there area few rare instances where I<big-endian> is used). The value read
from the zip file will have the I<endian> encoding removed before being
displayed.
Next, is an optional description of what the numeric value means.
=item * String
If the field corresponds to a printable string, it will be output enclosed
in single quotes.
=item * Binary Data
The term I<Binary Data> is just a catch-all for all other metadata in the
zip file. This data is displayed as a series of ascii-hex byte values in
the same order they are stored in the zip file.
=back
=back
For example, assuming you have a zip file, C<test,zip>, with one entry
$ unzip -l test.zip
Archive: test.zip
Length Date Time Name
--------- ---------- ----- ----
446 2023-03-22 20:03 lorem.txt
--------- -------
446 1 file
Running C<zipdetails> will gives this output
$ zipdetails test.zip
0000 LOCAL HEADER #1 04034B50 (67324752)
0004 Extract Zip Spec 14 (20) '2.0'
0005 Extract OS 00 (0) 'MS-DOS'
0006 General Purpose Flag 0000 (0)
[Bits 1-2] 0 'Normal Compression'
0008 Compression Method 0008 (8) 'Deflated'
000A Modification Time 5676A072 (1450614898) 'Wed Mar 22 20:03:36 2023'
000E CRC F90EE7FF (4178503679)
0012 Compressed Size 0000010E (270)
0016 Uncompressed Size 000001BE (446)
001A Filename Length 0009 (9)
001C Extra Length 0000 (0)
001E Filename 'lorem.txt'
0027 PAYLOAD
0135 CENTRAL HEADER #1 02014B50 (33639248)
0139 Created Zip Spec 1E (30) '3.0'
013A Created OS 03 (3) 'Unix'
013B Extract Zip Spec 14 (20) '2.0'
013C Extract OS 00 (0) 'MS-DOS'
013D General Purpose Flag 0000 (0)
[Bits 1-2] 0 'Normal Compression'
013F Compression Method 0008 (8) 'Deflated'
0141 Modification Time 5676A072 (1450614898) 'Wed Mar 22 20:03:36 2023'
0145 CRC F90EE7FF (4178503679)
0149 Compressed Size 0000010E (270)
014D Uncompressed Size 000001BE (446)
0151 Filename Length 0009 (9)
0153 Extra Length 0000 (0)
0155 Comment Length 0000 (0)
0157 Disk Start 0000 (0)
0159 Int File Attributes 0001 (1)
[Bit 0] 1 'Text Data'
015B Ext File Attributes 81ED0000 (2179792896)
[Bits 16-24] 01ED (493) 'Unix attrib: rwxr-xr-x'
[Bits 28-31] 08 (8) 'Regular File'
015F Local Header Offset 00000000 (0)
0163 Filename 'lorem.txt'
016C END CENTRAL HEADER 06054B50 (101010256)
0170 Number of this disk 0000 (0)
0172 Central Dir Disk no 0000 (0)
0174 Entries in this disk 0001 (1)
0176 Total Entries 0001 (1)
0178 Size of Central Dir 00000037 (55)
017C Offset to Central Dir 00000135 (309)
0180 Comment Length 0000 (0)
#
# Done
=head2 Verbose Output
If the C<-v> option is present, the metadata output is split into the
following columns:
=over 5
=item 1
The offset, in hex, to the start of the field relative to the beginning of
the file.
=item 2
The offset, in hex, to the end of the field relative to the beginning of
the file.
=item 3
The length, in hex, of the field.
=item 4
A hex dump of the bytes in field in the order they are stored in the zip file.
=item 5
A textual description of the field.
=item 6
Information about the contents of the field. See the description in the
L<Default Output> for more details.
=back
Here is the same zip file, C<test.zip>, dumped using the C<zipdetails>
C<-v> option:
$ zipdetails -v test.zip
0000 0003 0004 50 4B 03 04 LOCAL HEADER #1 04034B50 (67324752)
0004 0004 0001 14 Extract Zip Spec 14 (20) '2.0'
0005 0005 0001 00 Extract OS 00 (0) 'MS-DOS'
0006 0007 0002 00 00 General Purpose Flag 0000 (0)
[Bits 1-2] 0 'Normal Compression'
0008 0009 0002 08 00 Compression Method 0008 (8) 'Deflated'
000A 000D 0004 72 A0 76 56 Modification Time 5676A072 (1450614898) 'Wed Mar 22 20:03:36 2023'
000E 0011 0004 FF E7 0E F9 CRC F90EE7FF (4178503679)
0012 0015 0004 0E 01 00 00 Compressed Size 0000010E (270)
0016 0019 0004 BE 01 00 00 Uncompressed Size 000001BE (446)
001A 001B 0002 09 00 Filename Length 0009 (9)
001C 001D 0002 00 00 Extra Length 0000 (0)
001E 0026 0009 6C 6F 72 65 Filename 'lorem.txt'
6D 2E 74 78
74
0027 0134 010E ... PAYLOAD
0135 0138 0004 50 4B 01 02 CENTRAL HEADER #1 02014B50 (33639248)
0139 0139 0001 1E Created Zip Spec 1E (30) '3.0'
013A 013A 0001 03 Created OS 03 (3) 'Unix'
013B 013B 0001 14 Extract Zip Spec 14 (20) '2.0'
013C 013C 0001 00 Extract OS 00 (0) 'MS-DOS'
013D 013E 0002 00 00 General Purpose Flag 0000 (0)
[Bits 1-2] 0 'Normal Compression'
013F 0140 0002 08 00 Compression Method 0008 (8) 'Deflated'
0141 0144 0004 72 A0 76 56 Modification Time 5676A072 (1450614898) 'Wed Mar 22 20:03:36 2023'
0145 0148 0004 FF E7 0E F9 CRC F90EE7FF (4178503679)
0149 014C 0004 0E 01 00 00 Compressed Size 0000010E (270)
014D 0150 0004 BE 01 00 00 Uncompressed Size 000001BE (446)
0151 0152 0002 09 00 Filename Length 0009 (9)
0153 0154 0002 00 00 Extra Length 0000 (0)
0155 0156 0002 00 00 Comment Length 0000 (0)
0157 0158 0002 00 00 Disk Start 0000 (0)
0159 015A 0002 01 00 Int File Attributes 0001 (1)
[Bit 0] 1 'Text Data'
015B 015E 0004 00 00 ED 81 Ext File Attributes 81ED0000 (2179792896)
[Bits 16-24] 01ED (493) 'Unix attrib: rwxr-xr-x'
[Bits 28-31] 08 (8) 'Regular File'
015F 0162 0004 00 00 00 00 Local Header Offset 00000000 (0)
0163 016B 0009 6C 6F 72 65 Filename 'lorem.txt'
6D 2E 74 78
74
016C 016F 0004 50 4B 05 06 END CENTRAL HEADER 06054B50 (101010256)
0170 0171 0002 00 00 Number of this disk 0000 (0)
0172 0173 0002 00 00 Central Dir Disk no 0000 (0)
0174 0175 0002 01 00 Entries in this disk 0001 (1)
0176 0177 0002 01 00 Total Entries 0001 (1)
0178 017B 0004 37 00 00 00 Size of Central Dir 00000037 (55)
017C 017F 0004 35 01 00 00 Offset to Central Dir 00000135 (309)
0180 0181 0002 00 00 Comment Length 0000 (0)
#
# Done
=head2 Advanced Analysis
If you have a corrupt or non-standard zip file, particulatly one where the
C<Central Directory> metadata at the end of the file is absent/incomplete, you
can use either the C<--walk> option or the C<--scan> option to search for
any zip metadata that is still present in the file.
When either of these options is enabled, this program will bypass the
initial step of reading the C<Central Directory> at the end of the file and
simply scan the zip file sequentially from the start of the file looking
for zip metedata records. Although this can be error prone, for the most
part it will find any zip file metadata that is still present in the file.
The difference between the two options is how aggressive the sequential
scan is: C<--walk> is optimistic, while C<--scan> is pessimistic.
To understand the difference in more detail you need to know a bit about
how zip file metadata is structured. Under the hood, a zip file uses a
series of 4-byte signatures to flag the start of a each of the metadata
records it uses. When the C<--walk> or the C<--scan> option is enabled both
work identically by scanning the file from the beginning looking for any
the of these valid 4-byte metadata signatures. When a 4-byte signature is
found both options will blindly assume that it has found a vald metadata
record and display it.
=head3 C<--walk>
The C<--walk> option optimistically assumes that it has found a real zip
metatada record and so starts the scan for the next record directly after
the record it has just output.
=head3 C<--scan>
The C<--scan> option is pessimistic and assumes the 4-byte signature
sequence may have been a false-positive, so before starting the scan for
the next resord, it will rewind to the location in the file directly after
the 4-byte sequecce it just processed. This means it will rescan data that
has already been processed. For very lage zip files the C<--scan> option
can be really realy slow, so trying the C<--walk> option first.
B<Important Note>: If the zip file being processed contains one or more
nested zip files, and the outer zip file uses the C<STORE> compression
method, the C<--scan> option will display the zip metadata for both the
outer & inner zip files.
=head2 Filename Encoding Issues
Sometimes when displaying the contents of a zip file the filenames (or
comments) appear to be garbled. This section walks through the reasons and
mitigations that can be applied to work around these issues.
=head3 Background
When zip files were first created in the 1980's, there was no Unicode or
UTF-8. Issues around character set encoding interoperability were not a
major concern.
Initially, the only official encoding supported in zip files was IBM Code
Page 437 (AKA C<CP437>). As time went on users in locales where C<CP437>
wasn't appropriate stored filenames in the encoding native to their locale.
If you were running a system that matched the locale of the zip file, all
was well. If not, you had to post-process the filenames after unzipping the
zip file.
Fast forward to the introduction of Unicode and UTF-8 encoding. The
approach now used by all major zip implementations is to set the C<Language
encoding flag> (also known as C<EFS>) in the zip file metadata to signal
that a filename/comment is encoded in UTF-8.
To ensure maximum interoperability when sharing zip files store 7-bit
filenames as-is in the zip file. For anything else the C<EFS> bit needs to
be set and the filename is encoded in UTF-8. Although this rule is kept to
for the most part, there are exceptions out in the wild.
=head3 Dealing with Encoding Errors
The most common filename encoding issue is where the C<EFS> bit is not set and
the filename is stored in a character set that doesnt't match the system
encoding. This mostly impacts legacy zip files that predate the
introduction of Unicode.
To deal with this issue you first need to know what encoding was used in
the zip file. For example, if the filename is encoded in C<ISO-8859-1> you
can display the filenames using the C<--encoding> option
zipdetails --encoding ISO-8859-1 myfile.zip
A less common variation of this is where the C<EFS> bit is set, signalling
that the filename will be encoded in UTF-8, but the filename is not encoded
in UTF-8. To deal with this scenarion, use the C<--no-language-encoding>
option along with the C<--encoding> option.
=head1 LIMITATIONS
The following zip file features are not supported by this program:
=over 5
=item *
Multi-part/Split/Spanned Zip Archives.
This program cannot give an overall report on the combined parts of a
multi-part zip file.
The best you can do is run with either the C<--scan> or C<--walk> options
against individual parts. Some will contains zipfile metadata which will be
detected and some will only contain compressed payload data.
=item *
Encrypted Central Directory
When pkzip I<Strong Encryption> is enabled in a zip file this program can
still parse most of the metadata in the zip file. The exception is when the
C<Central Directory> of a zip file is also encrypted. This program cannot
parse any metadata from an encrypted C<Central Directory>.
=item *
Corrupt Zip files
When C<zipdetails> encounters a corrupt zip file, it will do one or more of
the following
=over 5
=item *
Display details of the corruption and carry on
=item *
Display details of the corruption and terminate
=item *
Terminate with a generic message
=back
Which of the above is output is dependent in the severity of the
corruption.
=back
=head1 TODO
=head2 JSON/YML Output
Output some of the zip file metadata as a JSON or YML document.
=head2 Corrupt Zip files
Although the detection and reporting of most of the common corruption use-cases is
present in C<zipdetails>, there are likely to be other edge cases that need
to be supported.
If you have a corrupt Zip file that isn't being processed properly, please
report it (see L<"SUPPORT">).
=head1 SUPPORT
General feedback/questions/bug reports should be sent to
L<https://github.com/pmqs/zipdetails/issues>.
=head1 SEE ALSO
The primary reference for Zip files is
L<APPNOTE.TXT|https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT>.
An alternative reference is the Info-Zip appnote. This is available from
L<ftp://ftp.info-zip.org/pub/infozip/doc/>
For details of WinZip AES encryption see L<AES Encryption Information:
Encryption Specification AE-1 and
AE-2|https://www.winzip.com/en/support/aes-encryption/>.
The C<zipinfo> program that comes with the info-zip distribution
(L<http://www.info-zip.org/>) can also display details of the structure of a zip
file.
=head1 AUTHOR
Paul Marquess F<pmqs@cpan.org>.
=head1 COPYRIGHT
Copyright (c) 2011-2024 Paul Marquess. All rights reserved.
This program is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.
|