Debian Codegraph @

archive50.go

raw symbols SCIP
1 package rardecode
2
3 import (
4 "bytes"
5 "crypto/hmac"
6 "crypto/sha256"
7 "errors"
8 "hash"
9 "hash/crc32"
10 "io"
11 "math/bits"
12 "slices"
13 "time"
14 )
15
16 const (
17 // block types
18 block5Arc = 1
19 block5File = 2
20 // block5Service = 3
21 block5Encrypt = 4
22 block5End = 5
23
24 // block flags
25 block5HasExtra = 0x0001
26 block5HasData = 0x0002
27 block5DataNotFirst = 0x0008
28 block5DataNotLast = 0x0010
29
30 // end block flags
31 endArc5NotLast = 0x0001
32
33 // archive encryption block flags
34 enc5CheckPresent = 0x0001 // password check data is present
35
36 // main archive block flags
37 arc5MultiVol = 0x0001
38 arc5VolNum = 0x0002
39 arc5Solid = 0x0004
40
41 // file block flags
42 file5IsDir = 0x0001
43 file5HasUnixMtime = 0x0002
44 file5HasCRC32 = 0x0004
45 file5UnpSizeUnknown = 0x0008
46
47 // file compression flags
48 file5CompAlgorithm = 0x0000003F
49 file5CompSolid = 0x00000040
50 file5CompMethod = 0x00000380
51 file5CompDictSize = 0x00007C00
52 file5CompDictFract = 0x000F8000
53 file5CompV5Compat = 0x00100000
54
55 // host os
56 file5HostOSWindows = 0
57 file5HostOSUnix = 1
58
59 // file header extra types
60 file5ExtraCrypt = 1
61 file5ExtraHash = 2
62 file5ExtraTime = 3
63 file5ExtraVersion = 4
64 file5ExtraRedirect = 5
65 file5ExtraOwner = 6
66
67 // file encryption record flags
68 file5ExtraCryptCheckPresent = 0x0001 // password check data is present
69 file5ExtraCryptUseMac = 0x0002 // use MAC instead of plain checksum
70
71 // precision time flags
72 file5ExtraTimeIsUnixTime = 0x01 // is unix time_t
73 file5ExtraTimeHasMTime = 0x02 // has modification time
74 file5ExtraTimeHasCTime = 0x04 // has creation time
75 file5ExtraTimeHasATime = 0x08 // has access time
76 file5ExtraTimeHasUnixNS = 0x10 // unix nanosecond time format
77
78 file5ExtraRedirDir = 0x1 // redirection target is a directory
79
80 file5ExtraUnixOwnerHasUserName = 0x01 // has unix user name string
81 file5ExtraUnixOwnerHasGroupName = 0x02 // has unix group name string
82 file5ExtraUnixOwnerHasUserID = 0x04 // has unix user id
83 file5ExtraUnixOwnerHasGroupID = 0x06 // has unix group id
84
85 maxPathSize = 0x10000
86
87 cacheSize50 = 4
88 maxPbkdf2Salt = 64
89 pwCheckSize = 8
90 maxKdfCount = 24
91
92 maxDictSize = 0x1000000000 // maximum dictionary size 64GB
93 maxHeaderSize = 0x200000 // maximum header size: https://www.rarlab.com/technote.htm
94 )
95
96 var (
97 ErrBadPassword = errors.New("rardecode: incorrect password")
98 ErrCorruptEncryptData = errors.New("rardecode: corrupt encryption data")
99 ErrUnknownEncryptMethod = errors.New("rardecode: unknown encryption method")
100 ErrPlatformIntSize = errors.New("rardecode: platform integer size too small")
101 ErrDictionaryTooLarge = errors.New("rardecode: decode dictionary too large")
102 ErrBadVolumeNumber = errors.New("rardecode: bad volume number")
103 ErrNoArchiveBlock = errors.New("rardecode: missing archive block")
104 ErrBadBlockHeader = errors.New("rardecode: bad block header")
105 )
106
107 type extra struct {
108 ftype uint64 // field type
109 data readBuf // field data
110 }
111
112 type blockHeader50 struct {
113 htype uint64 // block type
114 flags uint64
115 data readBuf // block header data
116 extra []extra // extra fields
117 dataSize int64 // size of block data
118 }
119
120 // leHash32 wraps a hash.Hash32 to return the result of Sum in little
121 // endian format.
122 type leHash32 struct {
123 hash.Hash32
124 }
125
126 func (h leHash32) Sum(b []byte) []byte {
127 s := h.Sum32()
128 return append(b, byte(s), byte(s>>8), byte(s>>16), byte(s>>24))
129 }
130
131 func newLittleEndianCRC32() hash.Hash {
132 return leHash32{crc32.NewIEEE()}
133 }
134
135 // archive50 implements archiveBlockReader for RAR 5 file format archives
136 type archive50 struct {
137 pass []byte
138 blockKey []byte // key used to encrypt blocks
139 multi bool // archive is multi-volume
140 solid bool // is a solid archive
141 keyCache [cacheSize50]struct { // encryption key cache
142 kdfCount int
143 salt []byte
144 keys [][]byte
145 }
146 }
147
148 func (a *archive50) useOldNaming() bool {
149 return false
150 }
151
152 // calcKeys50 calculates the keys used in RAR 5 archive processing.
153 // The returned slice of byte slices contains 3 keys.
154 // Key 0 is used for block or file decryption.
155 // Key 1 is optionally used for file checksum calculation.
156 // Key 2 is optionally used for password checking.
157 func calcKeys50(pass, salt []byte, kdfCount int) [][]byte {
158 if len(salt) > maxPbkdf2Salt {
159 salt = salt[:maxPbkdf2Salt]
160 }
161 keys := make([][]byte, 3)
162 if len(keys) == 0 {
163 return keys
164 }
165
166 prf := hmac.New(sha256.New, pass)
167 _, _ = prf.Write(salt)
168 _, _ = prf.Write([]byte{0, 0, 0, 1})
169
170 t := prf.Sum(nil)
171 u := slices.Clone(t)
172
173 kdfCount--
174
175 for i, iter := range []int{kdfCount, 16, 16} {
176 for iter > 0 {
177 prf.Reset()
178 _, _ = prf.Write(u)
179 u = prf.Sum(u[:0])
180 for j := range u {
181 t[j] ^= u[j]
182 }
183 iter--
184 }
185 keys[i] = slices.Clone(t)
186 }
187
188 pwcheck := keys[2]
189 for i, v := range pwcheck[pwCheckSize:] {
190 pwcheck[i&(pwCheckSize-1)] ^= v
191 }
192 pwcheck = pwcheck[:pwCheckSize]
193 // add checksum to end of pwcheck
194 sum := sha256.Sum256(pwcheck)
195 pwcheck = append(pwcheck, sum[:4]...)
196 keys[2] = pwcheck
197
198 return keys
199 }
200
201 // getKeys returns the the corresponding encryption keys for the given kdfcount and salt.
202 // It will check the password if check is provided.
203 func (a *archive50) getKeys(kdfCount int, salt, check []byte) ([][]byte, error) {
204 var keys [][]byte
205
206 if kdfCount > maxKdfCount {
207 return nil, ErrCorruptEncryptData
208 }
209 kdfCount = 1 << uint(kdfCount)
210
211 // check cache of keys for match
212 for _, v := range a.keyCache {
213 if kdfCount == v.kdfCount && bytes.Equal(salt, v.salt) {
214 keys = v.keys
215 break
216 }
217 }
218 if keys == nil {
219 // not found, calculate keys
220 keys = calcKeys50(a.pass, salt, kdfCount)
221
222 // store in cache
223 copy(a.keyCache[1:], a.keyCache[:])
224 a.keyCache[0].kdfCount = kdfCount
225 a.keyCache[0].salt = slices.Clone(salt)
226 a.keyCache[0].keys = keys
227 }
228
229 // check password
230 if check != nil && !bytes.Equal(check, keys[2]) {
231 return nil, ErrBadPassword
232 }
233 return keys, nil
234 }
235
236 // parseFileEncryptionRecord processes the optional file encryption record from a file header.
237 func (a *archive50) parseFileEncryptionRecord(b readBuf, f *fileBlockHeader) error {
238 f.Encrypted = true
239 if ver := b.uvarint(); ver != 0 {
240 return ErrUnknownEncryptMethod
241 }
242 flags := b.uvarint()
243 if len(b) < 33 {
244 return ErrCorruptEncryptData
245 }
246 kdfCount := int(b.byte())
247 salt := slices.Clone(b.bytes(16))
248 f.iv = slices.Clone(b.bytes(16))
249
250 var check []byte
251 if flags&file5ExtraCryptCheckPresent > 0 {
252 if len(b) < 12 {
253 return ErrCorruptEncryptData
254 }
255 check = slices.Clone(b.bytes(12))
256 }
257 useMac := flags&file5ExtraCryptUseMac > 0
258 // only need to generate keys for first block or
259 // last block if it has an optional hash key
260 if a.pass == nil || !(f.first || (f.last && useMac)) {
261 return nil
262 }
263 keys, err := a.getKeys(kdfCount, salt, check)
264 if err != nil {
265 return err
266 }
267 f.key = keys[0]
268 if useMac {
269 f.hashKey = keys[1]
270 }
271 return nil
272 }
273
274 func readWinFiletime(b *readBuf) (time.Time, error) {
275 if len(*b) < 8 {
276 return time.Time{}, ErrCorruptFileHeader
277 }
278 // 100-nanosecond intervals since January 1, 1601
279 t := b.uint64() - 116444736000000000
280 t *= 100
281 sec, nsec := bits.Div64(0, t, uint64(time.Second))
282 return time.Unix(int64(sec), int64(nsec)), nil
283 }
284
285 func readUnixTime(b *readBuf) (time.Time, error) {
286 if len(*b) < 4 {
287 return time.Time{}, ErrCorruptFileHeader
288 }
289 return time.Unix(int64(b.uint32()), 0), nil
290 }
291
292 func readUnixNanoseconds(b *readBuf) (time.Duration, error) {
293 if len(*b) < 4 {
294 return 0, ErrCorruptFileHeader
295 }
296 d := time.Duration(b.uint32() & 0x3fffffff)
297 if d >= time.Second {
298 return 0, ErrCorruptFileHeader
299 }
300 return d, nil
301 }
302
303 // parseFilePrecisionTimeRecord processes the optional high precision time record from a file header.
304 func parseFilePrecisionTimeRecord(b *readBuf, f *fileBlockHeader) error {
305 var err error
306 flags := b.uvarint()
307 isUnixTime := flags&file5ExtraTimeIsUnixTime > 0
308 if flags&file5ExtraTimeHasMTime > 0 {
309 if isUnixTime {
310 f.ModificationTime, err = readUnixTime(b)
311 } else {
312 f.ModificationTime, err = readWinFiletime(b)
313 }
314 if err != nil {
315 return err
316 }
317 }
318 if flags&file5ExtraTimeHasCTime > 0 {
319 if isUnixTime {
320 f.CreationTime, err = readUnixTime(b)
321 } else {
322 f.CreationTime, err = readWinFiletime(b)
323 }
324 if err != nil {
325 return err
326 }
327 }
328 if flags&file5ExtraTimeHasATime > 0 {
329 if isUnixTime {
330 f.AccessTime, err = readUnixTime(b)
331 } else {
332 f.AccessTime, err = readWinFiletime(b)
333 }
334 if err != nil {
335 return err
336 }
337 }
338 if isUnixTime && flags&file5ExtraTimeHasUnixNS > 0 {
339 if flags&file5ExtraTimeHasMTime > 0 {
340 ns, err := readUnixNanoseconds(b)
341 if err != nil {
342 return err
343 }
344 f.ModificationTime = f.ModificationTime.Add(ns)
345 }
346 if flags&file5ExtraTimeHasCTime > 0 {
347 ns, err := readUnixNanoseconds(b)
348 if err != nil {
349 return err
350 }
351 f.CreationTime = f.CreationTime.Add(ns)
352 }
353 if flags&file5ExtraTimeHasATime > 0 {
354 ns, err := readUnixNanoseconds(b)
355 if err != nil {
356 return err
357 }
358 f.AccessTime = f.AccessTime.Add(ns)
359 }
360 }
361 return nil
362 }
363
364 // parseFileRedirectionRecord processes the file redirection record from a file header.
365 func parseFileRedirectionRecord(b *readBuf, f *fileBlockHeader) error {
366 if len(*b) == 0 {
367 return ErrCorruptFileHeader
368 }
369 f.LinkType = byte(b.uvarint())
370 flags := b.uvarint()
371 f.LinkTargetIsDir = flags&file5ExtraRedirDir > 0
372 nameLen := int(b.uvarint())
373 if nameLen > maxPathSize {
374 return ErrCorruptFileHeader
375 }
376 f.LinkTarget = string(b.bytes(nameLen))
377 if len(f.LinkTarget) < nameLen {
378 return ErrCorruptFileHeader
379 }
380 return nil
381 }
382
383 // parseFileOwnerRecord processes the file owner record from a file header.
384 func parseFileOwnerRecord(b *readBuf, f *fileBlockHeader) error {
385 flags := b.uvarint()
386 if flags&file5ExtraUnixOwnerHasUserName > 0 {
387 nameLen := min(int(b.uvarint()), 255)
388 name := string(b.bytes(nameLen))
389 f.UnixOwnerUserName = &name
390 }
391 if flags&file5ExtraUnixOwnerHasGroupName > 0 {
392 nameLen := min(int(b.uvarint()), 255)
393 name := string(b.bytes(nameLen))
394 f.UnixOwnerGroupName = &name
395 }
396 if flags&file5ExtraUnixOwnerHasUserID > 0 {
397 id := b.uvarint()
398 f.UnixOwnerUserID = &id
399 }
400 if flags&file5ExtraUnixOwnerHasGroupID > 0 {
401 id := b.uvarint()
402 f.UnixOwnerGroupID = &id
403 }
404 return nil
405 }
406
407 func (a *archive50) parseFileHeader(h *blockHeader50) (*fileBlockHeader, error) {
408 f := new(fileBlockHeader)
409
410 f.HeaderEncrypted = a.blockKey != nil
411 f.first = h.flags&block5DataNotFirst == 0
412 f.last = h.flags&block5DataNotLast == 0
413
414 flags := h.data.uvarint() // file flags
415 f.IsDir = flags&file5IsDir > 0
416 f.UnKnownSize = flags&file5UnpSizeUnknown > 0
417 f.UnPackedSize = int64(h.data.uvarint())
418 f.PackedSize = h.dataSize
419 f.Attributes = int64(h.data.uvarint())
420 if flags&file5HasUnixMtime > 0 {
421 if len(h.data) < 4 {
422 return nil, ErrCorruptFileHeader
423 }
424 f.ModificationTime = time.Unix(int64(h.data.uint32()), 0)
425 }
426 if flags&file5HasCRC32 > 0 {
427 if len(h.data) < 4 {
428 return nil, ErrCorruptFileHeader
429 }
430 f.sum = slices.Clone(h.data.bytes(4))
431 if f.first {
432 f.hash = newLittleEndianCRC32
433 }
434 }
435
436 flags = h.data.uvarint() // compression flags
437 f.Solid = flags&file5CompSolid > 0
438 f.arcSolid = a.solid
439 method := (flags & file5CompMethod) >> 7 // compression method (0 == none)
440 if f.first && method != 0 {
441 unpackver := flags & file5CompAlgorithm
442 f.winSize = 0x20000 << ((flags & file5CompDictSize) >> 10)
443 switch unpackver {
444 case 0:
445 f.decVer = decode50Ver
446 case 1:
447 if flags&file5CompV5Compat > 0 {
448 f.decVer = decode50Ver
449 } else {
450 f.decVer = decode70Ver
451 }
452 f.winSize += f.winSize / 32 * int64((flags&file5CompDictFract)>>15)
453 default:
454 return nil, ErrUnknownDecoder
455 }
456 }
457 switch h.data.uvarint() {
458 case file5HostOSWindows:
459 f.HostOS = HostOSWindows
460 case file5HostOSUnix:
461 f.HostOS = HostOSUnix
462 default:
463 f.HostOS = HostOSUnknown
464 }
465 nlen := int(h.data.uvarint())
466 if len(h.data) < nlen {
467 return nil, ErrCorruptFileHeader
468 }
469 f.Name = string(h.data.bytes(nlen))
470
471 // parse optional extra records
472 for _, e := range h.extra {
473 var err error
474 switch e.ftype {
475 case file5ExtraCrypt:
476 if encErr := a.parseFileEncryptionRecord(e.data, f); encErr != nil {
477 f.errs = append(f.errs, encErr)
478 }
479 case file5ExtraHash:
480 // TODO: hash
481 case file5ExtraTime:
482 err = parseFilePrecisionTimeRecord(&e.data, f)
483 case file5ExtraVersion:
484 _ = e.data.uvarint() // ignore flags field
485 f.Version = int(e.data.uvarint())
486 case file5ExtraRedirect:
487 err = parseFileRedirectionRecord(&e.data, f)
488 case file5ExtraOwner:
489 err = parseFileOwnerRecord(&e.data, f)
490 }
491 if err != nil {
492 return nil, err
493 }
494 }
495 return f, nil
496 }
497
498 // parseEncryptionBlock calculates the key for block encryption.
499 func (a *archive50) parseEncryptionBlock(b readBuf) error {
500 if a.pass == nil {
501 return ErrArchiveEncrypted
502 }
503 if ver := b.uvarint(); ver != 0 {
504 return ErrUnknownEncryptMethod
505 }
506 flags := b.uvarint()
507 if len(b) < 17 {
508 return ErrCorruptEncryptData
509 }
510 kdfCount := int(b.byte())
511 salt := b.bytes(16)
512
513 var check []byte
514 if flags&enc5CheckPresent > 0 {
515 if len(b) < 12 {
516 return ErrCorruptEncryptData
517 }
518 check = b.bytes(12)
519 }
520
521 keys, err := a.getKeys(kdfCount, salt, check)
522 if err != nil {
523 return err
524 }
525 a.blockKey = keys[0]
526 return nil
527 }
528
529 func (a *archive50) parseArcBlock(h *blockHeader50) int {
530 flags := h.data.uvarint()
531 a.multi = flags&arc5MultiVol > 0
532 a.solid = flags&arc5Solid > 0
533 if flags&arc5VolNum > 0 {
534 return int(h.data.uvarint())
535 }
536 return -1
537 }
538
539 func (a *archive50) readBlockHeader(r byteReader) (*blockHeader50, error) {
540 if a.blockKey != nil {
541 // block is encrypted
542 if a.pass == nil {
543 return nil, ErrArchiveEncrypted
544 }
545 iv := make([]byte, 16)
546 _, err := io.ReadFull(r, iv)
547 if err != nil {
548 return nil, err
549 }
550 r, err = newAesDecryptReader(r, a.blockKey, iv)
551 if err != nil {
552 return nil, err
553 }
554 }
555 // find the header size
556 sizeBuf := make([]byte, 7)
557 _, err := io.ReadFull(r, sizeBuf)
558 if err != nil {
559 return nil, err
560 }
561 b := readBuf(sizeBuf)
562 crc := b.uint32()
563
564 // Check if header size is valid
565 size := int(b.uvarint())
566 bufSize := 3 + size - len(b)
567 if bufSize < 4 || size > maxHeaderSize {
568 return nil, ErrBadBlockHeader
569 }
570
571 buf := make([]byte, bufSize)
572 copy(buf, sizeBuf[4:])
573 _, err = io.ReadFull(r, buf[3:])
574 if err != nil {
575 return nil, err
576 }
577
578 // check header crc
579 hash := crc32.NewIEEE()
580 _, _ = hash.Write(buf)
581 if crc != hash.Sum32() {
582 return nil, ErrBadHeaderCRC
583 }
584
585 b = buf[3-len(b):]
586 h := new(blockHeader50)
587 h.htype = b.uvarint()
588 h.flags = b.uvarint()
589
590 var extraSize int
591 if h.flags&block5HasExtra > 0 {
592 extraSize = int(b.uvarint())
593 }
594 if h.flags&block5HasData > 0 {
595 h.dataSize = int64(b.uvarint())
596 }
597 if len(b) < extraSize {
598 return nil, ErrCorruptBlockHeader
599 }
600 h.data = b.bytes(len(b) - extraSize)
601
602 // read header extra records
603 for len(b) > 0 {
604 size = int(b.uvarint())
605 if len(b) < size {
606 return nil, ErrCorruptBlockHeader
607 }
608 data := readBuf(b.bytes(size))
609 ftype := data.uvarint()
610 h.extra = append(h.extra, extra{ftype, data})
611 }
612
613 return h, nil
614 }
615
616 func (a *archive50) mustReadBlockHeader(r byteReader) (*blockHeader50, error) {
617 h, err := a.readBlockHeader(r)
618 if err != nil {
619 if err == io.EOF {
620 err = io.ErrUnexpectedEOF
621 }
622 return nil, err
623 }
624 return h, nil
625 }
626
627 func (a *archive50) init(br *bufVolumeReader) (int, error) {
628 a.blockKey = nil // reset encryption when opening new volume file
629 volnum := -1
630 h, err := a.mustReadBlockHeader(br)
631 if err != nil {
632 return volnum, err
633 }
634 if h.htype == block5Encrypt {
635 err = a.parseEncryptionBlock(h.data)
636 if err != nil {
637 return volnum, err
638 }
639 h, err = a.mustReadBlockHeader(br)
640 if err != nil {
641 return volnum, err
642 }
643 }
644 if h.htype != block5Arc {
645 return volnum, ErrNoArchiveBlock
646 }
647 volnum = a.parseArcBlock(h)
648 return volnum, nil
649 }
650
651 // nextBlock advances to the next file block in the archive
652 func (a *archive50) nextBlock(br *bufVolumeReader) (*fileBlockHeader, error) {
653 for {
654 // get next block header
655 h, err := a.mustReadBlockHeader(br)
656 if err != nil {
657 return nil, err
658 }
659 switch h.htype {
660 case block5File:
661 return a.parseFileHeader(h)
662 case block5End:
663 flags := h.data.uvarint()
664 if flags&endArc5NotLast == 0 || !a.multi {
665 return nil, io.EOF
666 }
667 return nil, ErrMultiVolume
668 default:
669 if h.dataSize > 0 {
670 err = br.Discard(h.dataSize) // skip over block data
671 if err != nil {
672 return nil, err
673 }
674 }
675 }
676 }
677 }
678
679 // newArchive50 creates a new archiveBlockReader for a Version 5 archive.
680 func newArchive50(password *string) *archive50 {
681 a := &archive50{}
682 if password != nil {
683 a.pass = []byte(*password)
684 }
685 return a
686 }