Debian Codegraph @

internal/cdf/cdf_test.go

raw symbols SCIP
1 package cdf
2
3 import (
4 "encoding/binary"
5 "fmt"
6 "hash/fnv"
7 "math/bits"
8 "math/rand/v2"
9 "testing"
10 )
11
12 const testSecSize = 512
13
14 // testSecSizes are the two sector sizes a CDF file may use: 512 (v3) and
15 // 4096 (v4). Table tests generate inputs for each.
16 var testSecSizes = []int{512, 4096}
17
18 // secP2 returns the power-of-two exponent stored in the header for secSize.
19 func secP2(secSize int) uint16 {
20 return uint16(bits.TrailingZeros(uint(secSize)))
21 }
22
23 // testHeader builds a 512-byte CDF header with secSize-byte sectors and
24 // 64-byte short sectors.
25 func testHeader(secSize int, firstDirSec, firstSSAT int32, minStdStream uint32, masterSAT []int32) []byte {
26 h := make([]byte, 512)
27 binary.LittleEndian.PutUint64(h, cdfMagic)
28 binary.LittleEndian.PutUint16(h[30:], secP2(secSize))
29 binary.LittleEndian.PutUint16(h[32:], 6) // 64-byte short sectors
30 binary.LittleEndian.PutUint32(h[48:], uint32(firstDirSec))
31 binary.LittleEndian.PutUint32(h[56:], minStdStream)
32 binary.LittleEndian.PutUint32(h[60:], uint32(firstSSAT))
33 binary.LittleEndian.PutUint32(h[68:], uint32(0xFFFFFFFE)) // no extra master SAT sectors
34 binary.LittleEndian.PutUint32(h[72:], 0)
35 for i := 0; i < masterSATSize; i++ {
36 v := int32(-1)
37 if i < len(masterSAT) {
38 v = masterSAT[i]
39 }
40 binary.LittleEndian.PutUint32(h[76+4*i:], uint32(v))
41 }
42 return h
43 }
44
45 // idSector encodes ids as a secSize-byte sector of little-endian int32s,
46 // padding with -1 (free).
47 func idSector(secSize int, ids ...int32) []byte {
48 s := make([]byte, secSize)
49 for i := 0; i < secSize/4; i++ {
50 v := int32(-1)
51 if i < len(ids) {
52 v = ids[i]
53 }
54 binary.LittleEndian.PutUint32(s[4*i:], uint32(v))
55 }
56 return s
57 }
58
59 // padSector pads b with zeros to a full secSize-byte sector.
60 func padSector(secSize int, b []byte) []byte {
61 s := make([]byte, secSize)
62 copy(s, b)
63 return s
64 }
65
66 // dirEntryBytes encodes a single 128-byte directory entry. The name is
67 // encoded as NUL-terminated UTF-16LE.
68 func dirEntryBytes(name string, typ uint8, first int32, size uint32, uuid []byte) []byte {
69 e := make([]byte, dirEntrySize)
70 for i := 0; i < len(name); i++ {
71 binary.LittleEndian.PutUint16(e[2*i:], uint16(name[i]))
72 }
73 binary.LittleEndian.PutUint16(e[64:], uint16(2*(len(name)+1)))
74 e[66] = typ
75 copy(e[80:96], uuid)
76 binary.LittleEndian.PutUint32(e[116:], uint32(first))
77 binary.LittleEndian.PutUint32(e[120:], size)
78 return e
79 }
80
81 // summaryStream builds a minimal (Doc)SummaryInformation property-set stream
82 // containing a single NameOfApplication (0x12) property. If wide is true the
83 // value is encoded as UTF-16LE, otherwise as ASCII.
84 func summaryStream(appName string, wide bool) []byte {
85 strType, step := uint32(typeStringASCII), 1
86 if wide {
87 strType, step = typeStringWide, 2
88 }
89 strData := make([]byte, (len(appName)+1)*step) // NUL-terminated
90 for i := 0; i < len(appName); i++ {
91 strData[i*step] = appName[i]
92 }
93 // Section: 8-byte header, one 8-byte property declaration, then the value.
94 section := make([]byte, 24, 24+len(strData))
95 binary.LittleEndian.PutUint32(section[4:], 1) // one property
96 binary.LittleEndian.PutUint32(section[8:], propIDNameOfApplication)
97 binary.LittleEndian.PutUint32(section[12:], 16) // value offset in section
98 binary.LittleEndian.PutUint32(section[16:], strType)
99 binary.LittleEndian.PutUint32(section[20:], uint32(len(appName)+1))
100 section = append(section, strData...)
101 binary.LittleEndian.PutUint32(section, uint32(len(section))) // section length
102
103 // 48-byte property-set header; the first section declaration starts at
104 // 0x1c and its offset field (at 0x2c) points right after the header.
105 stream := make([]byte, 48+len(section))
106 binary.LittleEndian.PutUint32(stream[44:], 48)
107 copy(stream[48:], section)
108 return stream
109 }
110
111 type entrySpec struct {
112 name string
113 typ uint8
114 }
115
116 // makeCDF assembles a complete single-SAT-sector CDF file with secSize-byte
117 // sectors:
118 //
119 // sector 0: SAT
120 // sector 1: directory (root entry, optional summary entry, extras)
121 // sector 2: root storage's stream (short-sector pool, zero-filled)
122 // sector 3: summary stream (when summary != nil)
123 //
124 // The 512-byte header is zero-padded to a full sector so sector 0 starts at
125 // offset secSize. minStdStream is 0 so every stream is read through the
126 // long-sector path. Extra entries carry no stream data; detection only
127 // inspects their names.
128 func makeCDF(secSize int, rootUUID []byte, summaryName string, summary []byte, extras ...entrySpec) []byte {
129 if len(summary) > secSize {
130 panic("summary stream larger than one sector")
131 }
132 dir := dirEntryBytes("Root Entry", dirTypeRootStorage, 2, uint32(secSize), rootUUID)
133 if summary != nil {
134 dir = append(dir, dirEntryBytes(summaryName, dirTypeUserStream, 3, uint32(len(summary)), nil)...)
135 }
136 for _, e := range extras {
137 dir = append(dir, dirEntryBytes(e.name, e.typ, -2, 0, nil)...)
138 }
139 if len(dir) > secSize {
140 panic("directory larger than one sector")
141 }
142
143 out := padSector(secSize, testHeader(secSize, 1, -2, 0, []int32{0}))
144 out = append(out, idSector(secSize, -3, -2, -2, -2)...) // all chains are single-sector
145 out = append(out, padSector(secSize, dir)...)
146 out = append(out, make([]byte, secSize)...)
147 out = append(out, padSector(secSize, summary)...)
148 return out
149 }
150
151 func TestDetectInvalidInput(t *testing.T) {
152 badSectorSize := testHeader(testSecSize, 1, -2, 0, nil)
153 binary.LittleEndian.PutUint16(badSectorSize[30:], 21) // secP2 > 20
154
155 tooSmallSector := testHeader(testSecSize, 1, -2, 0, nil)
156 binary.LittleEndian.PutUint16(tooSmallSector[30:], 5) // 32 < dirEntrySize
157
158 // firstDirSec * secSize == 2^31 overflows int on 32bit arch and causes
159 // slice-bounds panic.
160 dirSecOverflow := testHeader(testSecSize, 1<<22-1, -2, 0, nil)
161
162 // secSize=4096, masterSAT[0]=0, firstSSAT=0. sector(0) is only 1 byte (file
163 // ends one byte into it), so collectIDs must not loop forever trying to read
164 // int32s from a sub-4-byte buffer.
165 secSize4K := 4096
166 truncatedSSAT := append(
167 padSector(secSize4K, testHeader(secSize4K, -2, 0, 0, []int32{0})),
168 0x00, // one-byte sector 0 — too small for even one int32
169 )
170
171 tests := []struct {
172 name string
173 data []byte
174 }{
175 {"nil", nil},
176 {"short", []byte{0xD0, 0xCF, 0x11, 0xE0}},
177 {"bad magic", make([]byte, 512)},
178 {"bad sector size", badSectorSize},
179 {"sector smaller than dir entry", tooSmallSector},
180 {"dir sector overflows int32", dirSecOverflow},
181 {"truncated sector in SSAT chain loops forever", truncatedSSAT},
182 }
183 for _, tt := range tests {
184 t.Run(tt.name, func(t *testing.T) {
185 if got := Detect(tt.data); got != CDFTypeGeneric {
186 t.Errorf("Detect() = %v, want CDFTypeGeneric", got)
187 }
188 })
189 }
190 }
191
192 func TestDetectMSIRootCLSID(t *testing.T) {
193 for _, secSize := range testSecSizes {
194 data := makeCDF(secSize, msiCLSID, "", nil)
195 if got := Detect(data); got != CDFTypeInstaller {
196 t.Errorf("Detect(secSize=%d) = %v, want CDFTypeInstaller", secSize, got)
197 }
198 }
199 }
200
201 func TestDetectFromAppName(t *testing.T) {
202 tests := []struct {
203 app string
204 want CDFType
205 }{
206 {"Microsoft Office Word", CDFTypeDoc},
207 {"Microsoft Excel", CDFTypeXls},
208 {"Microsoft Powerpoint", CDFTypePpt},
209 {"Advanced Installer 19.0", CDFTypeInstaller},
210 {"InstallShield", CDFTypeInstaller},
211 {"Microsoft Patch Compiler", CDFTypeInstaller},
212 {"NAnt", CDFTypeInstaller},
213 {"Windows Installer XML Toolset", CDFTypeInstaller},
214 {"MICROSOFT WORD", CDFTypeDoc}, // matching is case-insensitive
215 }
216 summaryNames := []string{"\x05SummaryInformation", "\x05DocumentSummaryInformation"}
217 for _, secSize := range testSecSizes {
218 for _, summaryName := range summaryNames {
219 for _, wide := range []bool{false, true} {
220 for _, tt := range tests {
221 t.Run(tt.app, func(t *testing.T) {
222 data := makeCDF(secSize, nil, summaryName, summaryStream(tt.app, wide))
223 if got := Detect(data); got != tt.want {
224 t.Errorf("Detect(secSize=%d, summary=%q, app=%q, wide=%v) = %v, want %v",
225 secSize, summaryName, tt.app, wide, got, tt.want)
226 }
227 })
228 }
229 }
230 }
231 }
232 }
233
234 // TestDetectFromSiblingNames exercises the fallback inside detectFromSummary:
235 // the application name does not match, so detection relies on the names of
236 // the other directory entries.
237 func TestDetectFromSiblingNames(t *testing.T) {
238 tests := []struct {
239 sibling string
240 want CDFType
241 }{
242 {"Book", CDFTypeXls},
243 {"Workbook", CDFTypeXls},
244 {"WordDocument", CDFTypeDoc},
245 {"PowerPoint Document", CDFTypePpt},
246 {"\x05DigitalSignature", CDFTypeInstaller},
247 // A non-distinctive sibling name yields no match, so detection
248 // falls back to the generic OLE storage type.
249 {"Contents", CDFTypeGeneric},
250 }
251 for _, secSize := range testSecSizes {
252 for _, tt := range tests {
253 t.Run(tt.sibling, func(t *testing.T) {
254 summary := summaryStream("Unknown Application", false)
255 data := makeCDF(secSize, nil, "\x05SummaryInformation", summary, entrySpec{tt.sibling, dirTypeUserStream})
256 if got := Detect(data); got != tt.want {
257 t.Errorf("Detect(secSize=%d) = %v, want %v", secSize, got, tt.want)
258 }
259 })
260 }
261 }
262 }
263
264 // TestDetectFromSectionNames exercises the final fallback in Detect: no
265 // summary stream at all, detection relies on distinctive directory entries.
266 func TestDetectFromSectionNames(t *testing.T) {
267 tests := []struct {
268 entry entrySpec
269 want CDFType
270 }{
271 {entrySpec{"EncryptedPackage", dirTypeUserStream}, CDFTypeGeneric},
272 {entrySpec{"EncryptedSummary", dirTypeUserStream}, CDFTypeGeneric},
273 {entrySpec{"Book", dirTypeUserStream}, CDFTypeXls},
274 {entrySpec{"Workbook", dirTypeUserStream}, CDFTypeXls},
275 {entrySpec{"WordDocument", dirTypeUserStream}, CDFTypeDoc},
276 {entrySpec{"PowerPoint Document", dirTypeUserStream}, CDFTypePpt},
277 {entrySpec{"__properties_version1.0", dirTypeUserStream}, CDFTypeMsg},
278 {entrySpec{"__recip_version1.0_#00000000", dirTypeUserStorage}, CDFTypeMsg},
279 // A non-distinctive entry matches nothing and degrades to generic.
280 {entrySpec{"Contents", dirTypeUserStream}, CDFTypeGeneric},
281 }
282 for _, secSize := range testSecSizes {
283 for _, tt := range tests {
284 t.Run(tt.entry.name, func(t *testing.T) {
285 data := makeCDF(secSize, nil, "", nil, tt.entry)
286 if got := Detect(data); got != tt.want {
287 t.Errorf("Detect(secSize=%d) = %v, want %v", secSize, got, tt.want)
288 }
289 })
290 }
291 }
292 }
293
294 // TestDetectMasterSATExtension builds a file whose SAT does not fit in the
295 // 109 header slots, so part of it must be loaded through the master SAT
296 // extension chain. The directory and streams live in sectors mapped only by
297 // the extension SAT sector, so detection fails unless the chain is followed.
298 func TestDetectMasterSATExtension(t *testing.T) {
299 const (
300 msatSec = 109 // master SAT extension sector
301 extSATSec = 110 // SAT sector referenced from the extension
302 dirSec = 13952 // first sector mapped by extSATSec (109*128)
303 rootSec = 13953
304 summarySec = 13954
305 nSectors = summarySec + 1
306 )
307 summary := summaryStream("Microsoft Excel", false)
308
309 data := make([]byte, (1+nSectors)*testSecSize)
310 sector := func(id int32) []byte {
311 off := (1 + int(id)) * testSecSize
312 return data[off : off+testSecSize]
313 }
314
315 masterSAT := make([]int32, masterSATSize)
316 for i := range masterSAT {
317 masterSAT[i] = int32(i) // SAT occupies sectors 0..108
318 }
319 copy(data, testHeader(testSecSize, dirSec, -2, 0, masterSAT))
320 binary.LittleEndian.PutUint32(data[68:], msatSec) // first extension sector
321 binary.LittleEndian.PutUint32(data[72:], 1) // one extension sector
322
323 // Mark every SAT entry free, then set the entries actually used.
324 for i := int32(0); i < masterSATSize; i++ {
325 copy(sector(i), idSector(testSecSize))
326 }
327 satIDs := make([]int32, testSecSize/4)
328 for i := range satIDs {
329 satIDs[i] = -1
330 }
331 for i := 0; i <= extSATSec; i++ {
332 satIDs[i] = -3 // sectors 0..110 hold SAT/MSAT data
333 }
334 copy(sector(0), idSector(testSecSize, satIDs...))
335
336 // The extension lists one extra SAT sector; remaining slots are free.
337 copy(sector(msatSec), idSector(testSecSize, extSATSec))
338 // extSATSec maps sectors 13952..14079: dir, root stream and summary are
339 // all single-sector chains.
340 copy(sector(extSATSec), idSector(testSecSize, -2, -2, -2))
341
342 dir := dirEntryBytes("Root Entry", dirTypeRootStorage, rootSec, testSecSize, nil)
343 dir = append(dir, dirEntryBytes("\x05SummaryInformation", dirTypeUserStream, summarySec, uint32(len(summary)), nil)...)
344 copy(sector(dirSec), dir)
345 copy(sector(summarySec), summary)
346
347 if got := Detect(data); got != CDFTypeXls {
348 t.Errorf("Detect() = %v, want CDFTypeXls", got)
349 }
350 }
351
352 // TestDetectShortStreamSummary stores the summary stream in the short-sector
353 // pool, exercising the SSAT and readShort paths.
354 func TestDetectShortStreamSummary(t *testing.T) {
355 summary := summaryStream("Microsoft Office Word", false)
356 if len(summary) <= 64 || len(summary) > testSecSize {
357 t.Fatalf("summary len %d, want >64 and <=%d to span short sectors", len(summary), testSecSize)
358 }
359
360 dir := dirEntryBytes("Root Entry", dirTypeRootStorage, 2, testSecSize, nil)
361 // streamFirst is a short-sector id because size < minStdStream.
362 dir = append(dir, dirEntryBytes("\x05SummaryInformation", dirTypeUserStream, 0, uint32(len(summary)), nil)...)
363
364 // sector 0: SAT, sector 1: dir, sector 2: short-sector pool, sector 3: SSAT
365 data := testHeader(testSecSize, 1, 3, 4096, []int32{0})
366 data = append(data, idSector(testSecSize, -3, -2, -2, -2)...)
367 data = append(data, padSector(testSecSize, dir)...)
368 data = append(data, padSector(testSecSize, summary)...) // pool holds the summary in 64-byte short sectors
369 nShort := int32((len(summary) + 63) / 64)
370 ssat := make([]int32, nShort)
371 for i := int32(0); i < nShort-1; i++ {
372 ssat[i] = i + 1
373 }
374 ssat[nShort-1] = -2
375 data = append(data, idSector(testSecSize, ssat...)...)
376
377 if got := Detect(data); got != CDFTypeDoc {
378 t.Errorf("Detect() = %v, want CDFTypeDoc", got)
379 }
380 }
381
382 // TestDetectShortStreamMultiSectorSSAT verifies that detection still succeeds
383 // when the short-stream we care about lives outside the first SSAT sector.
384 // With secSize=512 each SSAT sector holds 128 entries, so placing the summary
385 // at short-sector id 128 forces the lookup to descend into the second SSAT
386 // sector. Any per-sector bound (e.g. ssatLen() returning secSize/4) would
387 // wrongly reject sid=128 and cause detection to fall back to CDFTypeGeneric.
388 func TestDetectShortStreamMultiSectorSSAT(t *testing.T) {
389 const (
390 shortSecSz = 64
391 perSec = testSecSize / 4 // 128 SSAT entries per long sector
392 sstSectors = 17 // SST must reach short-sector 128 (offset 8192)
393 firstSST = int32(2)
394 lastSST = firstSST + sstSectors - 1
395 ssatSecA = lastSST + 1
396 ssatSecB = ssatSecA + 1
397 sidB0 = int32(perSec) // first short-sector id in the second SSAT sector
398 )
399 summary := summaryStream("Microsoft Office Word", false)
400 if len(summary) > 2*shortSecSz {
401 t.Fatalf("summary len %d, want <= %d so it fits in 2 short sectors", len(summary), 2*shortSecSz)
402 }
403
404 dir := dirEntryBytes("Root Entry", dirTypeRootStorage, firstSST, uint32(sstSectors*testSecSize), nil)
405 dir = append(dir, dirEntryBytes("\x05SummaryInformation", dirTypeUserStream, sidB0, uint32(len(summary)), nil)...)
406
407 // SAT layout: SAT itself, dir, chained SST sectors, two SSAT sectors.
408 sat := make([]int32, perSec)
409 for i := range sat {
410 sat[i] = -1
411 }
412 sat[0] = -3
413 sat[1] = -2
414 for s := firstSST; s < lastSST; s++ {
415 sat[s] = s + 1
416 }
417 sat[lastSST] = -2
418 sat[ssatSecA] = ssatSecB
419 sat[ssatSecB] = -2
420
421 data := testHeader(testSecSize, 1, ssatSecA, 4096, []int32{0})
422 data = append(data, idSector(testSecSize, sat...)...)
423 data = append(data, padSector(testSecSize, dir)...)
424
425 // Short-stream pool: 17 long sectors. Place the summary at short-sid 128,
426 // which lives at byte offset 128*64 = 8192 inside the pool.
427 sst := make([]byte, sstSectors*testSecSize)
428 copy(sst[int(sidB0)*shortSecSz:], summary)
429 data = append(data, sst...)
430
431 // First SSAT sector: nothing useful (all entries free).
432 data = append(data, idSector(testSecSize)...)
433
434 // Second SSAT sector: chain short-sector 128 → 129 → end, so a correct
435 // reader can recover the summary stream from the pool.
436 nShort := int32((len(summary) + shortSecSz - 1) / shortSecSz)
437 ssatB := make([]int32, perSec)
438 for i := range ssatB {
439 ssatB[i] = -1
440 }
441 for i := int32(0); i < nShort-1; i++ {
442 ssatB[i] = sidB0 + i + 1
443 }
444 ssatB[nShort-1] = -2
445 data = append(data, idSector(testSecSize, ssatB...)...)
446
447 if got := Detect(data); got != CDFTypeDoc {
448 t.Errorf("Detect() = %v, want CDFTypeDoc (short stream in 2nd SSAT sector)", got)
449 }
450 }
451
452 // makeFragmentedDirCDF builds a CDF whose directory stream spans two
453 // physically non-contiguous long sectors. Layout:
454 //
455 // sector 0: SAT
456 // sector 1: directory part 1 (contains Root Entry)
457 // sector 2: filler (free sector; SAT entry is -1)
458 // sector 3: directory part 2 (contains a WordDocument entry)
459 //
460 // The directory chain in the SAT is 1 → 3 → -2, so the second dir sector is
461 // only reachable via a fragmented walk. Detection must return CDFTypeDoc,
462 // which only happens if readLong follows the fragmented chain.
463 func makeFragmentedDirCDF(secSize int) []byte {
464 dir1 := dirEntryBytes("Root Entry", dirTypeRootStorage, -1, 0, nil)
465 dir2 := dirEntryBytes("WordDocument", dirTypeUserStream, -1, 0, nil)
466
467 data := padSector(secSize, testHeader(secSize, 1, -1, 4096, []int32{0}))
468 data = append(data, idSector(secSize, -3, 3, -1, -2)...) // sector 0: SAT
469 data = append(data, padSector(secSize, dir1)...) // sector 1: dir part 1
470 data = append(data, padSector(secSize, nil)...) // sector 2: filler
471 data = append(data, padSector(secSize, dir2)...) // sector 3: dir part 2
472 return data
473 }
474
475 // TestDetectFragmentedDirChain verifies that detection still works when the
476 // directory stream is split across non-contiguous long sectors — a layout
477 // real-world CDF writers (MSI builders, edited Office documents) commonly
478 // produce. The distinctive entry (WordDocument) lives in the second dir
479 // sector, so a readLong implementation that only handles contiguous chains
480 // will miss it and incorrectly return CDFTypeGeneric.
481 func TestDetectFragmentedDirChain(t *testing.T) {
482 for _, secSize := range testSecSizes {
483 t.Run(fmt.Sprintf("sec%d", secSize), func(t *testing.T) {
484 data := makeFragmentedDirCDF(secSize)
485 if got := Detect(data); got != CDFTypeDoc {
486 t.Errorf("Detect() = %v, want CDFTypeDoc (fragmented dir chain)", got)
487 }
488 })
489 }
490 }
491
492 func put16(b []byte, off int, v uint16) { binary.LittleEndian.PutUint16(b[off:], v) }
493 func put32(b []byte, off int, v uint32) { binary.LittleEndian.PutUint32(b[off:], v) }
494
495 // TestBuildSATTruncatedMSATNoPanic feeds a CDF whose master-SAT points at a
496 // partial (truncated) sector. The inner SAT loop walks perSec entries without
497 // checking len(msa), so a short sector triggers an index-out-of-range panic.
498 // CDF files use a sector size of either 512 (secP2 9) or 4096 (secP2 12); both
499 // are exercised here.
500 func TestBuildSATTruncatedMSATNoPanic(t *testing.T) {
501 for _, tc := range []struct {
502 name string
503 secP2 uint16
504 secSize int
505 }{
506 {"sector 512", 9, 512},
507 {"sector 4096", 12, 4096},
508 } {
509 t.Run(tc.name, func(t *testing.T) {
510 // One extra int32 (4 bytes) past the header: sector 0 starts at
511 // offset secSize and is only 4 bytes long, so readInt32s yields a
512 // single entry while the loop expects perSec of them.
513 data := make([]byte, tc.secSize+4)
514 binary.LittleEndian.PutUint64(data, cdfMagic)
515 put16(data, 30, tc.secP2)
516 put16(data, 32, 6) // shortP2
517 put32(data, 48, 0xFFFFFFFF) // firstDirSec = -1
518 put32(data, 56, 4096) // minStdStream
519 put32(data, 60, 0xFFFFFFFF) // firstSSAT = -1
520 put32(data, 68, 0) // firstMSAT = sector 0
521 put32(data, 72, 1) // nMSAT = 1
522 // masterSAT[0] points past EOF so the header loop breaks
523 // (errTruncated) and execution falls through to the master-SAT
524 // extension loop.
525 put32(data, 76, 100)
526 for i := 1; i < masterSATSize; i++ {
527 put32(data, 76+4*i, 0xFFFFFFFF)
528 }
529 // data[secSize:secSize+4] = 0 -> msa = [0], a non-negative secid so
530 // the loop keeps going and then dereferences msa[1].
531 put32(data, tc.secSize, 0)
532
533 if cdf := Detect(data); cdf != CDFTypeGeneric {
534 t.Errorf("expected: %q, got: %q", CDFTypeGeneric, cdf)
535 }
536 })
537 }
538 }
539
540 // TestCyclicChainBounded feeds a CDF whose SAT contains a self-referential
541 // entry (sector 1 points at itself) together with the maximum sector size of
542 // 1MiB (secP2 20). Walking such a cycle must be bounded by the input size: a
543 // stream can never be longer than the file. Without that bound the reader would
544 // follow the cycle thousands of times, each step appending a whole 1MiB sector,
545 // and attempt a multi-gigabyte allocation.
546 func TestCyclicChainBounded(t *testing.T) {
547 const secP2 = 20
548 secSize := 1 << secP2
549 // Header region [0,secSize), then sector 0 and sector 1.
550 data := make([]byte, 3*secSize)
551 binary.LittleEndian.PutUint64(data, cdfMagic)
552 put16(data, 30, secP2)
553 put16(data, 32, 6) // shortP2
554 put32(data, 48, 1) // firstDirSec = sector 1
555 put32(data, 56, 4096) // minStdStream
556 put32(data, 60, 0xFFFFFFFF) // firstSSAT = -1
557 put32(data, 68, 0xFFFFFFFF) // firstMSAT = -1
558 put32(data, 72, 0) // nMSAT = 0
559 // masterSAT[0] = sector 0 holds the SAT; the rest are unused (-1).
560 put32(data, 76, 0)
561 for i := 1; i < masterSATSize; i++ {
562 put32(data, 76+4*i, 0xFFFFFFFF)
563 }
564 // SAT lives in sector 0 (file offset secSize). Make sat[1] = 1 so the
565 // directory chain starting at sector 1 loops forever.
566 put32(data, secSize+4, 1)
567
568 if cdf := Detect(data); cdf != CDFTypeGeneric {
569 t.Errorf("expected: %q, got: %q", CDFTypeGeneric, cdf)
570 }
571 }
572
573 // TestSummaryAppNameNoPanic feeds summaryAppName streams whose length/offset
574 // fields are crafted to overflow or go negative, plus one well-formed stream.
575 // Malformed inputs must not panic and must yield "". The sdOff case is
576 // 386-specific: int(sdOff) is negative there, so the bounds check is bypassed
577 // and stream[sdOff:] would panic.
578 func TestSummaryAppNameNoPanic(t *testing.T) {
579 for _, tc := range []struct {
580 name string
581 stream func() []byte
582 want string
583 }{{
584 // A well-formed stream with NameOfApplication = "Word".
585 name: "valid app name",
586 stream: func() []byte {
587 stream := make([]byte, 80)
588 put32(stream, sectionDeclOffset+16, 48) // sdOff -> section at 48
589 sec := stream[48:]
590 put32(sec, 0, 29) // shLen
591 put32(sec, 4, 1) // nProps
592 put32(sec, 8, propIDNameOfApplication)
593 put32(sec, 12, 16) // off -> value at section[16:]
594 put32(sec, 16, typeStringASCII) // step = 1
595 put32(sec, 20, 5) // slen ("Word\0")
596 copy(sec[24:], "Word\x00")
597 return stream
598 },
599 want: "Word",
600 }, {
601 // off is near math.MaxUint32 so that off+8 overflows uint32 and
602 // bypasses the bounds check, then section[off:] panics.
603 name: "offset overflow",
604 stream: func() []byte {
605 stream := make([]byte, 64)
606 put32(stream, sectionDeclOffset+16, 48) // sdOff -> section at 48
607 sec := stream[48:]
608 put32(sec, 0, 16) // shLen
609 put32(sec, 4, 1) // nProps
610 put32(sec, 8, propIDNameOfApplication)
611 put32(sec, 12, 0xFFFFFFFF) // off; off+8 wraps to 7
612 return stream
613 },
614 want: "",
615 }, {
616 // slen*step overflows uint32, producing end < start so that
617 // section[start:end] panics.
618 name: "length overflow",
619 stream: func() []byte {
620 stream := make([]byte, 80)
621 put32(stream, sectionDeclOffset+16, 48) // sdOff -> section at 48
622 sec := stream[48:]
623 put32(sec, 0, 32) // shLen
624 put32(sec, 4, 1) // nProps
625 put32(sec, 8, propIDNameOfApplication)
626 put32(sec, 12, 16) // off -> value at section[16:]
627 put32(sec, 16, typeStringWide) // step = 2
628 put32(sec, 20, 0xFFFFFFFF) // slen; slen*2 overflows uint32
629 return stream
630 },
631 want: "",
632 }, {
633 // sdOff above math.MaxInt32. On 386 int(sdOff) is negative, the
634 // bounds check passes and stream[sdOff:] panics.
635 name: "sdOff negative on 386",
636 stream: func() []byte {
637 stream := make([]byte, 64)
638 put32(stream, sectionDeclOffset+16, 0x80000000) // sdOff > MaxInt32
639 return stream
640 },
641 want: "",
642 }} {
643 t.Run(tc.name, func(t *testing.T) {
644 if got := string(summaryAppName(tc.stream())); got != tc.want {
645 t.Errorf("expected: %q, got: %q", tc.want, got)
646 }
647 })
648 }
649 }
650
651 func BenchmarkDetect(b *testing.B) {
652 cases := []struct {
653 name string
654 build func(secSize int) []byte
655 }{{
656 name: "MSIRootCLSID",
657 build: func(secSize int) []byte {
658 return makeCDF(secSize, msiCLSID, "", nil)
659 },
660 }, {
661 name: "AppNameASCII",
662 build: func(secSize int) []byte {
663 return makeCDF(secSize, nil, "\x05SummaryInformation",
664 summaryStream("Microsoft Office Word", false))
665 },
666 }, {
667 name: "AppNameWide",
668 build: func(secSize int) []byte {
669 return makeCDF(secSize, nil, "\x05SummaryInformation",
670 summaryStream("Microsoft Excel", true))
671 },
672 }, {
673 name: "SiblingName",
674 build: func(secSize int) []byte {
675 return makeCDF(secSize, nil, "\x05SummaryInformation",
676 summaryStream("Unknown Application", false),
677 entrySpec{"WordDocument", dirTypeUserStream})
678 },
679 }, {
680 name: "SectionName",
681 build: func(secSize int) []byte {
682 return makeCDF(secSize, nil, "", nil,
683 entrySpec{"EncryptedPackage", dirTypeUserStream})
684 },
685 }, {
686 name: "Generic",
687 build: func(secSize int) []byte {
688 return makeCDF(secSize, nil, "", nil,
689 entrySpec{"Contents", dirTypeUserStream})
690 },
691 }, {
692 name: "ShortStreamSummary",
693 build: func(secSize int) []byte {
694 summary := summaryStream("Microsoft Office Word", false)
695 dir := dirEntryBytes("Root Entry", dirTypeRootStorage, 2, uint32(secSize), nil)
696 dir = append(dir, dirEntryBytes("\x05SummaryInformation", dirTypeUserStream, 0, uint32(len(summary)), nil)...)
697 // sector 0: SAT, sector 1: dir, sector 2: short-stream pool, sector 3: SSAT.
698 data := testHeader(secSize, 1, 3, 4096, []int32{0})
699 data = append(data, idSector(secSize, -3, -2, -2, -2)...)
700 data = append(data, padSector(secSize, dir)...)
701 data = append(data, padSector(secSize, summary)...)
702 nShort := int32((len(summary) + 63) / 64)
703 ssat := make([]int32, nShort)
704 for i := int32(0); i < nShort-1; i++ {
705 ssat[i] = i + 1
706 }
707 ssat[nShort-1] = -2
708 data = append(data, idSector(secSize, ssat...)...)
709 return data
710 },
711 }, {
712 name: "FragmentedDir",
713 build: makeFragmentedDirCDF,
714 }}
715
716 for _, secSize := range testSecSizes {
717 for _, bc := range cases {
718 data := bc.build(secSize)
719 b.Run(fmt.Sprintf("%s/sec%d", bc.name, secSize), func(b *testing.B) {
720 b.SetBytes(int64(len(data)))
721 b.ReportAllocs()
722 for b.Loop() {
723 Detect(data)
724 }
725 })
726 }
727 }
728 }
729
730 func FuzzDetect(f *testing.F) {
731 for _, secSize := range testSecSizes {
732 // MSI installer (root-storage CLSID).
733 f.Add(makeCDF(secSize, msiCLSID, "", nil))
734
735 // Detection from the summary stream's application name, both
736 // ASCII and UTF-16LE encodings.
737 for _, wide := range []bool{false, true} {
738 f.Add(makeCDF(secSize, nil, "\x05SummaryInformation",
739 summaryStream("Microsoft Office Word", wide)))
740 f.Add(makeCDF(secSize, nil, "\x05DocumentSummaryInformation",
741 summaryStream("Microsoft Excel", wide)))
742 }
743
744 // Detection from sibling entry names when the app name is unknown.
745 f.Add(makeCDF(secSize, nil, "\x05SummaryInformation",
746 summaryStream("Unknown Application", false),
747 entrySpec{"WordDocument", dirTypeUserStream}))
748
749 // Summary present but no recognizable names -> Generic fallback.
750 f.Add(makeCDF(secSize, nil, "\x05SummaryInformation",
751 summaryStream("Unknown Application", false),
752 entrySpec{"Contents", dirTypeUserStream}))
753
754 // Detection from section/entry names with no summary stream.
755 f.Add(makeCDF(secSize, nil, "", nil, entrySpec{"EncryptedPackage", dirTypeUserStream}))
756 f.Add(makeCDF(secSize, nil, "", nil, entrySpec{"Workbook", dirTypeUserStream}))
757 f.Add(makeCDF(secSize, nil, "", nil, entrySpec{"PowerPoint Document", dirTypeUserStream}))
758 f.Add(makeCDF(secSize, nil, "", nil, entrySpec{"__properties_version1.0", dirTypeUserStream}))
759
760 // Generic OLE storage with no distinctive entries.
761 f.Add(makeCDF(secSize, nil, "", nil, entrySpec{"Contents", dirTypeUserStream}))
762 }
763
764 // A bare header with no body and a non-CDF input.
765 f.Add(testHeader(512, 1, -2, 0, []int32{0}))
766
767 f.Fuzz(func(t *testing.T, data []byte) {
768 if len(data) == 0 {
769 return
770 }
771 // Seed the rng from input so the truncation points are deterministic.
772 h := fnv.New64a()
773 h.Write(data)
774 rng := rand.New(rand.NewPCG(h.Sum64(), 0))
775 // Truncate the data at random offsets. Truncating on each offset is
776 // too expensive.
777 for i := 0; i < 100; i++ {
778 j := rng.IntN(len(data))
779 _ = Detect(data[:j]) // must not panic on any input
780 }
781 })
782 }