Debian Codegraph @

archive15.go

raw symbols SCIP
1 package rardecode
2
3 import (
4 "bytes"
5 "crypto/sha1"
6 "errors"
7 "hash/crc32"
8 "io"
9 "slices"
10 "strconv"
11 "strings"
12 "time"
13 "unicode/utf16"
14 )
15
16 const (
17 // block types
18 blockArc = 0x73
19 blockFile = 0x74
20 blockComment = 0x75
21 blockService = 0x7a
22 blockEnd = 0x7b
23
24 // block flags
25 blockHasData = 0x8000
26
27 // archive block flags
28 arcVolume = 0x0001
29 arcComment = 0x0002
30 arcSolid = 0x0008
31 arcNewNaming = 0x0010
32 arcEncrypted = 0x0080
33
34 // file block flags
35 fileSplitBefore = 0x0001
36 fileSplitAfter = 0x0002
37 fileEncrypted = 0x0004
38 fileSolid = 0x0010
39 fileWindowMask = 0x00e0
40 fileLargeData = 0x0100
41 fileUnicode = 0x0200
42 fileSalt = 0x0400
43 fileVersion = 0x0800
44 fileExtTime = 0x1000
45
46 // end block flags
47 endArcNotLast = 0x0001
48
49 saltSize = 8 // size of salt for calculating AES keys
50 cacheSize30 = 4 // number of AES keys to cache
51 hashRounds = 0x40000
52 )
53
54 var (
55 ErrUnsupportedDecoder = errors.New("rardecode: unsupported decoder version")
56 )
57
58 type blockHeader15 struct {
59 htype byte // block header type
60 flags uint16
61 data readBuf // header data
62 dataSize int64 // size of extra block data
63 }
64
65 // archive15 implements archiveBlockReader for RAR 1.5 file format archives
66 type archive15 struct {
67 multi bool // archive is multi-volume
68 solid bool // archive is a solid archive
69 encrypted bool
70 oldNaming bool
71 pass []uint16 // password in UTF-16
72 keyCache [cacheSize30]struct { // cache of previously calculated decryption keys
73 salt []byte
74 key []byte
75 iv []byte
76 }
77 }
78
79 func (a *archive15) useOldNaming() bool {
80 return a.oldNaming
81 }
82
83 // Calculates the key and iv for AES decryption given a password and salt.
84 func calcAes30Params(pass []uint16, salt []byte) (key, iv []byte) {
85 p := make([]byte, 0, len(pass)*2+len(salt))
86 for _, v := range pass {
87 p = append(p, byte(v), byte(v>>8))
88 }
89 p = append(p, salt...)
90
91 hash := sha1.New()
92 iv = make([]byte, 16)
93 s := make([]byte, hash.Size())
94 b := s[:3]
95 for i := 0; i < hashRounds; i++ {
96 // ignore hash Write errors, should always succeed
97 _, _ = hash.Write(p)
98 b[0], b[1], b[2] = byte(i), byte(i>>8), byte(i>>16)
99 _, _ = hash.Write(b)
100 if i%(hashRounds/16) == 0 {
101 s = hash.Sum(s[:0])
102 iv[i/(hashRounds/16)] = s[4*4+3]
103 }
104 }
105 key = hash.Sum(s[:0])
106 key = key[:16]
107
108 for k := key; len(k) >= 4; k = k[4:] {
109 k[0], k[1], k[2], k[3] = k[3], k[2], k[1], k[0]
110 }
111 return key, iv
112 }
113
114 // parseDosTime converts a 32bit DOS time value to time.Time
115 func parseDosTime(t uint32) time.Time {
116 n := int(t)
117 sec := n & 0x1f << 1
118 min := n >> 5 & 0x3f
119 hr := n >> 11 & 0x1f
120 day := n >> 16 & 0x1f
121 mon := time.Month(n >> 21 & 0x0f)
122 yr := n>>25&0x7f + 1980
123 return time.Date(yr, mon, day, hr, min, sec, 0, time.Local)
124 }
125
126 // decodeName decodes a non-unicode filename from a file header.
127 func decodeName(buf []byte) string {
128 before, after, ok := bytes.Cut(buf, []byte{0})
129 if !ok {
130 return string(buf) // filename is UTF-8
131 }
132
133 name := before
134 encName := readBuf(after)
135 if len(encName) < 2 {
136 return "" // invalid encoding
137 }
138 highByte := uint16(encName.byte()) << 8
139 flags := encName.byte()
140 flagBits := 8
141 var wchars []uint16 // decoded characters are UTF-16
142 for len(wchars) < len(name) && len(encName) > 0 {
143 if flagBits == 0 {
144 flags = encName.byte()
145 flagBits = 8
146 if len(encName) == 0 {
147 break
148 }
149 }
150 switch flags >> 6 {
151 case 0:
152 wchars = append(wchars, uint16(encName.byte()))
153 case 1:
154 wchars = append(wchars, uint16(encName.byte())|highByte)
155 case 2:
156 if len(encName) < 2 {
157 break
158 }
159 wchars = append(wchars, encName.uint16())
160 case 3:
161 n := encName.byte()
162 b := name[len(wchars):]
163 if l := int(n&0x7f) + 2; l < len(b) {
164 b = b[:l]
165 }
166 if n&0x80 > 0 {
167 if len(encName) < 1 {
168 break
169 }
170 ec := encName.byte()
171 for _, c := range b {
172 wchars = append(wchars, uint16(c+ec)|highByte)
173 }
174 } else {
175 for _, c := range b {
176 wchars = append(wchars, uint16(c))
177 }
178 }
179 }
180 flags <<= 2
181 flagBits -= 2
182 }
183 return string(utf16.Decode(wchars))
184 }
185
186 // readExtTimes reads and parses the optional extra time field from the file header.
187 func readExtTimes(f *fileBlockHeader, b *readBuf) {
188 if len(*b) < 2 {
189 return // invalid, not enough data
190 }
191 flags := b.uint16()
192
193 ts := []*time.Time{&f.ModificationTime, &f.CreationTime, &f.AccessTime}
194
195 for i, t := range ts {
196 n := flags >> uint((3-i)*4)
197 if n&0x8 == 0 {
198 continue
199 }
200 if i != 0 { // ModificationTime already read so skip
201 if len(*b) < 4 {
202 return // invalid, not enough data
203 }
204 *t = parseDosTime(b.uint32())
205 }
206 if n&0x4 > 0 {
207 *t = t.Add(time.Second)
208 }
209 n &= 0x3
210 if n == 0 {
211 continue
212 }
213 if len(*b) < int(n) {
214 return // invalid, not enough data
215 }
216 // add extra time data in 100's of nanoseconds
217 d := time.Duration(0)
218 for j := 3 - n; j < n; j++ {
219 d |= time.Duration(b.byte()) << (j * 8)
220 }
221 d *= 100
222 *t = t.Add(d)
223 }
224 }
225
226 func (a *archive15) getKeys(salt []byte) (key, iv []byte) {
227 // check cache of keys
228 for _, v := range a.keyCache {
229 if bytes.Equal(v.salt[:], salt) {
230 return v.key, v.iv
231 }
232 }
233 key, iv = calcAes30Params(a.pass, salt)
234
235 // save a copy in the cache
236 copy(a.keyCache[1:], a.keyCache[:])
237 a.keyCache[0].salt = slices.Clone(salt) // copy so byte slice can be reused
238 a.keyCache[0].key = key
239 a.keyCache[0].iv = iv
240
241 return key, iv
242 }
243
244 func (a *archive15) parseFileHeader(h *blockHeader15) (*fileBlockHeader, error) {
245 f := new(fileBlockHeader)
246
247 f.first = h.flags&fileSplitBefore == 0
248 f.last = h.flags&fileSplitAfter == 0
249
250 f.Solid = h.flags&fileSolid > 0
251 f.arcSolid = a.solid
252 f.Encrypted = h.flags&fileEncrypted > 0
253 f.HeaderEncrypted = a.encrypted
254 f.IsDir = h.flags&fileWindowMask == fileWindowMask
255 if !f.IsDir {
256 f.winSize = 0x10000 << ((h.flags & fileWindowMask) >> 5)
257 }
258
259 b := h.data
260 if len(b) < 21 {
261 return nil, ErrCorruptFileHeader
262 }
263
264 f.PackedSize = h.dataSize
265 f.UnPackedSize = int64(b.uint32())
266 f.HostOS = b.byte() + 1
267 if f.HostOS > HostOSBeOS {
268 f.HostOS = HostOSUnknown
269 }
270 f.sum = slices.Clone(b.bytes(4))
271
272 f.ModificationTime = parseDosTime(b.uint32())
273 unpackver := b.byte() // decoder version
274 method := b.byte() - 0x30 // decryption method
275 namesize := int(b.uint16())
276 f.Attributes = int64(b.uint32())
277 if h.flags&fileLargeData > 0 {
278 if len(b) < 8 {
279 return nil, ErrCorruptFileHeader
280 }
281 _ = b.uint32() // already read large PackedSize in readBlockHeader
282 f.UnPackedSize |= int64(b.uint32()) << 32
283 f.UnKnownSize = f.UnPackedSize == -1
284 } else if int32(f.UnPackedSize) == -1 {
285 f.UnKnownSize = true
286 f.UnPackedSize = -1
287 }
288 if len(b) < namesize {
289 return nil, ErrCorruptFileHeader
290 }
291 name := b.bytes(namesize)
292 if h.flags&fileUnicode == 0 {
293 f.Name = string(name)
294 } else {
295 f.Name = decodeName(name)
296 }
297 // Rar 4.x uses '\' as file separator
298 f.Name = strings.Replace(f.Name, "\\", "/", -1)
299
300 if h.flags&fileVersion > 0 {
301 // file version is stored as ';n' appended to file name
302 i := strings.LastIndex(f.Name, ";")
303 if i > 0 {
304 j, err := strconv.Atoi(f.Name[i+1:])
305 if err == nil && j >= 0 {
306 f.Version = j
307 f.Name = f.Name[:i]
308 }
309 }
310 }
311
312 var salt []byte
313 if h.flags&fileSalt > 0 {
314 if len(b) < saltSize {
315 return nil, ErrCorruptFileHeader
316 }
317 salt = slices.Clone(b.bytes(saltSize))
318 }
319 if h.flags&fileExtTime > 0 {
320 readExtTimes(f, &b)
321 }
322
323 if !f.first {
324 return f, nil
325 }
326 // fields only needed for first block in a file
327 if f.Encrypted && len(salt) == saltSize && a.pass != nil {
328 f.key, f.iv = a.getKeys(salt)
329 }
330 f.hash = newLittleEndianCRC32
331 if method != 0 {
332 switch unpackver {
333 case 15:
334 return nil, ErrUnsupportedDecoder
335 case 20, 26:
336 f.decVer = decode20Ver
337 case 29:
338 f.decVer = decode29Ver
339 default:
340 return nil, ErrUnknownDecoder
341 }
342 }
343 return f, nil
344 }
345
346 func (a *archive15) parseArcBlock(h *blockHeader15) error {
347 a.encrypted = h.flags&arcEncrypted > 0
348 a.multi = h.flags&arcVolume > 0
349 a.oldNaming = h.flags&arcNewNaming == 0
350 a.solid = h.flags&arcSolid > 0
351 if a.encrypted && a.pass == nil {
352 return ErrArchiveEncrypted
353 }
354 return nil
355 }
356
357 // readBlockHeader returns the next block header in the archive.
358 // It will return io.EOF if there were no bytes read.
359 func (a *archive15) readBlockHeader(r byteReader) (*blockHeader15, error) {
360 if a.encrypted {
361 if a.pass == nil {
362 return nil, ErrArchiveEncrypted
363 }
364 salt := make([]byte, saltSize)
365 _, err := io.ReadFull(r, salt)
366 if err != nil {
367 return nil, err
368 }
369 key, iv := a.getKeys(salt)
370 r, err = newAesDecryptReader(r, key, iv)
371 if err != nil {
372 return nil, err
373 }
374 }
375 sizeBuf := make([]byte, 7)
376 _, err := io.ReadFull(r, sizeBuf)
377 if err != nil {
378 if err == io.EOF && a.encrypted {
379 err = io.ErrUnexpectedEOF
380 }
381 return nil, err
382 }
383 b := readBuf(sizeBuf)
384 crc := b.uint16()
385 h := new(blockHeader15)
386 h.htype = b.byte()
387 h.flags = b.uint16()
388 size := int(b.uint16())
389 if h.htype == blockArc && h.flags&arcComment > 0 {
390 // comment block embedded into archive block
391 if size < 13 {
392 return nil, ErrCorruptBlockHeader
393 }
394 size = 13
395 } else if size < 7 {
396 return nil, ErrCorruptBlockHeader
397 }
398
399 h.data = make([]byte, size)
400 copy(h.data, sizeBuf)
401 _, err = io.ReadFull(r, h.data[7:])
402 if err != nil {
403 if err == io.EOF {
404 err = io.ErrUnexpectedEOF
405 }
406 return nil, err
407 }
408 hash := crc32.NewIEEE()
409 if h.htype == blockComment {
410 if size < 13 {
411 return nil, ErrCorruptBlockHeader
412 }
413 _, _ = hash.Write(h.data[2:13])
414 } else {
415 _, _ = hash.Write(h.data[2:])
416 }
417 if crc != uint16(hash.Sum32()) {
418 return nil, ErrBadHeaderCRC
419 }
420 h.data = h.data[7:]
421 if h.flags&blockHasData > 0 {
422 if len(h.data) < 4 {
423 return nil, ErrCorruptBlockHeader
424 }
425 h.dataSize = int64(h.data.uint32())
426 }
427 if (h.htype == blockService || h.htype == blockFile) && h.flags&fileLargeData > 0 {
428 if len(h.data) < 25 {
429 return nil, ErrCorruptBlockHeader
430 }
431 b := h.data[21:25]
432 h.dataSize |= int64(b.uint32()) << 32
433 }
434 return h, nil
435 }
436
437 func (a *archive15) init(br *bufVolumeReader) (int, error) {
438 a.encrypted = false // reset encryption when opening new volume file
439 h, err := a.readBlockHeader(br)
440 if err != nil {
441 if err == io.EOF {
442 err = io.ErrUnexpectedEOF
443 }
444 } else if h.htype != blockArc {
445 err = ErrNoArchiveBlock
446 } else {
447 err = a.parseArcBlock(h)
448 }
449 return -1, err
450 }
451
452 // nextBlock advances to the next file block in the archive
453 func (a *archive15) nextBlock(br *bufVolumeReader) (*fileBlockHeader, error) {
454 for {
455 // could return an io.EOF here as 1.5 archives may not have an end block.
456 h, err := a.readBlockHeader(br)
457 if err != nil {
458 if err == io.EOF {
459 return nil, errVolumeOrArchiveEnd
460 }
461 return nil, err
462 }
463 switch h.htype {
464 case blockFile:
465 return a.parseFileHeader(h)
466 case blockEnd:
467 if h.flags&endArcNotLast == 0 || !a.multi {
468 return nil, io.EOF
469 }
470 return nil, ErrMultiVolume
471 default:
472 if h.dataSize > 0 {
473 err = br.Discard(h.dataSize) // skip over block data
474 if err != nil {
475 return nil, err
476 }
477 }
478 }
479 }
480 }
481
482 // newArchive15 creates a new archiveBlockReader for a Version 1.5 archive
483 func newArchive15(password *string) *archive15 {
484 a := &archive15{}
485 if password != nil {
486 a.pass = utf16.Encode([]rune(*password)) // convert to UTF-16
487 }
488 return a
489 }