Debian Codegraph @

signingblock/signingblock.go

raw symbols SCIP
1 package signingblock
2
3 import (
4 "bytes"
5 "crypto"
6 "crypto/sha256"
7 "crypto/x509"
8 "encoding/binary"
9 "errors"
10 "fmt"
11 "hash"
12 "io"
13 "math"
14 "os"
15 )
16
17 // https://source.android.com/security/apksigning/v2.html
18 // frameworks/base/core/java/android/util/apk/ApkSignatureSchemeV2Verifier.java
19
20 const (
21 eocdRecMinSize = 22
22 eocdRecMagic = 0x06054b50
23 eocdCommentSizeOffset = 20
24 eocdCentralDirSizeOffset = 12
25 eocdCentralDirOffsetOffset = 16
26
27 zip64LocatorSize = 20
28 zip64LocatorMagic = 0x07064b50
29
30 apkSigBlockMinSize = 32
31 apkSigBlockMagicHi = 0x3234206b636f6c42
32 apkSigBlockMagicLo = 0x20676953204b5041
33
34 blockIdVerityPadding = 0x42726577
35 blockIdSchemeV2 = 0x7109871a
36 blockIdSchemeV3 = 0xf05368c0
37 blockIdFrosting = 0x2146444e
38
39 schemeIdV1 = 1
40 schemeIdV2 = 2
41 schemeIdV3 = 3
42
43 maxChunkSize = 1024 * 1024
44
45 sdkVersionN = 24
46 sdkVersionP = 28
47 )
48
49 var (
50 errNoSigningBlockSignature = errors.New("This apk does not have signing block signature")
51 errEocdNotFound = errors.New("EOCD record not found.")
52 )
53
54 type signatureBlockScheme interface {
55 parseSigners(block *bytes.Buffer, contentDigests map[crypto.Hash][]byte, result *VerificationResult)
56 finalizeResult(minSdkVersion, maxSdkVersion int32, result *VerificationResult)
57 }
58
59 type signingBlock struct {
60 file *os.File
61 fileSize int64
62 eocdOffset int64
63 centralDirOffset int64
64 centralDirSize int64
65 sigBlockOffset int64
66 eocd []byte
67 }
68
69 type signingBlockNotFoundError struct {
70 err error
71 }
72
73 func (e *signingBlockNotFoundError) Error() string {
74 return "Signature Block signature not found: " + e.err.Error()
75 }
76
77 func IsSigningBlockNotFoundError(err error) bool {
78 _, ok := err.(*signingBlockNotFoundError)
79 return ok
80 }
81
82 func VerifySigningBlock(path string, minSdkVersion, maxSdkVersion int32) (res *VerificationResult, magic uint32, err error) {
83 var s *signingBlock
84 s, magic, err = newSigningBlock(path, maxSdkVersion)
85 if err != nil {
86 return
87 }
88 defer s.Close()
89
90 res = &VerificationResult{}
91 blocks, frosting, err := s.findSignatureBlocks(maxSdkVersion, res)
92 if frosting != nil && res.Frosting.Error == nil {
93 res.Frosting.Error = frosting.verifyApk(s.file, s.sigBlockOffset, blocks[schemeIdV2], s.centralDirOffset, s.centralDirSize, s.eocd)
94 }
95 if err != nil {
96 err = &signingBlockNotFoundError{err}
97 return
98 }
99
100 var block []byte
101 var scheme signatureBlockScheme
102 res.SchemeId, scheme, block = s.pickScheme(blocks, minSdkVersion, maxSdkVersion)
103
104 s.verify(scheme, block, minSdkVersion, maxSdkVersion, res)
105 err = res.GetLastError()
106 return
107 }
108
109 func ExtractCerts(path string, minSdkVersion, maxSdkVersion int32) (certs [][]*x509.Certificate, err error) {
110 var s *signingBlock
111 s, _, err = newSigningBlock(path, maxSdkVersion)
112 if err != nil {
113 return
114 }
115 defer s.Close()
116
117 res := &VerificationResult{}
118 blocks, _, err := s.findSignatureBlocks(maxSdkVersion, res)
119 if err != nil {
120 err = &signingBlockNotFoundError{err}
121 return
122 }
123
124 var block []byte
125 var scheme signatureBlockScheme
126 res.SchemeId, scheme, block = s.pickScheme(blocks, minSdkVersion, maxSdkVersion)
127
128 s.extractCerts(scheme, block, res)
129 return res.Certs, res.GetLastError()
130 }
131
132 func newSigningBlock(path string, maxSdkVersion int32) (sblock *signingBlock, magic uint32, err error) {
133 if maxSdkVersion < sdkVersionN {
134 err = &signingBlockNotFoundError{errors.New("unsupported SDK version, requires at least N")}
135 return
136 }
137
138 f, err := os.Open(path)
139 if err != nil {
140 return
141 }
142
143 fi, err := f.Stat()
144 if err != nil {
145 return
146 }
147
148 if fi.Size() < 4 {
149 err = fmt.Errorf("APK file is too short (%d bytes).", fi.Size())
150 return
151 }
152
153 if err = binary.Read(f, binary.LittleEndian, &magic); err != nil {
154 err = fmt.Errorf("Failed to read APK magic: %s", err.Error())
155 return
156 }
157
158 sblock = &signingBlock{
159 file: f,
160 fileSize: fi.Size(),
161 }
162 return
163 }
164
165 func (s *signingBlock) Close() error {
166 return s.file.Close()
167 }
168
169 func (s *signingBlock) findEocd() error {
170 if s.fileSize < eocdRecMinSize {
171 return fmt.Errorf("APK file is too short (%d bytes).", s.fileSize)
172 }
173
174 if err := s.findEocdMaxCommentSize(0); err == nil {
175 return nil
176 }
177 return s.findEocdMaxCommentSize(math.MaxUint16)
178 }
179
180 func (s *signingBlock) findEocdMaxCommentSize(maxCommentSize int) error {
181 if maxCommentSize > int(s.fileSize-eocdRecMinSize) {
182 maxCommentSize = int(s.fileSize - eocdRecMinSize)
183 }
184
185 buf := make([]byte, eocdRecMinSize+maxCommentSize)
186 bufOffsetInFile := s.fileSize - int64(len(buf))
187
188 if _, err := s.file.Seek(bufOffsetInFile, io.SeekStart); err != nil {
189 return err
190 }
191
192 if _, err := io.ReadFull(s.file, buf); err != nil {
193 return err
194 }
195
196 maxCommentSize = len(buf) - eocdRecMinSize
197 if maxCommentSize > math.MaxUint16 {
198 maxCommentSize = math.MaxUint16
199 }
200 emptyCommentStart := len(buf) - eocdRecMinSize
201
202 for commentSize := 0; commentSize <= maxCommentSize; commentSize++ {
203 pos := emptyCommentStart - commentSize
204 if binary.LittleEndian.Uint32(buf[pos:pos+4]) == eocdRecMagic {
205 recordCommentSize := binary.LittleEndian.Uint16(buf[pos+eocdCommentSizeOffset:])
206 if int(recordCommentSize) == commentSize {
207 s.eocdOffset = bufOffsetInFile + int64(pos)
208 s.centralDirOffset = int64(binary.LittleEndian.Uint32(buf[pos+eocdCentralDirOffsetOffset:]))
209 s.eocd = buf[pos:]
210
211 if s.centralDirOffset >= s.eocdOffset {
212 return fmt.Errorf("ZIP Central Directory offset ouf of range: %d. Zip End of Central Directory offset: %d",
213 s.centralDirOffset, s.eocdOffset)
214 }
215
216 s.centralDirSize = int64(binary.LittleEndian.Uint32(buf[pos+eocdCentralDirSizeOffset:]))
217 if s.centralDirOffset+int64(s.centralDirSize) != s.eocdOffset {
218 return errors.New("ZIP Central Directory is not immediately followed by End of Central Directory")
219 }
220 return nil
221 }
222 }
223 }
224 return errEocdNotFound
225 }
226
227 func (s *signingBlock) isZip64() bool {
228 locatorPos := s.eocdOffset - zip64LocatorSize
229 if locatorPos < 0 {
230 return false
231 }
232
233 if _, err := s.file.Seek(locatorPos, io.SeekStart); err != nil {
234 return false
235 }
236
237 var magic uint32
238 if err := binary.Read(s.file, binary.LittleEndian, &magic); err != nil {
239 return false
240 }
241 return magic == zip64LocatorMagic
242 }
243
244 func (s *signingBlock) pickScheme(blocks map[int][]byte, minSdkVersion, maxSdkVersion int32) (schemeId int, scheme signatureBlockScheme, block []byte) {
245 if block = blocks[schemeIdV3]; block != nil {
246 schemeId = schemeIdV3
247 scheme = &schemeV3{}
248 } else if block = blocks[schemeIdV2]; block != nil {
249 schemeId = schemeIdV2
250 scheme = &schemeV2{minSdkVersion, maxSdkVersion}
251 } else {
252 panic("unhandled")
253 }
254 return
255 }
256
257 func (s *signingBlock) findApkSigningBlock() (block []byte, offset int64, err error) {
258 if s.centralDirOffset < apkSigBlockMinSize {
259 err = errNoSigningBlockSignature
260 return
261 }
262
263 footer := make([]byte, 24)
264
265 if _, err = s.file.Seek(s.centralDirOffset-int64(len(footer)), io.SeekStart); err != nil {
266 return
267 }
268
269 if _, err = io.ReadFull(s.file, footer); err != nil {
270 return
271 }
272
273 if binary.LittleEndian.Uint64(footer[8:]) != apkSigBlockMagicLo ||
274 binary.LittleEndian.Uint64(footer[16:]) != apkSigBlockMagicHi {
275 err = errNoSigningBlockSignature
276 return
277 }
278
279 blockSizeFooter := binary.LittleEndian.Uint64(footer)
280 if blockSizeFooter < uint64(len(footer)) || blockSizeFooter > math.MaxInt32-8 {
281 err = fmt.Errorf("APK Signing Block size out of range: %d", blockSizeFooter)
282 return
283 }
284
285 totalSize := int64(blockSizeFooter + 8)
286 if totalSize < apkSigBlockMinSize {
287 err = fmt.Errorf("Apk Signing Block is too small: %d vs %d", totalSize, apkSigBlockMinSize)
288 return
289 }
290
291 offset = int64(s.centralDirOffset) - totalSize
292 if offset < 0 {
293 err = fmt.Errorf("APK Signing Block offset out of range: %d", offset)
294 return
295 }
296
297 block = make([]byte, totalSize)
298 if _, err = s.file.Seek(offset, io.SeekStart); err != nil {
299 return
300 }
301
302 if _, err = io.ReadFull(s.file, block); err != nil {
303 return
304 }
305
306 if blockSizeHeader := binary.LittleEndian.Uint64(block); blockSizeHeader != blockSizeFooter {
307 err = fmt.Errorf("APK Signing Block sizes in header and footer do not match: %d vs %d",
308 blockSizeHeader, blockSizeFooter)
309 return
310 }
311
312 return
313 }
314
315 func (s *signingBlock) findSignatureBlocks(maxSdkVersion int32, res *VerificationResult) (blocks map[int][]byte, frostingRes *frostingInfo, err error) {
316 if err = s.findEocd(); err != nil {
317 err = &signingBlockNotFoundError{err}
318 return
319 }
320
321 if s.isZip64() {
322 err = &signingBlockNotFoundError{errors.New("ZIP64 APK not supported")}
323 return
324 }
325
326 var sigBlock []byte
327 sigBlock, s.sigBlockOffset, err = s.findApkSigningBlock()
328 if err != nil {
329 err = &signingBlockNotFoundError{err}
330 return
331 }
332
333 pairs := bytes.NewReader(sigBlock[8 : len(sigBlock)-24])
334 entryCount := 0
335
336 blocks = make(map[int][]byte)
337
338 for pairs.Len() > 0 {
339 entryCount++
340
341 if pairs.Len() < 8 {
342 err = fmt.Errorf("Insufficient data to read size of APK Signing Block entry #%d", entryCount)
343 return
344 }
345
346 var entryLen int64
347 binary.Read(pairs, binary.LittleEndian, &entryLen)
348 if entryLen < 4 || entryLen > math.MaxInt32 {
349 err = fmt.Errorf("APK Signing Block entry #%d size out of range: %d", entryCount, entryLen)
350 return
351 }
352
353 nextEntryPos := pairs.Size() - int64(pairs.Len()) + entryLen
354 if entryLen > int64(pairs.Len()) {
355 err = fmt.Errorf("APK Signing Block entry #%d size out of range: %d, available: %d",
356 entryCount, entryLen, pairs.Len())
357 return
358 }
359
360 var id uint32
361 if err = binary.Read(pairs, binary.LittleEndian, &id); err != nil {
362 err = fmt.Errorf("failed to read signing block id: %s", err.Error())
363 return
364 }
365
366 switch id {
367 case blockIdSchemeV3:
368 if maxSdkVersion >= sdkVersionP {
369 block := make([]byte, entryLen-4)
370 if _, err = pairs.Read(block); err != nil {
371 return
372 }
373 blocks[schemeIdV3] = block
374 }
375 case blockIdSchemeV2:
376 block := make([]byte, entryLen-4)
377 if _, err = pairs.Read(block); err != nil {
378 return
379 }
380 blocks[schemeIdV2] = block
381 case blockIdVerityPadding:
382 // Block full of zeros to ensure the signing block is padded to 4K,
383 // for verity signature verification.
384 case blockIdFrosting:
385 frostingBlock := make([]byte, entryLen-4)
386 if _, err = pairs.Read(frostingBlock); err != nil {
387 return
388 }
389
390 var frosting frostingInfo
391 var frResult FrostingResult
392 res.Frosting = &frResult
393 frResult.KeySha256, frResult.ProtobufInfo, frResult.Error = frosting.parse(frostingBlock)
394 if frResult.Error != nil {
395 res.addWarning("frosting: %s", frResult.Error.Error())
396 } else {
397 frostingRes = &frosting
398 }
399 }
400
401 if _, err = pairs.Seek(nextEntryPos, io.SeekStart); err != nil {
402 return
403 }
404 }
405
406 if len(blocks) == 0 {
407 err = errors.New("No APK Signature block in APK Signing Block")
408 }
409
410 return
411 }
412
413 func (s *signingBlock) extractCerts(scheme signatureBlockScheme, block []byte, res *VerificationResult) map[crypto.Hash][]byte {
414 contentDigests := make(map[crypto.Hash][]byte)
415 signatureBlock := bytes.NewBuffer(block)
416
417 scheme.parseSigners(signatureBlock, contentDigests, res)
418 return contentDigests
419 }
420
421 func (s *signingBlock) verify(scheme signatureBlockScheme, block []byte, minSdkVersion, maxSdkVersion int32, res *VerificationResult) {
422 contentDigests := s.extractCerts(scheme, block, res)
423 if len(res.Certs) == 0 {
424 res.addError("no signers found")
425 return
426 }
427
428 if len(contentDigests) == 0 {
429 res.addError("no content digests found")
430 return
431 }
432
433 if !s.verifyIntegrity(contentDigests, res) {
434 return
435 }
436
437 scheme.finalizeResult(minSdkVersion, maxSdkVersion, res)
438 }
439
440 func (s *signingBlock) verifyIntegrity(expectedDigests map[crypto.Hash][]byte, result *VerificationResult) bool {
441 beforeApkSigningBlock := &dataSourceApk{file: s.file, start: 0, end: s.sigBlockOffset}
442 centralDir := &dataSourceApk{file: s.file, start: s.centralDirOffset, end: s.eocdOffset}
443 eocd := &dataSourceBytes{data: append([]byte(nil), s.eocd...)}
444
445 // For the purposes of integrity verification, ZIP End of Central Directory's field Start of
446 // Central Directory must be considered to point to the offset of the APK Signing Block.
447 binary.LittleEndian.PutUint32(eocd.data[eocdCentralDirOffsetOffset:], uint32(s.sigBlockOffset))
448
449 digestAlgorithms := make([]crypto.Hash, 0, len(expectedDigests))
450 for algo := range expectedDigests {
451 digestAlgorithms = append(digestAlgorithms, algo)
452 }
453
454 actualDigests, err := s.computeContentDigests(digestAlgorithms, beforeApkSigningBlock, centralDir, eocd)
455 if err != nil {
456 result.addError("Failed to compute digest(s) of contents: %s", err.Error())
457 return false
458 }
459
460 for _, algo := range digestAlgorithms {
461 if !bytes.Equal(expectedDigests[algo], actualDigests[algo]) {
462 result.addError("%d digest of contents did not verify.", algo)
463 continue
464
465 }
466 }
467 return true
468 }
469
470 func (s *signingBlock) computeContentDigests(digestAlgorithms []crypto.Hash, contents ...dataSource) (map[crypto.Hash][]byte, error) {
471 var oneMbAlgos []crypto.Hash
472 hasVerity := false
473 for _, algo := range digestAlgorithms {
474 switch algo {
475 case crypto.SHA256, crypto.SHA512:
476 oneMbAlgos = append(oneMbAlgos, algo)
477 case veritySHA256:
478 hasVerity = true
479 default:
480 panic(fmt.Sprintf("unhandled crypto algo %d", int(algo)))
481 }
482 }
483
484 var result map[crypto.Hash][]byte
485 var err error
486 if len(oneMbAlgos) != 0 {
487 result, err = s.computeOneMbChunkContentDigests(oneMbAlgos, contents)
488 if err != nil {
489 return result, err
490 }
491 }
492
493 if hasVerity {
494 if result == nil {
495 result = make(map[crypto.Hash][]byte)
496 }
497 result[veritySHA256], err = s.computeVerityContentDigest(contents)
498 if err != nil {
499 return result, err
500 }
501 }
502
503 if len(result) == 0 {
504 return nil, fmt.Errorf("no valid digest algorithms")
505 }
506
507 return result, nil
508 }
509
510 func (s *signingBlock) computeOneMbChunkContentDigests(digestAlgorithms []crypto.Hash, contents []dataSource) (map[crypto.Hash][]byte, error) {
511 var totalChunkCount int64
512 for _, input := range contents {
513 totalChunkCount += input.chunkCount()
514 }
515
516 if totalChunkCount >= math.MaxInt32/1024 {
517 return nil, fmt.Errorf("Too many chunks: %d", totalChunkCount)
518 }
519
520 digestsOfChunks := make([][]byte, len(digestAlgorithms))
521 hashers := make([]hash.Hash, len(digestAlgorithms))
522 for i, algo := range digestAlgorithms {
523 buf := make([]byte, 5+totalChunkCount*int64(algo.Size()))
524 buf[0] = 0x5a
525 binary.LittleEndian.PutUint32(buf[1:], uint32(totalChunkCount))
526
527 digestsOfChunks[i] = buf
528 hashers[i] = algo.New()
529 }
530
531 chunkContentPrefix := make([]byte, 5)
532 chunkContentPrefix[0] = 0xa5
533
534 chunkIndex := 0
535 for inputIdx, input := range contents {
536 var offset int64
537 remaining := input.length()
538 for remaining > 0 {
539 chunkSize := remaining
540 if chunkSize > maxChunkSize {
541 chunkSize = maxChunkSize
542 }
543
544 binary.LittleEndian.PutUint32(chunkContentPrefix[1:], uint32(chunkSize))
545
546 for i := range hashers {
547 hashers[i].Write(chunkContentPrefix)
548
549 if err := input.writeTo(hashers[i], offset, chunkSize); err != nil {
550 return nil, fmt.Errorf("Failed to digest chunk #%d of section #%d", chunkIndex, inputIdx)
551 }
552
553 sum := hashers[i].Sum(nil)
554 hashers[i].Reset()
555
556 copy(digestsOfChunks[i][5+chunkIndex*len(sum):], sum)
557 }
558 offset += chunkSize
559 remaining -= chunkSize
560 chunkIndex++
561 }
562 }
563 result := make(map[crypto.Hash][]byte, len(digestAlgorithms))
564 for i := range digestsOfChunks {
565 hashers[i].Write(digestsOfChunks[i])
566 result[digestAlgorithms[i]] = hashers[i].Sum(nil)
567 }
568 return result, nil
569 }
570
571 func (s *signingBlock) computeVerityContentDigest(contents []dataSource) ([]byte, error) {
572 if contents[0].length()%verityChunkSize != 0 {
573 return nil, fmt.Errorf("APK Signing block size not a multiple of %d", verityChunkSize)
574 }
575
576 chained := newChainedDataSource(contents...)
577 builder := newVerityTreeBuilder(make([]byte, 8))
578 rootHash, err := builder.generateTreeRootHash(chained)
579 if err != nil {
580 return nil, fmt.Errorf("failed to generate verity tree root hash: %s", err.Error())
581 }
582
583 result := make([]byte, sha256.Size+8)
584 copy(result, rootHash)
585 binary.LittleEndian.PutUint64(result[sha256.Size:], uint64(chained.length()))
586 return result, nil
587 }