Debian Codegraph @

signingblock/frosting.go

raw symbols SCIP
1 package signingblock
2
3 import (
4 "bytes"
5 "crypto/ecdsa"
6 "crypto/sha256"
7 "crypto/x509"
8 "encoding/asn1"
9 "encoding/base64"
10 "encoding/binary"
11 "encoding/hex"
12 "errors"
13 "fmt"
14 "hash"
15 "io"
16 "io/ioutil"
17 "math"
18 "math/big"
19 "os"
20 "strings"
21 )
22
23 /*
24 * *** FROSTING BLOCK STRUCTURE ***
25 *
26 * ------------------------------------------------------------
27 * |- size of the protobuf + size of the metadata array (varint) (AKA relative offset to the signatures array)
28 * --------------------------- SIGNED DATA START ---------------------------
29 * |- protobuf size (varint)
30 * |- protobuf frosting info (byte array)
31 * |
32 * |- metadata array size (varint)
33 * |- metadata array, pick first non-disabled
34 * |- entry size (varint)
35 * |- disabled flag (varint), checked != 0 in Play Store
36 * |- public key index (varint), from finsky.peer_app_sharing_api.frosting_public_keys comma separated array
37 * |- fileSha256 (digest over the apk before signing block, schemev2 signing block and eocd, see verifyApk()
38 * --------------------------- SIGNED DATA END ---------------------------
39 * |
40 * |- size of the signatures array (varint)
41 * |- signatures array, indexing matches the metadata array
42 * |- entry size (varint)
43 * |- signature (byte array)
44 * -------------------------------------------------------------
45 *
46 * All the size fields are in bytes and counted excluding the size varint itself.
47 *
48 * The SIGNED DATA end after the metadata entry you're checking againts, even if it is not the last entry.
49 * They are verified against signature created by frostingPublicKeys key. It uses ECDSAWithSHA256 algorithm.
50 * The fileSha256 hash must match the APK for the frosting to be valid.
51 *
52 * The 'protobuf frosting info' is a rather complex protobuf structure. It contains some APK's metadata,
53 * nothing really useful it seems. It does not seem to be relevant to the frosting signature's validity,
54 * so I have not examined it further.
55 * Interestingly, Google Photos apk from apkmirror.com contains 'com.google.android.apps.photos.PIXEL_2018_PRELOAD'
56 * string inside this protobuf, perhaps it is possible to distinguish preloaded /system apps from the Play Store apks?
57 * Some apk's have very short protobuf infos (Netflix, 200 bytes), some have much longer (Facebook, 2200 bytes).
58 * Here's an example of parsed protobuf info from the Netflix app:
59 *
60 * 1 <varint> = 1 // frosting versions?
61 * 2 <varint> = 0
62 * 3 <varint> = 1
63 * 4 <varint> = 1541545744578 // Timestamp of the frosting creation?
64 * 5 <chunk> = message:
65 * 8 <chunk> = message:
66 * 1 <chunk> = message(1 <varint> = 22) // minSdkLevel?
67 * 6 <varint> = 2
68 * 9 <chunk> = message:
69 * 1 <chunk> = message(1 <varint> = 2266, 4 <varint> = 2) // versionCode
70 * 2 <chunk> = message(1 <varint> = 50003, 4 <varint> = 4)
71 * 10 <chunk> = message:
72 * 1 <chunk> = bytes (30) // ?? only last byte changes across apks
73 * 0000 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FE FF FF FF FF FF FF ........................
74 * 0018 FF FF FF FF FF 3F .....?
75 * 3 <chunk> = message:
76 * 1 <chunk> = bytes (32) // sha256 of something?
77 * 0000 16 F8 22 A6 93 26 89 34 D8 2A 88 BB 8C AD B6 68 2C EB 77 A8 AA E4 5F AA .."..&.4.*.....h,.w..._.
78 * 0018 F9 3C CA 63 44 2A A4 B9 .<.cD*..
79 * 2 <varint> = 20
80 */
81
82 const (
83 // Value 'finsky.peer_app_sharing_api.frosting_public_keys' from com.android.vending 11.2.14-all [0] [PR] 207207134
84 frostingPublicKeys = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEZH2+1+E07dnErAD3L6BbTnaohU0bbXriNlJI7VxJU+LjdSwPyXR5pomARAMoyPkMksLz/gitUPtFuJoPL2ziEw=="
85 )
86
87 var (
88 ErrFrostingInvalidSignature = errors.New("invalid frosting signature")
89 ErrFrostingDigestMismatch = errors.New("frosting apk file digest mismatch")
90 )
91
92 type frostingInfo struct {
93 fileSha256 []byte
94 protobufInfo []byte
95
96 usedKeySha256 string
97 }
98
99 func (f *frostingInfo) readInt8(r io.ByteReader) (int32, error) {
100 x, err := r.ReadByte()
101 return int32(int8(x)), err
102 }
103
104 func (f *frostingInfo) readInt32(r io.ByteReader) (int32, error) {
105 v0, err := f.readInt8(r)
106 if err != nil {
107 return 0, err
108 }
109
110 if v0 < 0 {
111 v0 &= 0x7f
112
113 v1, err := f.readInt8(r)
114 if err != nil {
115 return 0, err
116 }
117
118 if v1 < 0 {
119 v0 |= (v1 & 0x7F) << 7
120 if v1, err = f.readInt8(r); err != nil {
121 return 0, err
122 }
123
124 if v1 < 0 {
125 v0 |= (v1 & 0x7F) << 14
126 if v1, err = f.readInt8(r); err != nil {
127 return 0, err
128 }
129
130 if v1 < 0 {
131 v2, err := f.readInt8(r)
132 if err != nil {
133 return 0, err
134 }
135
136 v0 = v0 | (v1&0x7F)<<21 | v2<<28
137 if v2 < 0 {
138 return 0, fmt.Errorf("varint overflow")
139 }
140 } else {
141 v0 |= v1 << 21
142 }
143 } else {
144 v0 |= v1 << 14
145 }
146 } else {
147 v0 |= v1 << 7
148 }
149 }
150 return v0, nil
151 }
152
153 func (f *frostingInfo) readArrayItem(bf *bytes.Reader, index int) ([]byte, error) {
154 totalSize, err := f.readInt32(bf)
155 if err != nil {
156 return nil, err
157 }
158
159 if totalSize <= 0 || int(totalSize) > bf.Len() {
160 return nil, fmt.Errorf("invalid base for array")
161 }
162
163 startPos, _ := bf.Seek(0, io.SeekCurrent)
164 for i := 0; i < index; i++ {
165 entrySize, err := f.readInt32(bf)
166 if err != nil {
167 return nil, err
168 }
169
170 if pos, _ := bf.Seek(0, io.SeekCurrent); entrySize < 0 || pos+int64(entrySize) >= startPos+int64(totalSize) {
171 return nil, fmt.Errorf("invalid next value")
172 }
173
174 if _, err := bf.Seek(int64(entrySize), io.SeekCurrent); err != nil {
175 return nil, fmt.Errorf("failed to seek to next")
176 }
177 }
178
179 size, err := f.readInt32(bf)
180 if err != nil {
181 return nil, fmt.Errorf("failed to read size")
182 }
183
184 if pos, _ := bf.Seek(0, io.SeekCurrent); size < 0 || pos+int64(size) > int64(totalSize)+startPos {
185 return nil, fmt.Errorf("invalid size value")
186 }
187
188 res := make([]byte, size)
189 _, err = bf.Read(res)
190 return res, err
191 }
192
193 type ecdsaSignature struct {
194 R, S *big.Int
195 }
196
197 func (f *frostingInfo) verifySignature(signed, signature []byte, keyBase64 string) error {
198 dec := base64.NewDecoder(base64.StdEncoding, strings.NewReader(keyBase64))
199 pubKeyAsn, err := ioutil.ReadAll(dec)
200 if err != nil {
201 return fmt.Errorf("failed to parse key base64: %s", err.Error())
202 }
203
204 keyDigest := sha256.Sum256(pubKeyAsn)
205 f.usedKeySha256 = hex.EncodeToString(keyDigest[:])
206
207 pkGen, err := x509.ParsePKIXPublicKey(pubKeyAsn)
208 if err != nil {
209 return fmt.Errorf("failed to unmarshal pk: %s", err.Error())
210 }
211
212 pk, ok := pkGen.(*ecdsa.PublicKey)
213 if !ok {
214 return fmt.Errorf("invalid key type: %T", pkGen)
215 }
216
217 digest := sha256.Sum256(signed)
218
219 ecdsaSig := new(ecdsaSignature)
220 if rest, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
221 return err
222 } else if len(rest) != 0 {
223 return errors.New("x509: trailing data after ECDSA signature")
224 }
225
226 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
227 return errors.New("x509: ECDSA signature contained zero or negative values")
228 }
229
230 if !ecdsa.Verify(pk, digest[:], ecdsaSig.R, ecdsaSig.S) {
231 return ErrFrostingInvalidSignature
232 }
233
234 return nil
235 }
236
237 func (f *frostingInfo) parseFrostingBlock(block []byte) error {
238 bf := bytes.NewReader(block)
239
240 protoAndMetaSize, err := f.readInt32(bf)
241 if err != nil || protoAndMetaSize <= 0 || int(protoAndMetaSize) > bf.Len() {
242 return fmt.Errorf("invalid protoAndMetaSize value")
243 }
244 offAfterSignaturesEnd, _ := bf.Seek(0, io.SeekCurrent)
245
246 protobufSize, err := f.readInt32(bf)
247 frostingProtobufStart, _ := bf.Seek(0, io.SeekCurrent)
248
249 if err != nil || protobufSize <= 0 || int(protobufSize) > bf.Len() ||
250 protobufSize > protoAndMetaSize-int32(frostingProtobufStart-offAfterSignaturesEnd) {
251 return fmt.Errorf("invalid protobufSize value")
252 }
253
254 if _, err := bf.Seek(int64(protobufSize), io.SeekCurrent); err != nil {
255 return fmt.Errorf("seek to metadata start failed %s", err.Error())
256 }
257
258 metadataSize, err := f.readInt32(bf)
259 if err != nil || metadataSize <= 0 || metadataSize > (protoAndMetaSize-protobufSize) {
260 return fmt.Errorf("invalid metadataSize")
261 }
262
263 limit, _ := bf.Seek(0, io.SeekCurrent)
264 limit += int64(metadataSize)
265 for signatureIdx := 0; signatureIdx < math.MaxInt16; signatureIdx++ {
266 pos, _ := bf.Seek(0, io.SeekCurrent)
267 if pos >= limit {
268 break
269 }
270
271 nextKey, err := f.readInt32(bf)
272 pos, _ = bf.Seek(0, io.SeekCurrent)
273 nextKey += int32(pos)
274 if err != nil || int64(nextKey) > limit || nextKey <= 0 {
275 return fmt.Errorf("invalid nextKey offset")
276 }
277
278 disabled, err := f.readInt32(bf)
279 if pos, _ := bf.Seek(0, io.SeekCurrent); err != nil || pos > int64(nextKey) {
280 return fmt.Errorf("invalid 'disabled' read")
281 }
282
283 if disabled != 0 {
284 if _, err := bf.Seek(int64(nextKey), io.SeekStart); err != nil {
285 return fmt.Errorf("can't seek after disabled: %s", err.Error())
286 }
287 continue
288 }
289
290 keyIndex, err := f.readInt32(bf)
291 keys := strings.Split(frostingPublicKeys, ",")
292 if err != nil || int(keyIndex) >= len(keys) {
293 return fmt.Errorf("invalid/unknown key used in this frosting (idx %d)!", keyIndex)
294 }
295
296 pos, _ = bf.Seek(0, io.SeekCurrent)
297 if int64(nextKey)-pos != sha256.Size {
298 return fmt.Errorf("invalind key index length")
299 }
300
301 fileSha256 := make([]byte, sha256.Size)
302 if _, err := bf.Read(fileSha256); err != nil {
303 return fmt.Errorf("failed to read signature: %s", err.Error())
304 }
305
306 if _, err := bf.Seek(offAfterSignaturesEnd+int64(protoAndMetaSize), io.SeekStart); err != nil {
307 return fmt.Errorf("failed to seek after signature read: %s", err.Error())
308 }
309
310 signature, err := f.readArrayItem(bf, signatureIdx)
311 if err != nil {
312 return fmt.Errorf("failed to read signature: %s", err.Error())
313 }
314
315 if _, err := bf.Seek(offAfterSignaturesEnd, io.SeekStart); err != nil {
316 return fmt.Errorf("failed to seek to signed data: %s", err.Error())
317 }
318
319 signedData := make([]byte, int64(nextKey)-offAfterSignaturesEnd)
320 if _, err := bf.Read(signedData); err != nil {
321 return fmt.Errorf("failed to read signed data: %s", err.Error())
322 }
323
324 if err := f.verifySignature(signedData, signature, keys[keyIndex]); err != nil {
325 if err == ErrFrostingInvalidSignature {
326 return err
327 }
328 return fmt.Errorf("failed to verify signature: %s", err.Error())
329 }
330
331 if _, err := bf.Seek(frostingProtobufStart, io.SeekStart); err != nil {
332 return fmt.Errorf("failed to seek to signed data: %s", err.Error())
333 }
334
335 protobufInfo := make([]byte, protobufSize)
336 if _, err := bf.Read(protobufInfo); err != nil {
337 return fmt.Errorf("failed to read protobufInfo data: %s", err.Error())
338 }
339
340 f.fileSha256 = fileSha256
341 f.protobufInfo = protobufInfo
342 return nil
343 }
344
345 return fmt.Errorf("no enabled signature found")
346 }
347
348 func (f *frostingInfo) parse(block []byte) (string, []byte, error) {
349 err := f.parseFrostingBlock(block)
350 return f.usedKeySha256, f.protobufInfo, err
351 }
352
353 func (f *frostingInfo) hashFileSection(hasher hash.Hash, apkFile *os.File, offset int64, size int) error {
354 if _, err := apkFile.Seek(offset, io.SeekStart); err != nil {
355 return err
356 }
357
358 buf := make([]byte, 0x2000)
359 var chunk int
360 var err error
361 for i := 0; i < size; i += chunk {
362 chunk = len(buf)
363 if chunk > (size - i) {
364 chunk = size - i
365 }
366
367 chunk, err = io.ReadFull(apkFile, buf[:chunk])
368 if err == io.EOF {
369 if chunk <= 0 {
370 return err
371 }
372 } else if err != nil {
373 return err
374 }
375
376 hasher.Write(buf[:chunk])
377 }
378 return nil
379 }
380
381 func (f *frostingInfo) verifyApk(apkFile *os.File, signingBlockOffset int64, schemeV2block []byte, zipCdOffset, zipCdSize int64, eocdOrig []byte) error {
382 hasher := sha256.New()
383
384 if err := f.hashFileSection(hasher, apkFile, 0, int(signingBlockOffset)); err != nil {
385 return fmt.Errorf("failed to hash apk: %s", err.Error())
386 }
387
388 if len(schemeV2block) != 0 {
389 binary.Write(hasher, binary.LittleEndian, uint32(blockIdSchemeV2))
390 hasher.Write(schemeV2block)
391 }
392
393 if err := f.hashFileSection(hasher, apkFile, zipCdOffset, int(zipCdSize)); err != nil {
394 return fmt.Errorf("failed to hash zip central directory: %s", err.Error())
395 }
396
397 // For the purposes of integrity verification, ZIP End of Central Directory's field Start of
398 // Central Directory must be considered to point to the offset of the APK Signing Block.
399 eocd := make([]byte, len(eocdOrig))
400 copy(eocd, eocdOrig)
401 binary.LittleEndian.PutUint32(eocd[eocdCentralDirOffsetOffset:], uint32(signingBlockOffset))
402 hasher.Write(eocd)
403
404 if !bytes.Equal(hasher.Sum(nil), f.fileSha256) {
405 return ErrFrostingDigestMismatch
406 }
407
408 return nil
409 }