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
//! Describes a `zip` archive
use std::any::Any;
use std::fmt::Write;
use std::fs::File;
use std::io::Cursor;
use std::path::Path;
use std::sync::Arc;
use ahash::AHashSet;
use cms::signed_data::{SignerIdentifier, SignerInfo};
use flate2::{Decompress, FlushDecompress, Status};
use log::warn;
use md5::{Digest, Md5};
use memchr::memmem;
use sha1::Sha1;
use sha2::Sha256;
use winnow::binary::{le_u32, le_u64, length_take};
use winnow::combinator::repeat;
use winnow::error::ContextError;
use winnow::prelude::*;
use winnow::token::take;
use x509_cert::Certificate;
use x509_cert::der::oid::db::DB;
use x509_cert::der::{Decode, Encode};
use x509_cert::name::Name;
use crate::anomaly::ZipAnomaly;
use crate::signature::{CertificateInfo, Signature};
use crate::source::Source;
use crate::structs::{
CentralDirectory, CentralDirectoryEntry, EndOfCentralDirectory, LocalFileHeader,
Zip64EndOfCentralDirectory,
};
use crate::{CertificateError, FileCompressionType, ReadSeek, ZipError, ber, name};
/// Maximum allowed uncompressed size for a file entry.
const MAX_UNCOMPRESSED_SIZE: usize = u32::MAX as usize;
/// Caps the self-healing forward scan so a corrupt archive can't degrade to a quadratic scan.
const SELF_HEAL_MAX_SCAN: usize = 1 << 20;
/// How far back from a claimed offset to search; corrupt offsets shift by a few bytes.
const SELF_HEAL_BACKWARD: usize = 1 << 16;
/// Window size for the backward EOCD signature search from the end of the stream.
const EOCD_SEARCH_WINDOW: usize = 4096;
/// Fixed part of a local file header: `4 (magic) + 26 (fields)`.
const LOCAL_HEADER_FIXED_LEN: usize = 30;
/// Reach of one read when scanning local headers in [`ZipEntry::anomalies`]:
/// covers the headers of many small neighbouring entries at once.
const HEADER_WINDOW: usize = 64 * 1024;
/// Room for the extra field of a local header, read along with it: zipalign
/// pads by a few bytes. A longer one is read separately.
const HEADER_SLACK: usize = 64;
/// A buffered span of the source, for [`ZipEntry::local_headers`].
#[derive(Default)]
struct Window {
start: usize,
data: Vec<u8>,
}
impl Window {
/// Whether `len` bytes at `offset` are in the window.
fn covers(&self, offset: usize, len: usize) -> bool {
offset >= self.start && offset + len <= self.start + self.data.len()
}
/// The window from `offset` on.
fn at(&self, offset: usize) -> Option<&[u8]> {
self.data.get(offset.checked_sub(self.start)?..)
}
/// Reads up to `len` bytes at `offset`, fewer at the end of the source;
/// empty past it.
fn fill(&mut self, zip: &ZipEntry, offset: usize, len: usize) {
let len = len.min(zip.source.len().saturating_sub(offset));
self.start = offset;
// one buffer for the whole scan: a fresh allocation per read costs
// more than the read
self.data.resize(len, 0);
if zip.source.read_exact_at(offset, &mut self.data).is_err() {
self.data.clear();
}
}
}
/// Upper bound for the APK Signing Block region read out of the source.
///
/// Real signing blocks are at most a few megabytes (certificates plus verity
/// padding to a 4096 multiple); anything larger is malformed data that must
/// not be pulled into memory.
const MAX_SIGNING_BLOCK_SIZE: usize = 64 * 1024 * 1024;
/// Represents a parsed ZIP archive.
///
/// Reads lazily from a seekable source: only the central directory is kept
/// in memory; local file headers and entry data are fetched on demand.
pub struct ZipEntry {
/// Lazily-read backing source.
source: Source,
/// Absolute offset of the central directory.
central_dir_offset: usize,
/// Central directory structure
central_directory: CentralDirectory,
}
impl std::fmt::Debug for ZipEntry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ZipEntry")
.field("len", &self.source.len())
.field("central_dir_offset", &self.central_dir_offset)
.field("entries", &self.central_directory.ordered_names.len())
.finish_non_exhaustive()
}
}
/// Metadata of a single archive entry, without reading its data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EntryInfo {
/// Compression method declared in the central directory
/// ([`ZipEntry::METHOD_STORED`], [`ZipEntry::METHOD_DEFLATED`], or another value in tampered archives)
pub compression_method: u16,
/// Compressed size, in bytes
pub compressed_size: u64,
/// Uncompressed size, in bytes
pub uncompressed_size: u64,
/// The local header's compression method disagrees with the central directory's
pub tampered: bool,
}
/// Largest expansion of DEFLATE: a 258-byte match coded in about 2 bits.
const MAX_DEFLATE_RATIO: usize = 1032;
/// Output of [`inflate`].
struct Inflated {
data: Vec<u8>,
/// The stream reached its end marker.
complete: bool,
/// Compressed bytes consumed.
consumed: usize,
}
/// Inflates raw DEFLATE data without trusting the declared size.
///
/// The buffer starts at the declared size, capped by what the input can
/// expand to, so an honest entry is inflated in one pass with no reallocation
/// while a lying one can't make it allocate gigabytes up front. It then grows
/// until the end of the stream, up to [`MAX_UNCOMPRESSED_SIZE`].
fn inflate(compressed: &[u8], declared: usize) -> Result<Inflated, ZipError> {
let capacity = declared
.min(compressed.len().saturating_mul(MAX_DEFLATE_RATIO))
.min(MAX_UNCOMPRESSED_SIZE);
let mut data = Vec::with_capacity(capacity);
let mut decompress = Decompress::new(false);
let complete = loop {
let consumed = decompress.total_in() as usize;
let produced = data.len();
let status = decompress
.decompress_vec(&compressed[consumed..], &mut data, FlushDecompress::Finish)
.map_err(|_| ZipError::DecompressionError)?;
if status == Status::StreamEnd {
break true;
}
if data.len() == data.capacity() {
if data.len() >= MAX_UNCOMPRESSED_SIZE {
return Err(ZipError::FileTooLarge);
}
let grow = data
.len()
.max(64 * 1024)
.min(MAX_UNCOMPRESSED_SIZE - data.len());
data.reserve_exact(grow);
continue;
}
// room left but no progress: the input ended before the stream did
if decompress.total_in() as usize == consumed && data.len() == produced {
break false;
}
};
Ok(Inflated {
data,
complete,
consumed: decompress.total_in() as usize,
})
}
/// Implementation of basic methods
impl ZipEntry {
/// Compression method `0`: uncompressed entry data.
///
/// See: <https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT> (4.4.5)
pub const METHOD_STORED: u16 = 0;
/// Compression method `8`: Deflate-compressed entry data.
///
/// See: <https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT> (4.4.5)
pub const METHOD_DEFLATED: u16 = 8;
/// General purpose flag bit `0`: the entry is encrypted.
///
/// See: <https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT> (4.4.4)
const FLAG_ENCRYPTED: u16 = 1;
/// Parses the local file header at `offset`, reading it lazily from the source.
///
/// Two bounded reads: the fixed part first (to learn the name and extra
/// field lengths), then the variable part. The entry data offset is
/// always computed from the local header's own lengths, which may
/// legitimately differ from the central directory copy.
fn read_local_header_at(&self, offset: usize) -> Result<LocalFileHeader, ZipError> {
let mut fixed = [0u8; LOCAL_HEADER_FIXED_LEN];
self.source.read_exact_at(offset, &mut fixed)?;
// name and extra lengths live at the tail of the fixed part
let name_len = u16::from_le_bytes([fixed[26], fixed[27]]) as usize;
let extra_len = u16::from_le_bytes([fixed[28], fixed[29]]) as usize;
// one buffer: the fixed part, with the variable part read into its tail
let total = LOCAL_HEADER_FIXED_LEN + name_len + extra_len;
let mut raw = Vec::with_capacity(total);
raw.extend_from_slice(&fixed);
raw.resize(total, 0);
self.source.read_exact_at(
offset + LOCAL_HEADER_FIXED_LEN,
&mut raw[LOCAL_HEADER_FIXED_LEN..],
)?;
let mut header = LocalFileHeader::parse(&raw, 0).map_err(|_| ZipError::ParseError)?;
// `parse` sees only the freshly-read slice, so patch in the real stream offset
header.offset = offset;
Ok(header)
}
/// Parses the entry's local file header: the claimed offset when it hosts
/// a header with a matching filename, otherwise the self-healing scan.
fn read_local_header_verified(
&self,
entry: &CentralDirectoryEntry,
) -> Result<LocalFileHeader, ZipError> {
// an offset past usize can't be read; the scan below then finds nothing
let claim = usize::try_from(entry.local_header_offset).unwrap_or(usize::MAX);
let expected_name = entry
.raw_file_name
.as_deref()
.unwrap_or(entry.file_name.as_bytes());
if let Ok(header) = self.read_local_header_at(claim)
&& header.file_name.as_ref() == expected_name
{
return Ok(header);
}
let offset = self
.find_local_header_offset(claim, expected_name)
.ok_or(ZipError::FileNotFound)?;
self.read_local_header_at(offset)
.map_err(|_| ZipError::FileNotFound)
}
/// Recovers the real local file header offset for an entry whose
/// `local_header_offset` is corrupt: scans a bounded, filename-verified
/// window for a matching `PK\x03\x04`.
///
/// Skips the claimed offset; the caller has already tried it.
fn find_local_header_offset(&self, claim: usize, expected_name: &[u8]) -> Option<usize> {
// bounded scan for a matching local header, verified by filename.
let start = claim.saturating_sub(SELF_HEAL_BACKWARD);
let end = self
.source
.len()
.min(self.central_dir_offset)
.min(claim.saturating_add(SELF_HEAL_MAX_SCAN));
if end <= start {
return None;
}
// read the scan window once, then walk it
let window = self.source.read_bytes_at(start, end - start).ok()?;
let mut pos = 0;
while let Some(rel) = memmem::find(&window[pos..], b"PK\x03\x04") {
let candidate = start + pos + rel;
if candidate != claim
&& let Ok(header) = self.read_local_header_at(candidate)
&& header.file_name.as_ref() == expected_name
{
return Some(candidate);
}
pos += rel + 1;
}
None
}
/// Creates a new `ZipEntry` from raw in-memory ZIP data.
///
/// Wraps the bytes in a [`Cursor`] and delegates to [`ZipEntry::from_reader`],
/// so in-memory and file-backed archives share the same lazy reading path.
///
/// # Errors
///
/// Returns a [ZipError] if:
/// - The input does not start with a valid ZIP signature [ZipError::InvalidHeader];
/// - The End of Central Directory cannot be found [ZipError::NotFoundEOCD];
/// - Parsing of the EOCD or central directory fails [ZipError::ParseError].
///
/// # Examples
///
/// ```no_run
/// # use apk_info_zip::{ZipEntry, ZipError};
/// let data = std::fs::read("archive.zip").unwrap();
/// let zip = ZipEntry::new(data).expect("failed to parse ZIP archive");
/// ```
pub fn new(input: Vec<u8>) -> Result<ZipEntry, ZipError> {
Self::from_reader(Cursor::new(input))
}
/// Creates a new `ZipEntry` that lazily reads a ZIP archive from any
/// seekable source, for example a [`std::fs::File`]. Only the central
/// directory is loaded into memory.
///
/// # Errors
///
/// Returns a [ZipError] if:
/// - The stream is too short or does not start with a valid ZIP signature [ZipError::InvalidHeader];
/// - The End of Central Directory cannot be found [ZipError::NotFoundEOCD];
/// - Parsing of the EOCD or central directory fails [ZipError::ParseError].
///
/// # Examples
///
/// ```no_run
/// # use apk_info_zip::{ZipEntry, ZipError};
/// let file = std::fs::File::open("app.apk").unwrap();
/// let zip = ZipEntry::from_reader(file).expect("failed to parse ZIP archive");
/// ```
pub fn from_reader(reader: impl ReadSeek + 'static) -> Result<ZipEntry, ZipError> {
// a file gets positional reads, no seek before every read
let mut reader = Some(reader);
if let Some(file) = (&mut reader as &mut dyn Any).downcast_mut::<Option<File>>()
&& let Some(file) = file.take()
{
return Self::parse(Source::from_file(file)?);
}
let Some(reader) = reader else {
unreachable!("the reader is taken only when it is a file");
};
Self::parse(Source::new(Box::new(reader))?)
}
/// Opens a file on disk and parses it lazily; the file is never fully
/// read into memory.
///
/// # Errors
///
/// Returns a [ZipError] if the file cannot be opened
/// ([ZipError::IoError]), or anything [`ZipEntry::from_reader`] reports.
///
/// # Examples
///
/// ```no_run
/// # use apk_info_zip::{ZipEntry, ZipError};
/// let zip = ZipEntry::open("app.apk").expect("failed to parse ZIP archive");
/// ```
pub fn open<P: AsRef<Path>>(path: P) -> Result<ZipEntry, ZipError> {
let file = std::fs::File::open(path)?;
Self::from_reader(file)
}
fn parse(source: Source) -> Result<ZipEntry, ZipError> {
// perform basic sanity check
let mut magic = [0u8; 4];
source.read_exact_at(0, &mut magic)?;
if magic != *b"PK\x03\x04" {
return Err(ZipError::InvalidHeader);
}
let (eocd_offset, decoy_eocd) =
Self::find_eocd_offset(&source).ok_or(ZipError::NotFoundEOCD)?;
// the EOCD record plus up to a maximum-size archive comment
let eocd_len = (source.len() - eocd_offset).min(22 + u16::MAX as usize);
let eocd_bytes = source.read_bytes_at(eocd_offset, eocd_len)?;
let eocd =
EndOfCentralDirectory::parse(&mut &eocd_bytes[..]).map_err(|_| ZipError::ParseError)?;
// ZIP64: the 64-bit values replace the EOCD fields saturated at their
// maximum, and the CD ends where the ZIP64 record starts
let zip64 = Self::read_zip64_eocd(&source, eocd_offset);
let wide =
|narrow: u64, max: u64, wide: fn(&Zip64EndOfCentralDirectory) -> u64| match &zip64 {
Some((_, record)) if narrow == max => wide(record),
_ => narrow,
};
let total_entries = wide(eocd.total_entries.into(), u16::MAX.into(), |r| {
r.total_entries
});
let central_dir_size = wide(eocd.central_dir_size.into(), u32::MAX.into(), |r| {
r.central_dir_size
});
let central_dir_offset = wide(eocd.central_dir_offset.into(), u32::MAX.into(), |r| {
r.central_dir_offset
});
let cd_end = zip64.as_ref().map_or(eocd_offset, |(offset, _)| *offset);
// Prefer the EOCD's declared CD offset;
// derive it (`eocd - cd_size`) only when prepended/polyglot data left it stale.
let declared = usize::try_from(central_dir_offset).unwrap_or(usize::MAX);
let derived = usize::try_from(central_dir_size)
.ok()
.and_then(|size| cd_end.checked_sub(size))
.ok_or(ZipError::ParseError)?;
let mut cd_magic = [0u8; 4];
let central_dir_offset = if source
.read_exact_at(declared, &mut cd_magic)
.is_ok_and(|_| cd_magic == *b"PK\x01\x02")
{
declared
} else {
derived
};
// Read from the CD offset to EOF; `central_dir_size` can understate the
// real record area in a tampered archive. Parse at most `total_entries`
// records, like Android's loop over `num_records`, so a decoy appended
// past the count (which still installs and runs) can't shadow a real
// entry such as the manifest.
let cd_bytes =
source.read_bytes_at(central_dir_offset, source.len() - central_dir_offset)?;
let total_entries = usize::try_from(total_entries).unwrap_or(usize::MAX);
let mut central_directory = CentralDirectory::parse(&cd_bytes, 0, total_entries)
.map_err(|_| ZipError::ParseError)?;
// archive-level defects go first, before the record list ones
let mut anomalies = Vec::new();
if let Some(offset) = decoy_eocd {
anomalies.push(ZipAnomaly::FakeEocdInComment {
offset: offset as u64,
});
}
let eocd_end = eocd_offset + 22 + usize::from(eocd.comment_length);
if eocd_end != source.len() {
anomalies.push(ZipAnomaly::EocdNotAtEnd {
expected_len: eocd_end as u64,
actual_len: source.len() as u64,
});
}
if central_dir_offset != declared {
anomalies.push(ZipAnomaly::CentralDirectoryShifted {
declared: declared as u64,
actual: central_dir_offset as u64,
});
}
anomalies.append(&mut central_directory.anomalies);
central_directory.anomalies = anomalies;
Ok(ZipEntry {
source,
central_dir_offset,
central_directory,
})
}
/// Reads the ZIP64 EOCD record through the locator right before the EOCD.
///
/// Tries the offset declared in the locator, then the spot right before
/// the locator, for an archive with prepended data. Returns the record's
/// offset along with it.
fn read_zip64_eocd(
source: &Source,
eocd_offset: usize,
) -> Option<(usize, Zip64EndOfCentralDirectory)> {
let locator_offset = eocd_offset.checked_sub(Zip64EndOfCentralDirectory::LOCATOR_LEN)?;
let locator = source
.read_bytes_at(locator_offset, Zip64EndOfCentralDirectory::LOCATOR_LEN)
.ok()?;
let declared = Zip64EndOfCentralDirectory::parse_locator(&locator)?;
let derived = locator_offset.checked_sub(Zip64EndOfCentralDirectory::RECORD_LEN);
[usize::try_from(declared).ok(), derived]
.into_iter()
.flatten()
.find_map(|offset| {
let record = source
.read_bytes_at(offset, Zip64EndOfCentralDirectory::RECORD_LEN)
.ok()?;
Some((offset, Zip64EndOfCentralDirectory::parse_record(&record)?))
})
}
/// Finds the EOCD, scanning 4KB windows backward with a 3-byte overlap so a
/// signature on a window edge still matches.
///
/// Accepts a candidate only if its comment reaches the exact end of the
/// stream ([`Self::eocd_spans_to_end`]) — Android's invariant, which ignores
/// a fake `PK\x05\x06` planted in the archive comment. Falls back to the
/// rightmost match when none qualifies, so an archive with a broken comment
/// length or trailing data still parses.
///
/// Returns the offset, and the offset of a rejected signature after it,
/// the planted one, if any.
///
/// Like Android's `libziparchive`, searches only the last `22 + u16::MAX`
/// bytes, the most a comment can span. Android rejects a file whose EOCD
/// is further back (a truncated archive, one with data appended after it)
/// as "not zip", and a full scan of such a file would read all of it.
fn find_eocd_offset(source: &Source) -> Option<(usize, Option<usize>)> {
const MAGIC: &[u8; 4] = b"PK\x05\x06";
let total_len = source.len();
let search_start = total_len.saturating_sub(22 + u16::MAX as usize);
let mut fallback = None;
// one reusable window for the whole backward scan
let mut window = vec![0u8; EOCD_SEARCH_WINDOW];
let mut end = total_len;
loop {
let start = end.saturating_sub(EOCD_SEARCH_WINDOW);
let len = end - start;
source.read_exact_at(start, &mut window[..len]).ok()?;
// Walk candidate signatures in this window from the rightmost.
let mut upto = len;
while let Some(pos) = memmem::rfind(&window[..upto], MAGIC) {
let offset = start + pos;
if offset < search_start {
break;
}
if Self::eocd_spans_to_end(source, &window[..len], start, offset, total_len) {
return Some((offset, fallback));
}
// remember the first (rightmost) candidate as a lenient fallback
fallback.get_or_insert(offset);
// keep searching strictly earlier in the window
upto = pos + MAGIC.len() - 1;
}
if start <= search_start {
return fallback.map(|offset| (offset, None));
}
// step back, overlapping by 3 bytes
end = start + MAGIC.len() - 1;
}
}
/// Whether an EOCD at `offset`, plus its declared comment, ends exactly at
/// the stream's end — the mark of the real record over a comment-embedded
/// decoy. Reads `comment_length` from `window` (already read from
/// `win_start`), touching the source only when that field crosses the edge.
fn eocd_spans_to_end(
source: &Source,
window: &[u8],
win_start: usize,
offset: usize,
total_len: usize,
) -> bool {
// 22-byte fixed record; comment_length is the u16 at offset + 20
let Some(fields_end) = offset.checked_add(22) else {
return false;
};
if fields_end > total_len {
return false;
}
let rel = offset - win_start;
let comment_len = if rel + 22 <= window.len() {
u16::from_le_bytes([window[rel + 20], window[rel + 21]])
} else {
let mut buf = [0u8; 2];
if source.read_exact_at(offset + 20, &mut buf).is_err() {
return false;
}
u16::from_le_bytes(buf)
} as usize;
fields_end + comment_len == total_len
}
/// Returns an iterator over the names of all files in the ZIP archive,
/// in central directory record order.
///
/// The order comes straight from the archive, so repeated parses of the
/// same file yield the same sequence (unlike hash map iteration, which is
/// random per process).
///
/// # Examples
///
/// ```no_run
/// # use apk_info_zip::ZipEntry;
/// # let zip_data = std::fs::read("archive.zip").unwrap();
/// # let zip = ZipEntry::new(zip_data).unwrap();
/// for filename in zip.namelist() {
/// println!("{}", filename);
/// }
/// ```
pub fn namelist(&self) -> impl Iterator<Item = &str> + '_ {
self.central_directory
.ordered_names
.iter()
.map(|x| x.as_ref())
}
/// Whether the archive has an entry named `filename`, without reading it.
///
/// # Examples
///
/// ```no_run
/// # use apk_info_zip::ZipEntry;
/// # let zip = ZipEntry::open("app.xapk").unwrap();
/// if zip.contains("manifest.json") {
/// println!("looks like an xapk");
/// }
/// ```
pub fn contains(&self, filename: &str) -> bool {
self.central_directory.entries.contains_key(filename)
}
/// Returns metadata of `filename` (sizes, compression method, tamper flag)
/// without reading or decompressing its data.
///
/// The tamper flag mirrors the detection of [`ZipEntry::read`]: the entry is
/// marked tampered when its local header's compression method disagrees with
/// the central directory's.
///
/// # Examples
///
/// ```no_run
/// # use apk_info_zip::ZipEntry;
/// # let zip_data = std::fs::read("archive.zip").unwrap();
/// # let zip = ZipEntry::new(zip_data).unwrap();
/// let info = zip.entry_info("example.txt").expect("failed to get entry info");
/// println!("{} bytes, tampered: {}", info.uncompressed_size, info.tampered);
/// ```
pub fn entry_info(&self, filename: &str) -> Option<EntryInfo> {
let entry = self.central_directory.entries.get(filename)?;
// local header is read lazily; a corrupt claimed offset falls back
// to the bounded self-healing scan, and an unhealable entry is a miss
let local_method = self
.read_local_header_verified(entry)
.ok()?
.compression_method;
Some(EntryInfo {
compression_method: entry.compression_method,
compressed_size: entry.compressed_size,
uncompressed_size: entry.uncompressed_size,
tampered: local_method != entry.compression_method,
})
}
/// Inspects the archive for structural defects.
///
/// Reports what was noticed while opening the archive (the end record,
/// the central directory), then checks the local header of every entry
/// against its central directory record. The entry data is not read, so
/// the cost is one small read per entry.
///
/// # Examples
///
/// ```no_run
/// # use apk_info_zip::ZipEntry;
/// let zip = ZipEntry::open("app.apk").unwrap();
/// for anomaly in zip.anomalies() {
/// println!("{}: {anomaly}", anomaly.code());
/// }
/// ```
pub fn anomalies(&self) -> Vec<ZipAnomaly> {
let mut anomalies = self.central_directory.anomalies.clone();
let entries: Vec<(&Arc<str>, &CentralDirectoryEntry)> = self
.central_directory
.ordered_names
.iter()
.filter_map(|name| Some((name, self.central_directory.entries.get(name)?)))
.collect();
let local_headers = self.local_headers(&entries);
for ((name, entry), local) in entries.into_iter().zip(local_headers) {
let entry_name = || name.to_string();
let method = entry.compression_method;
if method != Self::METHOD_STORED && method != Self::METHOD_DEFLATED {
anomalies.push(ZipAnomaly::UnknownCompressionMethod {
entry: entry_name(),
method,
});
} else if method == Self::METHOD_STORED
&& entry.compressed_size != entry.uncompressed_size
{
anomalies.push(ZipAnomaly::StoredSizeMismatch {
entry: entry_name(),
compressed: entry.compressed_size,
uncompressed: entry.uncompressed_size,
});
}
let Some(local) = local else {
anomalies.push(ZipAnomaly::LocalHeaderMissing {
entry: entry_name(),
});
continue;
};
if local.offset as u64 != entry.local_header_offset {
anomalies.push(ZipAnomaly::LocalHeaderShifted {
entry: entry_name(),
declared: entry.local_header_offset,
actual: local.offset as u64,
});
}
if local.compression_method != method {
anomalies.push(ZipAnomaly::CompressionMethodMismatch {
entry: entry_name(),
central: method,
local: local.compression_method,
});
}
if (entry.general_purpose | local.general_purpose_bit_flag) & Self::FLAG_ENCRYPTED != 0
{
anomalies.push(ZipAnomaly::EncryptionFlag {
entry: entry_name(),
});
}
}
anomalies
}
/// Reads the local headers of `entries`, in the same order; `None` for an
/// entry whose header isn't found even by the self-healing scan.
///
/// A read is a system call, slow on some filesystems, and an apk has
/// thousands of entries. The headers are walked in file order, and one
/// read covers every header that starts within [`HEADER_WINDOW`] of the
/// first: the headers of small neighbouring entries come together, while
/// the data of a large entry is never read.
fn local_headers(
&self,
entries: &[(&Arc<str>, &CentralDirectoryEntry)],
) -> Vec<Option<LocalFileHeader>> {
// an offset past `usize` has no header to read: `None`
let mut order: Vec<(usize, usize)> = entries
.iter()
.enumerate()
.filter_map(|(i, (_, entry))| {
Some((usize::try_from(entry.local_header_offset).ok()?, i))
})
.collect();
order.sort_unstable();
let mut headers = vec![None; entries.len()];
let mut window = Window::default();
for (position, &(claim, i)) in order.iter().enumerate() {
let entry = entries[i].1;
let expected_name = entry
.raw_file_name
.as_deref()
.unwrap_or(entry.file_name.as_bytes());
if !window.covers(claim, LOCAL_HEADER_FIXED_LEN) {
// up to the end of the last header that starts within reach;
// a longer extra field is read on its own below
let span_end = order[position..]
.iter()
.take_while(|(offset, _)| offset - claim < HEADER_WINDOW)
.map(|&(offset, j)| {
offset
+ LOCAL_HEADER_FIXED_LEN
+ entries[j].1.file_name.len()
+ HEADER_SLACK
})
.max()
.unwrap_or(claim + LOCAL_HEADER_FIXED_LEN);
window.fill(self, claim, span_end - claim);
}
let header = self
.window_local_header(claim, &mut window)
.filter(|header| header.file_name.as_ref() == expected_name);
// a missing or foreign header goes through the self-healing scan
headers[i] = header.or_else(|| self.read_local_header_verified(entry).ok());
}
headers
}
/// Parses the local header at `claim` out of `window`, reading the header
/// alone when the window doesn't hold all of it.
fn window_local_header(&self, claim: usize, window: &mut Window) -> Option<LocalFileHeader> {
let fixed = window.at(claim)?;
let name_len = u16::from_le_bytes([*fixed.get(26)?, *fixed.get(27)?]) as usize;
let extra_len = u16::from_le_bytes([*fixed.get(28)?, *fixed.get(29)?]) as usize;
let total = LOCAL_HEADER_FIXED_LEN + name_len + extra_len;
if !window.covers(claim, total) {
window.fill(self, claim, total);
}
let mut header = LocalFileHeader::parse(window.at(claim)?, 0).ok()?;
header.offset = claim;
Some(header)
}
/// Reads the contents of a file from the ZIP archive.
///
/// This method handles both normally compressed files and tampered files
/// where the compression metadata may be inconsistent. It returns the
/// uncompressed file contents along with the detected compression type.
///
/// # Notes
///
/// The method attempts to handle files that have tampered headers:
/// - If the compression method indicates compression but the compressed
/// size equals the uncompressed size, the file is treated as
/// [FileCompressionType::StoredTampered].
/// - If decompression fails but the data is still present, it falls back
/// to [FileCompressionType::StoredTampered].
///
/// # Examples
///
/// ```no_run
/// # use apk_info_zip::{ZipEntry, ZipError, FileCompressionType};
/// # let zip_data = std::fs::read("archive.zip").unwrap();
/// # let zip = ZipEntry::new(zip_data).unwrap();
/// let (data, compression) = zip.read("example.txt").expect("failed to read file");
/// match compression {
/// FileCompressionType::Stored | FileCompressionType::Deflated => println!("all fine"),
/// FileCompressionType::StoredTampered | FileCompressionType::DeflatedTampered => println!("tampering detected"),
/// }
/// ```
pub fn read(&self, filename: &str) -> Result<(Vec<u8>, FileCompressionType), ZipError> {
let central_directory_entry = self
.central_directory
.entries
.get(filename)
.ok_or(ZipError::FileNotFound)?;
// Parse the local file header lazily; a corrupt claimed offset falls
// back to the bounded self-healing scan.
let local_header = self.read_local_header_verified(central_directory_entry)?;
let method = central_directory_entry.compression_method;
let tampered = local_header.compression_method != method;
let (Ok(compressed_size), Ok(uncompressed_size)) = (
usize::try_from(central_directory_entry.compressed_size),
usize::try_from(central_directory_entry.uncompressed_size),
) else {
return Err(ZipError::FileTooLarge);
};
if uncompressed_size > MAX_UNCOMPRESSED_SIZE || compressed_size > MAX_UNCOMPRESSED_SIZE {
return Err(ZipError::FileTooLarge);
}
// data offset is derived from the local header's own lengths
let offset = local_header.offset + local_header.size();
// read lengths come from the central directory: local sizes are
// zeroed under the data-descriptor flag
let read_data = |len: usize| self.source.read_bytes_at(offset, len);
match (method, compressed_size == uncompressed_size) {
(Self::METHOD_STORED, _) => {
// stored (no compression)
let data = read_data(uncompressed_size)?;
let compression = if tampered {
FileCompressionType::StoredTampered
} else {
FileCompressionType::Stored
};
Ok((data, compression))
}
(Self::METHOD_DEFLATED, _) => {
// deflate default
let compressed_data = read_data(compressed_size)?;
let inflated = inflate(&compressed_data, uncompressed_size)?;
// a size that disagrees with the data is tampered metadata:
// the real data is returned, never cut to the declared size
let size_mismatch = inflated.data.len() != uncompressed_size;
if !inflated.complete {
warn!(
"{filename}: deflate stream ends early, {} of {uncompressed_size} declared bytes recovered",
inflated.data.len()
);
} else if size_mismatch {
warn!(
"{filename}: inflates to {} bytes, the central directory declares {uncompressed_size}",
inflated.data.len()
);
}
let compression = if tampered || size_mismatch {
FileCompressionType::DeflatedTampered
} else {
FileCompressionType::Deflated
};
Ok((inflated.data, compression))
}
(_, true) => {
// unknown method but stored-sized
let data = read_data(uncompressed_size)?;
Ok((data, FileCompressionType::StoredTampered))
}
(_, false) => {
// unknown method: try deflate, then fall back to stored
let compressed_data = read_data(compressed_size)?;
// only a whole, valid stream that uses up the data counts as deflate
match inflate(&compressed_data, uncompressed_size) {
Ok(inflated)
if inflated.complete && inflated.consumed == compressed_data.len() =>
{
Ok((inflated.data, FileCompressionType::DeflatedTampered))
}
_ => {
// fallback to stored tampered
let data = read_data(uncompressed_size)?;
Ok((data, FileCompressionType::StoredTampered))
}
}
}
}
}
/// Parses an archive nested inside this one, e.g. the base apk of a
/// `xapk`/`apkm` container.
///
/// For a stored entry, it reads the inner archive in place through a window
/// over the same source, so a large inner apk costs one central directory
/// read. For any other entry, it decompresses the data into memory first
/// and gets the same bytes as [`ZipEntry::read`].
///
/// # Errors
///
/// Returns a [ZipError] if the entry cannot be read, or the nested data is
/// not a valid archive (see [`ZipEntry::from_reader`]).
///
/// # Examples
///
/// ```no_run
/// # use apk_info_zip::ZipEntry;
/// let container = ZipEntry::open("app.apkm").unwrap();
/// let base = container.open_nested("base.apk").expect("failed to parse inner apk");
/// ```
pub fn open_nested(&self, filename: &str) -> Result<ZipEntry, ZipError> {
let entry = self
.central_directory
.entries
.get(filename)
.ok_or(ZipError::FileNotFound)?;
let method = entry.compression_method;
let size = usize::try_from(entry.uncompressed_size).map_err(|_| ZipError::FileTooLarge)?;
let stored = method == Self::METHOD_STORED
|| (method != Self::METHOD_DEFLATED
&& entry.compressed_size == entry.uncompressed_size);
// a stored archive is read in place, so its size costs no memory
if !stored {
let (data, _) = self.read(filename)?;
return Self::new(data);
}
let local_header = self.read_local_header_verified(entry)?;
let offset = local_header.offset + local_header.size();
Self::parse(self.source.slice(offset, size)?)
}
}
/// Implementation for certificate parsing
///
/// Very cool research about signature blocks: <https://goa2023.nullcon.net/doc/goa-2023/Android-SigMorph-Covert-Communication-Exploiting-Android-Signing-Schemes.pdf>
impl ZipEntry {
/// Magic of APK signing block
///
/// See: <https://source.android.com/docs/security/features/apksigning/v2#apk-signing-block>
pub const APK_SIGNATURE_MAGIC: &[u8] = b"APK Sig Block 42";
/// Magic of V2 Signature Scheme
///
/// See: <https://xrefandroid.com/android-16.0.0_r2/xref/tools/apksig/src/main/java/com/android/apksig/internal/apk/v2/V2SchemeConstants.java#23>
pub const SIGNATURE_SCHEME_V2_BLOCK_ID: u32 = 0x7109871a;
/// Magic of V3 Signature Scheme
///
/// See: <https://xrefandroid.com/android-16.0.0_r2/xref/tools/apksig/src/main/java/com/android/apksig/internal/apk/v3/V3SchemeConstants.java#25>
pub const SIGNATURE_SCHEME_V3_BLOCK_ID: u32 = 0xf05368c0;
/// Magic of V3.1 Signature Scheme
///
/// See: <https://xrefandroid.com/android-16.0.0_r2/xref/tools/apksig/src/main/java/com/android/apksig/internal/apk/v3/V3SchemeConstants.java#26>
pub const SIGNATURE_SCHEME_V31_BLOCK_ID: u32 = 0x1b93ad61;
/// Magic of V3.2 Signature Scheme
///
/// See: <https://xrefandroid.com/android-17.0.0_r1/xref/tools/apksig/src/main/java/com/android/apksig/internal/apk/v3/V3SchemeConstants.java#27>
pub const SIGNATURE_SCHEME_V32_BLOCK_ID: u32 = 0x70e1c89f;
/// Magic of V1 source stamp signing
///
/// Includes metadata such as timestamp of the build, the version of the build tools, source code's git commit hash, etc
///
/// See: <https://xrefandroid.com/android-16.0.0_r2/xref/tools/apksig/src/main/java/com/android/apksig/internal/apk/stamp/SourceStampConstants.java#23>
pub const V1_SOURCE_STAMP_BLOCK_ID: u32 = 0x2b09189e;
/// Magic of V2 source stamp signing
///
/// Includes metadata such as timestamp of the build, the version of the build tools, source code's git commit hash, etc
///
/// See: <https://xrefandroid.com/android-16.0.0_r2/xref/tools/apksig/src/main/java/com/android/apksig/internal/apk/stamp/SourceStampConstants.java#24>
pub const V2_SOURCE_STAMP_BLOCK_ID: u32 = 0x6dff800d;
/// Used to increase the size of the signing block (including the length and magic) to a multiple 4096
///
/// See: <https://xrefandroid.com/android-16.0.0_r2/xref/tools/apksig/src/main/java/com/android/apksig/internal/apk/ApkSigningBlockUtils.java#100>
pub const VERITY_PADDING_BLOCK_ID: u32 = 0x42726577;
/// Block that contains dependency metadata, which is saved by the Android Gradle plugin to identify any issues related to dependencies
///
/// This data is compressed, encrypted by a Google Play signing key, so we can't extract it.
///
/// Dependency information for Play Console: <https://developer.android.com/build/dependencies#dependency-info-play>
///
/// See: <https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:signflinger/src/com/android/signflinger/SignedApk.java;l=58?q=0x504b4453>
pub const DEPENDENCY_INFO_BLOCK_ID: u32 = 0x504b4453;
/// Used to track channels of distribution for an APK, mostly Chinese APKs have this
///
/// Alsow known as `MEITAN_APK_CHANNEL_BLOCK`
pub const APK_CHANNEL_BLOCK_ID: u32 = 0x71777777;
/// ByteDance build config, a JSON object with feature flags, stored next to the Walle channel
///
/// Not documented publicly. Samples (sha256):
/// - `a1112a0c941f865847c2fab9138cf815735268fbfcd41d697412fb80992c7395` - Toutiao (`com.ss.android.article.news`)
/// - `4225e058411e61dfbde8310819f7551cbbc95b75d35cec1e1d3c24f718b2ec75` - Toutiao 10.1.2
pub const BYTEDANCE_BLOCK_ID: u32 = 0x71777776;
/// ByteDance padding, a few thousand ASCII `1` characters
///
/// Not documented publicly. Samples (sha256):
/// - `a1112a0c941f865847c2fab9138cf815735268fbfcd41d697412fb80992c7395` - Toutiao (`com.ss.android.article.news`)
/// - `c400ae7596f5eeaa3e3b942be1f0da0f1fe7835c6cb51618a898c3f09145b840` - Douyin (`com.ss.android.ugc.aweme`)
pub const BYTEDANCE_PADDING_BLOCK_ID: u32 = 0x71777775;
/// Google Play Frosting ID
pub const GOOGLE_PLAY_FROSTING_ID: u32 = 0x2146444e;
/// Zero block ID
pub const ZERO_BLOCK_ID: u32 = 0xff3b5998;
/// The signature of some Chinese packer
///
/// See: <https://github.com/mcxiaoke/packer-ng-plugin/blob/ffbe05a2d27406f3aea574d083cded27f0742160/common/src/main/java/com/mcxiaoke/packer/common/PackerCommon.java#L29>
pub const PACKER_NG_SIG_V2: u32 = 0x7a786b21;
/// Some apk protector/parser, idk, seen in the wild
///
/// The channel information in the ID-Value pair
///
/// See: <https://edgeone.ai/document/58005>
pub const VASDOLLY_V2: u32 = 0x881155ff;
/// Extracts information from a v1 (APK-style) signature in the ZIP archive.
///
/// Follows apksig `V1SchemeVerifier`: every `META-INF/*.RSA`, `*.DSA` or
/// `*.EC` signature block that sits directly in `META-INF/` and has a
/// matching `.SF` file is a signer, other block files are ignored. The
/// reported certificates are the ones each signer's `SignerInfo` points
/// to, followed by their issuer chains, merged across signers.
///
/// A malformed signature block is skipped with a warning; the call fails
/// only if no signature block could be parsed at all.
///
/// # Example
///
/// ```no_run
/// # use apk_info_zip::{ZipEntry, Signature};
/// # let zip_data = std::fs::read("archive.zip").unwrap();
/// # let archive = ZipEntry::new(zip_data).unwrap();
/// match archive.get_signature_v1() {
/// Ok(Some(Signature::V1(certs))) => println!("Found {} certificates", certs.len()),
/// Ok(Some(_)) => println!("v1 call returned a non-v1 signature"),
/// Ok(None) => println!("No v1 signature found"),
/// Err(err) => eprintln!("Error parsing signature: {:?}", err),
/// }
/// ```
pub fn get_signature_v1(&self) -> Result<Option<Signature>, CertificateError> {
let names: AHashSet<&str> = self.namelist().collect();
let mut certificates: Vec<CertificateInfo> = Vec::new();
let mut parsed = false;
let mut failed = false;
for block in self
.namelist()
.filter(|name| Self::is_v1_signature_block(name))
{
let stem = &block[..block.rfind('.').unwrap_or(block.len())];
if !names.contains(format!("{stem}.SF").as_str()) {
warn!("v1 signature block {block} has no matching .SF file, ignoring it");
continue;
}
let signer = self
.read(block)
.map_err(CertificateError::from)
.and_then(|(data, _)| Self::parse_v1_signature_block(&data));
match signer {
Ok(chain) => {
parsed = true;
for certificate in chain {
if !certificates.contains(&certificate) {
certificates.push(certificate);
}
}
}
Err(err) => {
warn!("skipping malformed v1 signature block {block}: {err}");
failed = true;
}
}
}
match (parsed, failed) {
(true, _) => Ok(Some(Signature::V1(certificates))),
(false, true) => Err(CertificateError::ParseError),
// just apk without signatures
(false, false) => Ok(None),
}
}
/// `META-INF/<name>.RSA|.DSA|.EC`, without subdirectories.
fn is_v1_signature_block(name: &str) -> bool {
name.strip_prefix("META-INF/").is_some_and(|rest| {
!rest.contains('/')
&& (rest.ends_with(".RSA") || rest.ends_with(".DSA") || rest.ends_with(".EC"))
})
}
/// Returns the signing certificate of a PKCS#7 signature block and its
/// issuer chain.
///
/// The blob is walked as BER so that every certificate keeps its original
/// bytes for fingerprints. The certificate comes from the first
/// `SignerInfo` that resolves to one: a certificate the `SignerInfo` does
/// not point to is not the signer, even if it comes first in the set.
fn parse_v1_signature_block(data: &[u8]) -> Result<Vec<CertificateInfo>, CertificateError> {
// 1.2.840.113549.1.7.2
const SIGNED_DATA_OID: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02];
let mut input = data;
let content_info = ber::read(&mut input).ok_or(CertificateError::ParseError)?;
let fields = ber::children(&content_info).ok_or(CertificateError::ParseError)?;
let [content_type, content, ..] = fields.as_slice() else {
return Err(CertificateError::ParseError);
};
if content_type.content != SIGNED_DATA_OID || content.tag != [0xa0] {
return Err(CertificateError::ParseError);
}
// SignedData: version, digestAlgorithms, encapContentInfo,
// certificates [0] IMPLICIT OPTIONAL, crls [1] IMPLICIT OPTIONAL, signerInfos
let signed_data = ber::children(content)
.and_then(|children| children.into_iter().next())
.ok_or(CertificateError::ParseError)?;
let fields = ber::children(&signed_data).ok_or(CertificateError::ParseError)?;
let certificates: Vec<(Certificate, &[u8])> =
match fields.iter().skip(3).find(|field| field.tag == [0xa0]) {
Some(set) => ber::children(set)
.ok_or(CertificateError::ParseError)?
.into_iter()
.filter_map(|tlv| decode_certificate(tlv.raw).map(|cert| (cert, tlv.raw)))
.collect(),
None => Vec::new(),
};
let signer_infos = fields
.iter()
.skip(3)
.find(|field| field.tag == [0x31])
.and_then(ber::children)
.ok_or(CertificateError::ParseError)?;
for signer_info in signer_infos {
let Some(signer_info) =
ber::to_der(signer_info.raw).and_then(|der| SignerInfo::from_der(&der).ok())
else {
continue;
};
let SignerIdentifier::IssuerAndSerialNumber(id) = &signer_info.sid else {
continue;
};
let leaf = certificates.iter().position(|(cert, _)| {
let tbs = cert.tbs_certificate();
tbs.serial_number() == &id.serial_number && same_name(tbs.issuer(), &id.issuer)
});
if let Some(leaf) = leaf {
return Ok(Self::certificate_chain(&certificates, leaf));
}
}
Err(CertificateError::SignerError)
}
/// Builds the chain from `leaf` by following issuers through the
/// certificate set, like apksig `Certificate.getCertificateChain`.
fn certificate_chain(
certificates: &[(Certificate, &[u8])],
leaf: usize,
) -> Vec<CertificateInfo> {
let mut unused: Vec<usize> = (0..certificates.len()).filter(|&i| i != leaf).collect();
let mut chain = vec![leaf];
let mut current = leaf;
loop {
let tbs = certificates[current].0.tbs_certificate();
if same_name(tbs.subject(), tbs.issuer()) {
break;
}
let Some(position) = unused.iter().position(|&i| {
same_name(certificates[i].0.tbs_certificate().subject(), tbs.issuer())
}) else {
break;
};
current = unused.remove(position);
chain.push(current);
}
chain
.into_iter()
.map(|i| certificate_info(&certificates[i].0, certificates[i].1))
.collect()
}
/// Parses the APK Signature Block and extracts useful information.
///
/// This method checks for the presence of an APK Signature Scheme block
/// at the end of the ZIP archive and attempts to parse all contained
/// signatures (v2, v3, etc.).
///
/// Parsing is lenient: an ID-value pair whose value is malformed is
/// skipped by its declared length, and the blocks after it are still
/// reported.
///
/// <div class="warning">
///
/// This method handles only v2+ signature blocks.
///
/// v1 signatures are handled separately - [ZipEntry::get_signature_v1].
///
/// </div>
pub fn get_signatures_other(&self) -> Result<Vec<Signature>, CertificateError> {
let offset = self.central_dir_offset;
// The APK Signing Block ends exactly 24 bytes before the central
// directory: `u64` block size + 16 bytes of magic. Only this bounded
// region is read out of the source.
if offset < 24 {
return Err(CertificateError::ParseError);
}
let tail = self
.source
.read_bytes_at(offset - 24, 24)
.map_err(|_| CertificateError::ParseError)?;
let mut slice: &[u8] = &tail;
let size_of_block = le_u64::<&[u8], ContextError>
.parse_next(&mut slice)
.map_err(|_| CertificateError::ParseError)?;
let magic = take::<usize, &[u8], ContextError>(16usize)
.parse_next(&mut slice)
.map_err(|_| CertificateError::ParseError)?;
// if the magic does not match, then assume that there is no v2+ block with signatures
if magic != Self::APK_SIGNATURE_MAGIC {
return Ok(Vec::new());
}
// the block spans [offset - (size_of_block + 8), offset - 24):
// size of block (full) - 8 bytes (size of block - start) - 24 (end signature)
let total = size_of_block
.checked_add(8)
.and_then(|v| usize::try_from(v).ok())
.ok_or(CertificateError::ParseError)?;
// does not fit before the central directory, or absurdly large
// (real signing blocks are at most a few megabytes): treat as absent
if !(24..=MAX_SIGNING_BLOCK_SIZE).contains(&total) || total > offset {
return Ok(Vec::new());
}
let block = self
.source
.read_bytes_at(offset - total, total - 24)
.map_err(|_| CertificateError::ParseError)?;
let mut slice: &[u8] = █
let size_of_block_start = le_u64::<&[u8], ContextError>
.parse_next(&mut slice)
.map_err(|_| CertificateError::ParseError)?;
// A block whose own sizes disagree is corrupt: treat it as absent
// rather than failing the whole signature listing. The v1 JAR
// signature, if any, is still reported by the caller.
if size_of_block != size_of_block_start {
warn!(
"apk signing block size mismatch: start={size_of_block_start}, end={size_of_block}, treating the block as absent"
);
return Ok(Vec::new());
}
// Android stops at the first pair it can't read and never sees the
// pairs after it, so the walk stops there too, with one clear warning
// instead of a cascade of garbage ids
if let Some(broken) = Self::find_unreadable_pair(slice) {
warn!(
"apk signing block is corrupted: the pair at offset 0x{:x} runs past the end of the block, the pairs from there on are unreachable",
offset - total + 8 + broken
);
slice = &slice[..broken];
}
let mut signatures: Vec<Signature> =
repeat::<&[u8], Option<Signature>, Vec<Option<Signature>>, ContextError, _>(
0..,
self.parse_apk_signatures(),
)
.parse_next(&mut slice)
.map_err(|_| CertificateError::ParseError)?
.into_iter()
.flatten()
.collect();
// schemes go first regardless of the pair order in the block
signatures.sort_by_key(Signature::order);
Ok(signatures)
}
/// Returns the offset of the first pair whose header or value runs past
/// the end of `pairs`, like the "size out of range" check of apksig
/// `ApkSigningBlockUtils.findApkSignatureSchemeBlock`.
fn find_unreadable_pair(pairs: &[u8]) -> Option<usize> {
let mut offset = 0;
while offset < pairs.len() {
let rest = &pairs[offset..];
let Some(size) = rest
.first_chunk::<8>()
.map(|size| u64::from_le_bytes(*size))
else {
return Some(offset);
};
// a pair with `size < 4` is still walked as a 12-byte header
let size = size.max(4);
if size > (rest.len() - 8) as u64 {
return Some(offset);
}
offset += 8 + size as usize;
}
None
}
#[expect(dead_code, reason = "describes the signer layout, not called yet")]
fn parse_digest<'a>() -> impl Parser<&'a [u8], (u32, &'a [u8]), ContextError> {
move |input: &mut &'a [u8]| {
// digest_block_length, signature_algorithm_id, digest_length, digest
let (_, signature_algorithm_id, digest) =
(le_u32, le_u32, length_take(le_u32)).parse_next(input)?;
Ok((signature_algorithm_id, digest))
}
}
fn parse_certificate<'a>() -> impl Parser<&'a [u8], Option<CertificateInfo>, ContextError> {
move |input: &mut &'a [u8]| {
let raw = length_take(le_u32).parse_next(input)?;
let Some(certificate) = decode_certificate(raw) else {
warn!(
"skipping a certificate that is neither DER nor BER (sha256={})",
hex(&Sha256::digest(raw))
);
return Ok(None);
};
Ok(Some(certificate_info(&certificate, raw)))
}
}
#[expect(dead_code, reason = "describes the signer layout, not called yet")]
fn parse_attribute_v2<'a>() -> impl Parser<&'a [u8], (u32, &'a [u8]), ContextError> {
move |input: &mut &'a [u8]| {
let (attribute_length, id) = (le_u32, le_u32).parse_next(input)?;
let value = take(attribute_length.saturating_sub(4)).parse_next(input)?;
Ok((id, value))
}
}
#[expect(dead_code, reason = "describes the signer layout, not called yet")]
fn parse_attribute_v3<'a>() -> impl Parser<&'a [u8], (u32, &'a [u8]), ContextError> {
move |input: &mut &'a [u8]| {
let (attribute_length, id) = (le_u32, le_u32).parse_next(input)?;
let value = take(attribute_length.saturating_sub(4)).parse_next(input)?;
let _const_id = le_u32.parse_next(input)?;
// also should be somekind of Proof-of-rotation struct, but skip for now
Ok((id, value))
}
}
#[expect(dead_code, reason = "describes the signer layout, not called yet")]
fn parse_signature<'a>() -> impl Parser<&'a [u8], (u32, &'a [u8]), ContextError> {
move |input: &mut &'a [u8]| {
// signature_block_length, signature_algorithm_id, signature_length, signature
let (_, signature_algorithm_id, signature) =
(le_u32, le_u32, length_take(le_u32)).parse_next(input)?;
Ok((signature_algorithm_id, signature))
}
}
fn parse_signer_v2<'a>() -> impl Parser<&'a [u8], Vec<CertificateInfo>, ContextError> {
move |input: &mut &'a [u8]| {
// 1 - parse signer
let mut signer_data = length_take(le_u32).parse_next(input)?;
// 1.1 - parse signed data
let mut signed_data = length_take(le_u32).parse_next(&mut signer_data)?;
// 1.1.1 - parse digests
let mut _digests_data = length_take(le_u32).parse_next(&mut signed_data)?;
// uncomment this block if actually need parse digests
// let digests: Vec<(u32, &[u8])> =
// repeat(0.., Self::parse_digest()).parse_next(&mut digests_data)?;
// 1.1.2 - parse certificates
let mut certificates_data = length_take(le_u32).parse_next(&mut signed_data)?;
let certificates: Vec<Option<CertificateInfo>> =
repeat(0.., Self::parse_certificate()).parse_next(&mut certificates_data)?;
// 1.1.3 - parse attributes
let mut _attributes_data = length_take(le_u32).parse_next(&mut signed_data)?;
// uncomment this block if actually need parse attributes
// let attributes: Vec<(u32, &[u8])> =
// repeat(0.., Self::parse_attribute_v2()).parse_next(&mut attributes_data)?;
// 1.2 - parse signatures
let mut _signatures_data = length_take(le_u32).parse_next(&mut signer_data)?;
// uncomment this block if actually need parse signatures
// let signatures: Vec<(u32, &[u8])> =
// repeat(0.., Self::parse_signature()).parse_next(&mut signatures_data)?;
// 1.3 - parse public key
let _public_key = length_take(le_u32).parse_next(&mut signer_data)?;
Ok(certificates.into_iter().flatten().collect())
}
}
fn parse_signer_v3<'a>() -> impl Parser<&'a [u8], Vec<CertificateInfo>, ContextError> {
move |input: &mut &'a [u8]| {
// 1 - parse signer
let mut signer_data = length_take(le_u32).parse_next(input)?;
// 1.1 - parse signed data
let mut signed_data = length_take(le_u32).parse_next(&mut signer_data)?;
// 1.1.1 - parse digests
let mut _digests_data = length_take(le_u32).parse_next(&mut signed_data)?;
// uncomment this block if actually need parse digests
// let digests: Vec<(u32, &[u8])> =
// repeat(0.., Self::parse_digest()).parse_next(&mut digests_data)?;
// 1.1.2 - parse certificates
let mut certificates_data = length_take(le_u32).parse_next(&mut signed_data)?;
let certificates: Vec<Option<CertificateInfo>> =
repeat(0.., Self::parse_certificate()).parse_next(&mut certificates_data)?;
// 1.1.3 - parse sdk's
let (_min_sdk, _max_sdk) = (le_u32, le_u32).parse_next(&mut signed_data)?;
// 1.1.4 - parse attributes
let mut _attributes_data = length_take(le_u32).parse_next(&mut signed_data)?;
// uncomment this block if actually need parse attributes
// let attributes: Vec<(u32, &[u8])> =
// repeat(0.., Self::parse_attribute_v3()).parse_next(&mut attributes_data)?;
// 1.2 - parse duplicates sdk
let (_duplicate_min_sdk, _duplicate_max_sdk) =
(le_u32, le_u32).parse_next(&mut signer_data)?;
// 1.3 - parse signatures
let mut _signatures_data = length_take(le_u32).parse_next(&mut signer_data)?;
// uncomment this block if actually need parse signatures
// let signatures: Vec<(u32, &[u8])> =
// repeat(0.., Self::parse_signature()).parse_next(&mut signatures_data)?;
// 1.4 - parse public key
let _public_key = length_take(le_u32).parse_next(&mut signer_data)?;
Ok(certificates.into_iter().flatten().collect())
}
}
/// Parses one ID-value pair, `None` for a pair that is skipped.
fn parse_apk_signatures<'a>(&self) -> impl Parser<&'a [u8], Option<Signature>, ContextError> {
// Android looks a pair up by ID and takes the first match
// (apksig `ApkSigningBlockUtils.findApkSignatureSchemeBlock`), so a
// repeated ID is never seen by the platform
let mut seen = AHashSet::new();
move |input: &mut &'a [u8]| {
let (size, id) = (le_u64, le_u32).parse_next(input)?;
if !seen.insert(id) {
warn!(
"duplicate signing block pair 0x{id:08x} (size=0x{size:08x}), Android uses only the first one, skipping"
);
let _ = take::<usize, &[u8], ContextError>(size.saturating_sub(4) as usize)
.parse_next(input)?;
return Ok(None);
}
// A malformed pair must not hide the blocks that follow it
// Skips the pair by its declared length, and continues with the next pair
let mut value: &'a [u8] = input;
match Self::parse_signature_pair_value(id, size).parse_next(&mut value) {
Ok(signature) => {
*input = value;
Ok(signature)
}
Err(_) => {
warn!(
"malformed signing block pair 0x{id:08x} (size=0x{size:08x}), skipping the pair"
);
// skip the declared value; a length running past the end
// of the block is a hard error and ends the walk
let _ = take::<usize, &[u8], ContextError>(size.saturating_sub(4) as usize)
.parse_next(input)?;
Ok(None)
}
}
}
}
/// Parses the value of a single ID-value pair of the APK Signing Block,
/// `None` for padding and blocks that are not reported.
fn parse_signature_pair_value<'a>(
id: u32,
size: u64,
) -> impl Parser<&'a [u8], Option<Signature>, ContextError> {
move |input: &mut &'a [u8]| {
let signature = match id {
Self::SIGNATURE_SCHEME_V2_BLOCK_ID => {
let mut signers_data = length_take(le_u32).parse_next(input)?;
let certificates =
repeat::<_, Vec<CertificateInfo>, Vec<Vec<CertificateInfo>>, _, _>(
1..,
Self::parse_signer_v2(),
)
.parse_next(&mut signers_data)?
.into_iter()
.flatten()
.collect();
Ok(Signature::V2(certificates))
}
Self::SIGNATURE_SCHEME_V3_BLOCK_ID => {
let mut signers_data = length_take(le_u32).parse_next(input)?;
let certificates =
repeat::<_, Vec<CertificateInfo>, Vec<Vec<CertificateInfo>>, _, _>(
1..,
Self::parse_signer_v3(),
)
.parse_next(&mut signers_data)?
.into_iter()
.flatten()
.collect();
Ok(Signature::V3(certificates))
}
Self::SIGNATURE_SCHEME_V31_BLOCK_ID => {
let mut signers_data = length_take(le_u32).parse_next(input)?;
let certificates =
repeat::<_, Vec<CertificateInfo>, Vec<Vec<CertificateInfo>>, _, _>(
1..,
Self::parse_signer_v3(),
)
.parse_next(&mut signers_data)?
.into_iter()
.flatten()
.collect();
Ok(Signature::V31(certificates))
}
Self::SIGNATURE_SCHEME_V32_BLOCK_ID => {
let mut signers_data = length_take(le_u32).parse_next(input)?;
let certificates =
repeat::<_, Vec<CertificateInfo>, Vec<Vec<CertificateInfo>>, _, _>(
1..,
Self::parse_signer_v3(),
)
.parse_next(&mut signers_data)?
.into_iter()
.flatten()
.collect();
Ok(Signature::V32(certificates))
}
Self::APK_CHANNEL_BLOCK_ID => {
let data = take(size.saturating_sub(4) as usize).parse_next(input)?;
Ok(Signature::ApkChannelBlock(
String::from_utf8_lossy(data).trim().to_string(),
))
}
Self::V1_SOURCE_STAMP_BLOCK_ID => {
// https://cs.android.com/android/platform/superproject/main/+/main:tools/apksig/src/main/java/com/android/apksig/internal/apk/stamp/V1SourceStampSigner.java;l=86;bpv=0;bpt=1
let _stamp_block_prefix = le_u32.parse_next(input)?;
let certificate = Self::parse_certificate().parse_next(input)?;
// i don't think that it is useful information
let _signed_data = length_take(le_u32).parse_next(input)?;
certificate
.map(Signature::StampBlockV1)
.ok_or_else(ContextError::new)
}
Self::V2_SOURCE_STAMP_BLOCK_ID => {
// https://cs.android.com/android/platform/superproject/main/+/main:tools/apksig/src/main/java/com/android/apksig/internal/apk/stamp/V2SourceStampSigner.java;l=124;drc=61197364367c9e404c7da6900658f1b16c42d0da;bpv=0;bpt=1
let _stamp_block_prefix = le_u32.parse_next(input)?;
let certificate = Self::parse_certificate().parse_next(input)?;
// i don't think that it is useful information
let _signed_digests_data = length_take(le_u32).parse_next(input)?;
// i don't think that it is useful information
let _encoded_stamp_attributes = length_take(le_u32).parse_next(input)?;
// i don't think that it is useful information
let _signed_attributes = length_take(le_u32).parse_next(input)?;
certificate
.map(Signature::StampBlockV2)
.ok_or_else(ContextError::new)
}
Self::PACKER_NG_SIG_V2 => {
let data = take(size.saturating_sub(4) as usize).parse_next(input)?;
Ok(Signature::PackerNextGenV2(data.to_vec()))
}
Self::GOOGLE_PLAY_FROSTING_ID => {
let _ = take(size.saturating_sub(4) as usize).parse_next(input)?;
Ok(Signature::GooglePlayFrosting)
}
Self::VASDOLLY_V2 => {
let data = take(size.saturating_sub(4) as usize).parse_next(input)?;
Ok(Signature::VasDollyV2(
String::from_utf8_lossy(data).trim().to_owned(),
))
}
Self::BYTEDANCE_BLOCK_ID => {
let data = take(size.saturating_sub(4) as usize).parse_next(input)?;
Ok(Signature::ByteDance(
String::from_utf8_lossy(data).trim().to_owned(),
))
}
Self::VERITY_PADDING_BLOCK_ID
| Self::DEPENDENCY_INFO_BLOCK_ID
| Self::ZERO_BLOCK_ID
| Self::BYTEDANCE_PADDING_BLOCK_ID => {
// not interesting blocks
let _ = take(size.saturating_sub(4) as usize).parse_next(input)?;
return Ok(None);
}
// no block uses a zero id, it shows up when the pairs lost alignment
0 => {
warn!(
"signing block pair with a zero id (size=0x{size:08x}), the block is likely misaligned"
);
let _ = take(size.saturating_sub(4) as usize).parse_next(input)?;
return Ok(None);
}
_ => {
// highlight new interesting blocks
warn!(
"got unknown id block - 0x{:08x} (size=0x{:08x}), please open issue on github, let's try to figure out",
id, size
);
let _ = take(size.saturating_sub(4) as usize).parse_next(input)?;
return Ok(None);
}
};
signature.map(Some)
}
}
}
impl From<Certificate> for CertificateInfo {
fn from(value: Certificate) -> Self {
let encoded = value.to_der().unwrap_or_default();
certificate_info(&value, &encoded)
}
}
/// Builds the certificate summary, with fingerprints over `raw`, the bytes
/// the certificate was stored as.
///
/// Android identifies a signer by the original encoding, which differs from
/// a DER re-encoding when the certificate is BER.
fn certificate_info(certificate: &Certificate, raw: &[u8]) -> CertificateInfo {
let cert = certificate.tbs_certificate();
CertificateInfo {
serial_number: hex(cert.serial_number().as_bytes()),
subject: name::to_string(cert.subject()),
issuer: name::to_string(cert.issuer()),
valid_from: cert.validity().not_before.to_string(),
valid_until: cert.validity().not_after.to_string(),
signature_type: DB
.by_oid(&cert.signature().oid)
.unwrap_or_default()
.to_string(),
md5_fingerprint: hex(&Md5::digest(raw)),
sha1_fingerprint: hex(&Sha1::digest(raw)),
sha256_fingerprint: hex(&Sha256::digest(raw)),
}
}
/// Compares distinguished names the way Java's `X500Principal.equals` does,
/// ignoring the string type and case: a `SignerInfo` may spell the issuer as
/// `PrintableString` while the certificate uses `UTF8String`.
fn same_name(a: &Name, b: &Name) -> bool {
a == b || name::to_string(a).to_lowercase() == name::to_string(b).to_lowercase()
}
/// Parses a certificate as strict DER, falling back to BER like Android does.
fn decode_certificate(raw: &[u8]) -> Option<Certificate> {
Certificate::from_der(raw)
.ok()
.or_else(|| Certificate::from_der(&ber::to_der(raw)?).ok())
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().fold(String::new(), |mut out, x| {
_ = write!(out, "{x:02x}");
out
})
}
#[cfg(test)]
mod tests {
use std::io::{Read, Seek, SeekFrom};
use ahash::AHashMap;
use super::*;
fn deflate_raw(data: &[u8]) -> Vec<u8> {
let mut compress = flate2::Compress::new(flate2::Compression::default(), false);
let mut out = Vec::with_capacity(data.len() + 1024);
compress
.compress_vec(data, &mut out, flate2::FlushCompress::Finish)
.unwrap();
out
}
/// Mixed data: compressible but not trivially.
fn sample(len: usize) -> Vec<u8> {
(0..len)
.map(|i| (i * 31 % 251) as u8 ^ (i / 1000) as u8)
.collect()
}
#[test]
fn inflate_honest_size_needs_no_reallocation() {
for len in [0, 1, 100, 65_536, 3 * 1024 * 1024] {
let data = sample(len);
let inflated = inflate(&deflate_raw(&data), len).unwrap();
assert!(inflated.complete);
assert_eq!(inflated.data, data);
assert_eq!(inflated.data.capacity(), len, "len {len}");
}
}
#[test]
fn inflate_ignores_understated_size() {
let data = sample(100_000);
let inflated = inflate(&deflate_raw(&data), 1000).unwrap();
assert!(inflated.complete);
assert_eq!(inflated.data, data);
}
#[test]
fn inflate_caps_overstated_size_by_the_input() {
let compressed = deflate_raw(b"tiny");
let inflated = inflate(&compressed, MAX_UNCOMPRESSED_SIZE).unwrap();
assert_eq!(inflated.data, b"tiny");
assert!(inflated.data.capacity() <= compressed.len() * MAX_DEFLATE_RATIO);
}
#[test]
fn inflate_reports_truncated_stream() {
let data = sample(100_000);
let compressed = deflate_raw(&data);
let inflated = inflate(&compressed[..compressed.len() / 2], data.len()).unwrap();
assert!(!inflated.complete);
assert!(!inflated.data.is_empty());
assert_eq!(&data[..inflated.data.len()], &inflated.data[..]);
}
#[test]
fn read_returns_whole_entry_despite_understated_size() {
let data = sample(100_000);
let compressed = deflate_raw(&data);
let mut archive = deflated_archive("a.bin", &compressed, data.len() as u32);
// understate the central directory's uncompressed size
let cd = memmem::rfind(&archive, b"PK\x01\x02").unwrap();
archive[cd + 24..cd + 28].copy_from_slice(&1000u32.to_le_bytes());
let zip = ZipEntry::new(archive).unwrap();
let (read, compression) = zip.read("a.bin").unwrap();
assert_eq!(read, data);
assert_eq!(compression, FileCompressionType::DeflatedTampered);
}
#[test]
fn read_honest_deflated_entry_is_not_tampered() {
let data = sample(10_000);
let archive = deflated_archive("a.bin", &deflate_raw(&data), data.len() as u32);
let zip = ZipEntry::new(archive).unwrap();
assert_eq!(
zip.read("a.bin").unwrap(),
(data, FileCompressionType::Deflated)
);
}
/// One deflated entry, sizes as given.
fn deflated_archive(name: &str, compressed: &[u8], uncompressed: u32) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(b"PK\x03\x04");
out.extend_from_slice(&20u16.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&8u16.to_le_bytes()); // deflated
out.extend_from_slice(&[0u8; 8]); // time, date, crc
out.extend_from_slice(&(compressed.len() as u32).to_le_bytes());
out.extend_from_slice(&uncompressed.to_le_bytes());
out.extend_from_slice(&(name.len() as u16).to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(name.as_bytes());
out.extend_from_slice(compressed);
let cd_offset = out.len() as u32;
out.extend_from_slice(b"PK\x01\x02");
out.extend_from_slice(&20u16.to_le_bytes());
out.extend_from_slice(&20u16.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&8u16.to_le_bytes());
out.extend_from_slice(&[0u8; 8]);
out.extend_from_slice(&(compressed.len() as u32).to_le_bytes());
out.extend_from_slice(&uncompressed.to_le_bytes());
out.extend_from_slice(&(name.len() as u16).to_le_bytes());
out.extend_from_slice(&[0u8; 12]);
out.extend_from_slice(&0u32.to_le_bytes());
out.extend_from_slice(name.as_bytes());
let cd_size = out.len() as u32 - cd_offset;
out.extend_from_slice(b"PK\x05\x06");
out.extend_from_slice(&0u32.to_le_bytes());
out.extend_from_slice(&1u16.to_le_bytes());
out.extend_from_slice(&1u16.to_le_bytes());
out.extend_from_slice(&cd_size.to_le_bytes());
out.extend_from_slice(&cd_offset.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out
}
/// Builds a minimal, well-formed two-file STORED zip archive and returns it
/// together with the byte position of each central directory entry's
/// `local_header_offset` field (so tests can corrupt it).
fn build_archive(entries: &[(&str, &[u8])]) -> (Vec<u8>, AHashMap<String, usize>) {
build_archive_gap(entries, 0)
}
/// Like [`build_archive`], but inserts `gap` filler bytes between the CD and
/// the EOCD (e.g. a ZIP64 EOCD record), so the declared `cd_offset` no
/// longer equals `eocd_offset - cd_size`.
fn build_archive_gap(
entries: &[(&str, &[u8])],
gap: usize,
) -> (Vec<u8>, AHashMap<String, usize>) {
let mut data = Vec::new();
struct Meta {
name: String,
local_header_offset: u32,
size: u32,
cd_off_field: usize,
}
let mut metas = Vec::new();
// local file headers + raw (stored) data
for (name, content) in entries {
let size = content.len() as u32;
let lho = data.len() as u32;
data.extend_from_slice(&0x0403_4b50u32.to_le_bytes());
data.extend_from_slice(&20u16.to_le_bytes()); // version needed
data.extend_from_slice(&0u16.to_le_bytes()); // flags
data.extend_from_slice(&0u16.to_le_bytes()); // method = stored
data.extend_from_slice(&0u16.to_le_bytes()); // mod time
data.extend_from_slice(&0u16.to_le_bytes()); // mod date
data.extend_from_slice(&0u32.to_le_bytes()); // crc (not verified)
data.extend_from_slice(&size.to_le_bytes());
data.extend_from_slice(&size.to_le_bytes());
data.extend_from_slice(&(name.len() as u16).to_le_bytes());
data.extend_from_slice(&0u16.to_le_bytes()); // extra len
data.extend_from_slice(name.as_bytes());
data.extend_from_slice(content);
metas.push(Meta {
name: name.to_string(),
local_header_offset: lho,
size,
cd_off_field: 0,
});
}
// central directory
let cd_start = data.len() as u32;
for m in &mut metas {
data.extend_from_slice(&0x0201_4b50u32.to_le_bytes());
data.extend_from_slice(&20u16.to_le_bytes()); // version made by
data.extend_from_slice(&20u16.to_le_bytes()); // version needed
data.extend_from_slice(&0u16.to_le_bytes()); // flags
data.extend_from_slice(&0u16.to_le_bytes()); // method
data.extend_from_slice(&0u16.to_le_bytes()); // mod time
data.extend_from_slice(&0u16.to_le_bytes()); // mod date
data.extend_from_slice(&0u32.to_le_bytes()); // crc
data.extend_from_slice(&m.size.to_le_bytes());
data.extend_from_slice(&m.size.to_le_bytes());
data.extend_from_slice(&(m.name.len() as u16).to_le_bytes());
data.extend_from_slice(&0u16.to_le_bytes()); // extra len
data.extend_from_slice(&0u16.to_le_bytes()); // comment len
data.extend_from_slice(&0u16.to_le_bytes()); // disk number
data.extend_from_slice(&0u16.to_le_bytes()); // internal attrs
data.extend_from_slice(&0u32.to_le_bytes()); // external attrs
m.cd_off_field = data.len();
data.extend_from_slice(&m.local_header_offset.to_le_bytes());
data.extend_from_slice(m.name.as_bytes());
}
let cd_size = data.len() as u32 - cd_start;
// bytes between the central directory and the EOCD (not counted in cd_size)
data.extend(std::iter::repeat_n(0, gap));
// EOCD
data.extend_from_slice(&0x0605_4b50u32.to_le_bytes());
data.extend_from_slice(&0u16.to_le_bytes()); // disk number
data.extend_from_slice(&0u16.to_le_bytes()); // cd start disk
data.extend_from_slice(&(entries.len() as u16).to_le_bytes());
data.extend_from_slice(&(entries.len() as u16).to_le_bytes());
data.extend_from_slice(&cd_size.to_le_bytes());
data.extend_from_slice(&cd_start.to_le_bytes());
data.extend_from_slice(&0u16.to_le_bytes()); // comment len
let mut fields = AHashMap::new();
for m in metas {
fields.insert(m.name, m.cd_off_field);
}
(data, fields)
}
fn corrupt_offset(data: &mut [u8], field: usize, value: u32) {
data[field..field + 4].copy_from_slice(&value.to_le_bytes());
}
#[test]
fn cd_offset_declared_wins_over_derived_when_gap_present() {
// ZIP64 record between CD and EOCD: the declared cd_offset points at the
// real CD, while `eocd_offset - cd_size` lands `gap` bytes too late.
let (data, _) = build_archive_gap(&[("a.txt", b"a"), ("b.txt", b"bb")], 76);
let zip = ZipEntry::new(data).unwrap();
assert_eq!(zip.namelist().count(), 2);
assert_eq!(zip.read("a.txt").unwrap().0, b"a");
assert_eq!(zip.read("b.txt").unwrap().0, b"bb");
}
#[test]
fn namelist_follows_central_directory_order() {
let entries: Vec<(&str, &[u8])> = ["a.txt", "b.txt", "c.txt", "d.txt", "e.txt"]
.iter()
.map(|n| (*n, n.as_bytes()))
.collect();
let (data, _) = build_archive(&entries);
// two independent parses: hash map iteration is random per instance, so
// both matching the archive order proves the names come from the CD records
let zip1 = ZipEntry::new(data.clone()).unwrap();
let zip2 = ZipEntry::new(data).unwrap();
let expected = vec!["a.txt", "b.txt", "c.txt", "d.txt", "e.txt"];
assert_eq!(zip1.namelist().collect::<Vec<_>>(), expected);
assert_eq!(zip2.namelist().collect::<Vec<_>>(), expected);
}
#[test]
fn read_works_on_healthy_archive() {
let (data, _) = build_archive(&[("a.txt", b"hello"), ("b.txt", b"world!")]);
let zip = ZipEntry::new(data).unwrap();
assert_eq!(zip.read("a.txt").unwrap().0, b"hello");
assert_eq!(zip.read("b.txt").unwrap().0, b"world!");
}
#[test]
fn read_heals_shifted_local_header_offset() {
let (mut data, fields) = build_archive(&[("a.txt", b"AAA"), ("b.txt", b"BBBBBBBB")]);
// Corrupt b's local_header_offset: claim it is 40 bytes after reality.
let orig = u32::from_le_bytes(
data[fields["b.txt"]..fields["b.txt"] + 4]
.try_into()
.unwrap(),
);
corrupt_offset(&mut data, fields["b.txt"], orig + 40);
let zip = ZipEntry::new(data).unwrap();
// b.txt's local header is not in the fast index, so read must lazily heal it.
assert_eq!(zip.read("b.txt").unwrap().0, b"BBBBBBBB");
// The untouched entry still reads normally.
assert_eq!(zip.read("a.txt").unwrap().0, b"AAA");
}
#[test]
fn read_rejects_wrong_filename_during_recovery() {
// Point b's claim at a.txt's local header. The exact-offset attempt finds
// a.txt's header but its filename does not match, so recovery must keep
// scanning until it reaches b.txt's own (matching) header.
let (mut data, fields) = build_archive(&[("a.txt", b"AAA"), ("b.txt", b"BBBB")]);
let a_claim = u32::from_le_bytes(
data[fields["a.txt"]..fields["a.txt"] + 4]
.try_into()
.unwrap(),
);
corrupt_offset(&mut data, fields["b.txt"], a_claim);
let zip = ZipEntry::new(data).unwrap();
assert_eq!(zip.read("b.txt").unwrap().0, b"BBBB");
}
#[test]
fn unhealable_offset_is_not_found() {
let (mut data, fields) = build_archive(&[("a.txt", b"AAAAAAA"), ("b.txt", b"BBBBBB")]);
// Corrupt b's claim to a huge offset well away from any local header, so
// the bounded scan cannot reach it and read must report FileNotFound.
corrupt_offset(&mut data, fields["b.txt"], u32::MAX - 100);
let zip = ZipEntry::new(data).unwrap();
assert_eq!(zip.read("b.txt").unwrap_err(), ZipError::FileNotFound);
// a.txt (healthy) still reads.
assert_eq!(zip.read("a.txt").unwrap().0, b"AAAAAAA");
}
#[test]
fn read_missing_file_is_not_found() {
let (data, _) = build_archive(&[("a.txt", b"hello")]);
let zip = ZipEntry::new(data).unwrap();
assert_eq!(zip.read("nope.txt").unwrap_err(), ZipError::FileNotFound);
}
/// A `ReadSeek` wrapper that counts how many bytes were actually read from
/// the source, to prove that parsing stays lazy.
struct CountingSource {
inner: Cursor<Vec<u8>>,
counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
}
impl CountingSource {
fn new(data: Vec<u8>) -> (Self, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
use std::sync::atomic::AtomicUsize;
let counter = std::sync::Arc::new(AtomicUsize::new(0));
(
Self {
inner: Cursor::new(data),
counter: std::sync::Arc::clone(&counter),
},
counter,
)
}
}
impl Read for CountingSource {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = self.inner.read(buf)?;
self.counter
.fetch_add(n, std::sync::atomic::Ordering::Relaxed);
Ok(n)
}
}
impl Seek for CountingSource {
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
self.inner.seek(pos)
}
}
/// Opening an archive must read only the EOCD + central directory, never
/// the entry payloads, no matter how big they are.
#[test]
fn construction_reads_only_metadata() {
// a 1MB stored entry: if the whole file were read, the counter would
// blow past the archive size
let big = vec![0x41u8; 1024 * 1024];
let (data, _) = build_archive(&[("big.bin", &big), ("small.txt", b"hi")]);
let (source, counter) = CountingSource::new(data.clone());
let zip = ZipEntry::from_reader(source).unwrap();
// archive is ~1MB, but only the tail metadata (EOCD + CD + sanity
// probes) may be read
assert!(
counter.load(std::sync::atomic::Ordering::Relaxed) < 32 * 1024,
"construction read {} bytes, not lazy",
counter.load(std::sync::atomic::Ordering::Relaxed)
);
assert_eq!(zip.namelist().count(), 2);
// reading an entry pulls roughly its own size, not the whole archive
let before = counter.load(std::sync::atomic::Ordering::Relaxed);
let (data, compression) = zip.read("big.bin").unwrap();
assert_eq!(data.len(), 1024 * 1024);
assert_eq!(compression, FileCompressionType::Stored);
assert!(
counter.load(std::sync::atomic::Ordering::Relaxed) - before <= 1024 * 1024 + 512,
"entry read pulled way more than the entry itself"
);
}
/// `ZipEntry::open` reads a real file from disk through the same lazy path.
#[test]
fn open_reads_archive_from_file() {
let (data, _) = build_archive(&[("a.txt", b"hello"), ("b.txt", b"world!")]);
let path =
std::env::temp_dir().join(format!("apk-info-lazy-test-{}.zip", std::process::id()));
std::fs::write(&path, &data).expect("can't write temp archive");
let zip = ZipEntry::open(&path).unwrap();
assert_eq!(zip.read("a.txt").unwrap().0, b"hello");
assert_eq!(zip.read("b.txt").unwrap().0, b"world!");
std::fs::remove_file(&path).ok();
}
/// An EOCD hidden behind a comment long enough to straddle the search
/// window boundary (4096) must still be found: adjacent windows overlap by
/// `MAGIC.len() - 1` bytes precisely for this case.
#[test]
fn eocd_straddling_search_window_is_found() {
let (data, _) = build_archive(&[("a.txt", b"hello")]);
// rebuild the EOCD with a comment sized so the EOCD signature starts
// exactly 2 bytes before the first 4096-byte window boundary:
// comment length 4076 => magic at len - (22 + 4076) = len - 4098
let mut data = data;
let eocd: Vec<u8> = data.split_off(data.len() - 22);
let comment = vec![0xCC; 4076];
let mut patched = eocd;
patched[20..22].copy_from_slice(&(comment.len() as u16).to_le_bytes());
patched.extend_from_slice(&comment);
data.extend_from_slice(&patched);
let zip = ZipEntry::new(data).unwrap();
assert_eq!(zip.read("a.txt").unwrap().0, b"hello");
}
/// A long comment that pushes the EOCD a full window back is found too
/// (several backward window reads).
#[test]
fn eocd_with_multiview_comment_is_found() {
let (data, _) = build_archive(&[("a.txt", b"hello")]);
let mut data = data;
let eocd: Vec<u8> = data.split_off(data.len() - 22);
let comment = vec![0xAB; 8192];
let mut patched = eocd;
patched[20..22].copy_from_slice(&(comment.len() as u16).to_le_bytes());
patched.extend_from_slice(&comment);
data.extend_from_slice(&patched);
let zip = ZipEntry::new(data).unwrap();
assert_eq!(zip.read("a.txt").unwrap().0, b"hello");
}
/// Trailing data after the EOCD leaves no candidate reaching the end; the
/// rightmost one is used without scanning the rest of the file.
#[test]
fn eocd_before_trailing_data_is_found_without_full_scan() {
let big = vec![0x41u8; 1024 * 1024];
let (mut data, _) = build_archive(&[("big.bin", &big), ("a.txt", b"hello")]);
data.extend_from_slice(&[0u8; 185]);
let (source, counter) = CountingSource::new(data);
let zip = ZipEntry::from_reader(source).unwrap();
assert_eq!(zip.read("a.txt").unwrap().0, b"hello");
assert!(
counter.load(std::sync::atomic::Ordering::Relaxed) < 128 * 1024,
"construction read {} bytes, scanned past the comment range",
counter.load(std::sync::atomic::Ordering::Relaxed)
);
}
/// A name that isn't UTF-8 neither hides the entries after it nor makes
/// its own entry unreadable: it's read under its U+FFFD name.
#[test]
fn entries_after_a_non_utf8_name_are_read() {
let (mut data, _) = build_archive(&[
("a.txt", b"first"),
("Xbad.txt", b"hidden"),
("resources.arsc", b"table"),
]);
// the same invalid lead byte in the local header and in the CD
for at in memmem::find_iter(&data.clone(), b"Xbad.txt") {
data[at] = 0xC0;
}
let zip = ZipEntry::new(data).unwrap();
assert_eq!(zip.namelist().count(), 3);
assert_eq!(zip.read("resources.arsc").unwrap().0, b"table");
assert_eq!(zip.read("\u{fffd}bad.txt").unwrap().0, b"hidden");
}
/// An EOCD further from the end than the longest comment, e.g. in a
/// truncated archive or one with data appended, is not searched for:
/// Android rejects such a file as "EOCD not found" too.
#[test]
fn eocd_beyond_comment_range_is_not_found() {
let big = vec![0x41u8; 1024 * 1024];
let (mut data, _) = build_archive(&[("a.txt", b"hello")]);
data.extend_from_slice(&big);
let (source, counter) = CountingSource::new(data);
assert_eq!(
ZipEntry::from_reader(source).unwrap_err(),
ZipError::NotFoundEOCD
);
assert!(
counter.load(std::sync::atomic::Ordering::Relaxed) < 128 * 1024,
"read {} bytes looking for the EOCD",
counter.load(std::sync::atomic::Ordering::Relaxed)
);
}
}