Repository navigation
Expand file tree
/
Copy pathole.go
More file actions
270 lines (259 loc) · 7.51 KB
/
Copy pathole.go
File metadata and controls
270 lines (259 loc) · 7.51 KB
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
package xlsreader
import (
"bytes"
"encoding/binary"
"fmt"
"strings"
)
const (
endOfChain uint32 = 0xFFFFFFFE
freeSector uint32 = 0xFFFFFFFF
fatSector uint32 = 0xFFFFFFFD
difatSector uint32 = 0xFFFFFFFC
sectorSize = 512
)
var le = binary.LittleEndian
var oleSignature = []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}
type compoundFile struct {
data []byte
sectors int
fat []uint32
used []bool
root []byte
workbook []byte
summary []byte
miniBytes []byte
miniStream []byte
miniUsed map[uint32]bool
miniReady bool
}
func openCompound(data []byte) (*compoundFile, error) {
if len(data) < 8 || !bytes.Equal(data[:8], oleSignature) {
return nil, unsupported("expected OLE/CFB .xls (not XLSX, CSV, or raw BIFF)")
}
if len(data) < 512 {
return nil, invalid("truncated OLE header")
}
if le.Uint16(data[26:]) != 3 || le.Uint16(data[30:]) != 9 {
return nil, unsupported("only CFB version 3 with 512-byte sectors is supported")
}
if le.Uint16(data[28:]) != 0xFFFE || le.Uint16(data[32:]) != 6 || le.Uint32(data[56:]) != 4096 {
return nil, invalid("invalid CFB byte order, mini sector size, or cutoff")
}
if len(data)%512 != 0 || len(data) < 1536 {
return nil, invalid("truncated OLE sectors")
}
c := &compoundFile{data: data, sectors: len(data)/512 - 1}
c.used = make([]bool, c.sectors)
fatCount, difatCount := le.Uint32(data[44:]), le.Uint32(data[72:])
if fatCount == 0 || uint64(fatCount) > uint64(c.sectors) || uint64(difatCount) > uint64(c.sectors) {
return nil, invalid("invalid FAT/DIFAT count")
}
ids := make([]uint32, 0)
addFAT := func(id uint32) error {
if id == freeSector {
return nil
}
if uint64(id) >= uint64(c.sectors) || c.used[id] || len(ids) >= int(fatCount) {
return invalid("invalid or duplicate FAT sector")
}
c.used[id] = true
ids = append(ids, id)
return nil
}
for pos := 76; pos < 512; pos += 4 {
if err := addFAT(le.Uint32(data[pos:])); err != nil {
return nil, err
}
}
next := le.Uint32(data[68:])
difatIDs := make([]uint32, 0)
for i := uint32(0); i < difatCount; i++ {
if uint64(next) >= uint64(c.sectors) || c.used[next] {
return nil, invalid("invalid or cyclic DIFAT chain")
}
c.used[next] = true
difatIDs = append(difatIDs, next)
block := c.sector(next)
for pos := 0; pos < 508; pos += 4 {
if err := addFAT(le.Uint32(block[pos:])); err != nil {
return nil, err
}
}
next = le.Uint32(block[508:])
}
if next != endOfChain || len(ids) != int(fatCount) {
return nil, invalid("DIFAT length does not match header")
}
for _, id := range ids {
block := c.sector(id)
for pos := 0; pos < 512; pos += 4 {
c.fat = append(c.fat, le.Uint32(block[pos:]))
}
}
if len(c.fat) < c.sectors {
return nil, invalid("FAT does not cover all sectors")
}
for _, id := range ids {
if c.fat[id] != fatSector {
return nil, invalid("FAT sector marker missing")
}
}
for _, id := range difatIDs {
if c.fat[id] != difatSector {
return nil, invalid("DIFAT sector marker missing")
}
}
directory, err := c.chain(le.Uint32(data[48:]), -1)
if err != nil {
return nil, fmt.Errorf("directory: %w", err)
}
if len(directory) < 128 || directory[66] != 5 {
return nil, invalid("missing root directory entry")
}
root := directory[:128]
c.root = root
// Walk only siblings of the root's children: nested embedded workbooks are
// not substitutes for the document's own Workbook stream.
stack := []uint32{le.Uint32(root[76:])}
visited := make(map[uint32]bool)
for len(stack) > 0 {
id := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if id == freeSector {
continue
}
if uint64(id) >= uint64(len(directory)/128) || visited[id] {
return nil, invalid("invalid or cyclic directory tree")
}
visited[id] = true
entry := directory[int(id)*128 : int(id+1)*128]
if entry[66] != 1 && entry[66] != 2 {
return nil, invalid("invalid directory child type")
}
stack = append(stack, le.Uint32(entry[68:]), le.Uint32(entry[72:]))
length := int(le.Uint16(entry[64:]))
if length < 2 || length > 64 || length%2 != 0 || le.Uint16(entry[length-2:]) != 0 {
return nil, invalid("invalid directory name")
}
name, err := decodeUTF16Bytes(entry[:length-2])
if err != nil {
return nil, err
}
if entry[66] == 2 && (strings.EqualFold(name, "Workbook") || strings.EqualFold(name, "Book")) {
if c.workbook != nil {
return nil, invalid("multiple workbook streams")
}
c.workbook = entry
}
if entry[66] == 2 && strings.EqualFold(name, "\x05SummaryInformation") {
if c.summary != nil {
return nil, invalid("multiple summary streams")
}
c.summary = entry
}
}
if c.workbook == nil {
return nil, invalid("Workbook stream not found")
}
return c, nil
}
func (c *compoundFile) readStream(entry []byte) ([]byte, error) {
size, err := streamSize(entry, len(c.data))
if err != nil {
return nil, err
}
if size == 0 {
return []byte{}, nil
}
start := le.Uint32(entry[116:])
if size >= 4096 {
return c.chain(start, size)
}
if err := c.loadMiniStream(); err != nil {
return nil, err
}
result := make([]byte, 0, size)
for remaining := size; remaining > 0; remaining -= 64 {
if uint64(start) >= uint64(len(c.miniBytes)/4) || uint64(start) >= uint64(len(c.miniStream)/64) || c.miniUsed[start] {
return nil, invalid("invalid, cyclic, or overlapping mini FAT chain")
}
c.miniUsed[start] = true
take := 64
if remaining < take {
take = remaining
}
offset := int(start) * 64
result = append(result, c.miniStream[offset:offset+take]...)
start = le.Uint32(c.miniBytes[int(start)*4:])
}
if start != endOfChain {
return nil, invalid("mini stream chain exceeds declared size")
}
return result, nil
}
func (c *compoundFile) loadMiniStream() error {
if c.miniReady {
return nil
}
data := c.data
miniCount := le.Uint32(data[64:])
if uint64(miniCount) > uint64(c.sectors) {
return invalid("invalid mini FAT size")
}
miniBytes, err := c.chain(le.Uint32(data[60:]), int(miniCount)*512)
if err != nil {
return err
}
rootSize, err := streamSize(c.root, len(data))
if err != nil {
return err
}
miniStream, err := c.chain(le.Uint32(c.root[116:]), rootSize)
if err != nil {
return err
}
if rootSize%64 != 0 {
return invalid("misaligned mini stream")
}
c.miniBytes, c.miniStream = miniBytes, miniStream
c.miniUsed = make(map[uint32]bool)
c.miniReady = true
return nil
}
func streamSize(entry []byte, fileSize int) (int, error) {
size := le.Uint64(entry[120:])
if size > uint64(fileSize) {
return 0, invalid("stream size exceeds file size")
}
return int(size), nil
}
// sector is called only after the sector number has been validated.
func (c *compoundFile) sector(id uint32) []byte {
offset := (int(id) + 1) * 512
return c.data[offset : offset+512]
}
// chain reads a normal FAT chain. size == -1 means an unknown directory size.
// A shared allocation map catches loops and overlapping metadata/data streams.
func (c *compoundFile) chain(start uint32, size int) ([]byte, error) {
result := make([]byte, 0)
for start != endOfChain {
if uint64(start) >= uint64(c.sectors) || c.used[start] {
return nil, invalid("invalid, cyclic, or overlapping FAT chain")
}
if size >= 0 && len(result) >= size {
return nil, invalid("FAT chain exceeds declared stream size")
}
c.used[start] = true
block := c.sector(start)
if size >= 0 && size-len(result) < 512 {
block = block[:size-len(result)]
}
result = append(result, block...)
start = c.fat[start]
}
if size >= 0 && len(result) != size {
return nil, invalid("truncated FAT stream")
}
return result, nil
}