-
Notifications
You must be signed in to change notification settings - Fork 27
/
apkverifier.go
256 lines (223 loc) · 8.35 KB
/
apkverifier.go
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
// Package apkverifier does APK signature verification.
// It should support all algorithms and schemes supported Android, including scheme v2 verification
// and checks for downgrade attack to v1.
package apkverifier
import (
"crypto/x509"
"encoding/xml"
"errors"
"fmt"
"io"
"os"
"strconv"
"github.com/avast/apkparser"
"github.com/avast/apkverifier/apilevel"
"github.com/avast/apkverifier/signingblock"
)
// Result Contains result of Apk verification
type Result struct {
SigningSchemeId int
SignerCerts [][]*x509.Certificate
SigningBlockResult *signingblock.VerificationResult
}
// ErrMixedDexApkFile Returned from the Verify method if the file starts with the DEX magic value,
// but otherwise looks like a properly signed APK.
//
// This detects 'Janus' Android vulnerability where a DEX is prepended to a valid,
// signed APK file. The signature verification passes because with v1 scheme,
// only the APK portion of the file is checked, but Android then loads the prepended,
// unsigned DEX file instead of the one from APK.
// https://www.guardsquare.com/en/blog/new-android-vulnerability-allows-attackers-modify-apps-without-affecting-their-signatures
//
// If this error is returned, the signature is otherwise valid (the err would be nil
// had it not have the DEX file prepended).
var ErrMixedDexApkFile = errors.New("This file is both DEX and ZIP archive! Exploit?")
const (
dexHeaderMagic uint32 = 0xa786564 // "dex\n", littleendinan
maxApkSigners = 10
)
// Verify Calls VerifyWithSdkVersion with sdk versions <apilevel.V_AnyMin; apilevel.V_AnyMax>
func Verify(path string, optionalZip *apkparser.ZipReader) (res Result, err error) {
return VerifyWithSdkVersion(path, optionalZip, apilevel.V_AnyMin, apilevel.V_AnyMax)
}
// VerifyReader Calls VerifyWithSdkVersionReader with sdk versions <apilevel.V_AnyMin; apilevel.V_AnyMax>
func VerifyReader(r io.ReadSeeker, optionalZip *apkparser.ZipReader) (res Result, err error) {
return VerifyWithSdkVersionReader(r, optionalZip, apilevel.V_AnyMin, apilevel.V_AnyMax)
}
// VerifyWithSdkVersion see VerifyWithSdkVersionReader
func VerifyWithSdkVersion(path string, optionalZip *apkparser.ZipReader, minSdkVersion, maxSdkVersion int32) (res Result, err error) {
f, err := os.Open(path)
if err != nil {
return Result{}, err
}
defer f.Close()
return VerifyWithSdkVersionReader(f, optionalZip, minSdkVersion, maxSdkVersion)
}
// VerifyWithSdkVersionReader Verify the application signature. If err is nil, the signature is correct,
// otherwise it is not and res may or may not contain extracted certificates,
// depending on how the signature verification failed.
// Path is required, pass optionalZip if you have the ZipReader already opened and want to reuse it.
// This method will not close it.
// minSdkVersion and maxSdkVersion means the apk has to successfuly verify on real devices with sdk version
// inside the <minSdkVersion;maxSdkVersion> interval.
// minSdkVersion == apilevel.V_AnyMin means it will obtain the minSdkVersion from AndroidManifest.
func VerifyWithSdkVersionReader(r io.ReadSeeker, optionalZip *apkparser.ZipReader, minSdkVersion, maxSdkVersion int32) (res Result, err error) {
if optionalZip == nil {
optionalZip, err = apkparser.OpenZipReader(r)
if err != nil {
return Result{}, err
}
defer optionalZip.Close()
}
var sandboxVersion, targetSdkVersion int32
var manifestError error
if minSdkVersion == apilevel.V_AnyMin || apilevel.RequiresSandboxV2(maxSdkVersion) {
var manifestMinSdkVersion int32
manifestMinSdkVersion, targetSdkVersion, sandboxVersion, err = getManifestInfo(optionalZip)
if err != nil {
manifestError = err
} else {
if minSdkVersion == apilevel.V_AnyMin {
minSdkVersion = manifestMinSdkVersion
}
}
}
if minSdkVersion > maxSdkVersion {
err = fmt.Errorf("invalid sdk version range <%d;%d>", minSdkVersion, maxSdkVersion)
return
}
var fileMagic uint32
var signingBlockError error
res.SigningBlockResult, fileMagic, signingBlockError = signingblock.VerifySigningBlockReaderWithZip(r, minSdkVersion, maxSdkVersion, optionalZip)
if res.SigningBlockResult != nil && !signingblock.IsSigningBlockNotFoundError(signingBlockError) {
res.SignerCerts = res.SigningBlockResult.Certs
res.SigningSchemeId = res.SigningBlockResult.SchemeId
} else {
res.SigningSchemeId = 1
}
if signingBlockError != nil && !signingblock.IsSigningBlockNotFoundError(signingBlockError) {
return res, signingBlockError
} else if apilevel.SupportsSigV2(minSdkVersion) && signingBlockError == nil {
return res, nil
}
// Android O and newer requires that APKs targeting security sandbox version 2 and higher
// are signed using APK Signature Scheme v2 or newer.
var sandboxError error
if apilevel.RequiresSandboxV2(maxSdkVersion) && sandboxVersion > 1 && (signingBlockError != nil || res.SigningSchemeId < 2) {
sandboxError = fmt.Errorf("no valid signature for sandbox version %d", sandboxVersion)
} else if targetSdkVersion >= apilevel.V11_0_Eleven && maxSdkVersion >= targetSdkVersion && res.SigningSchemeId < 2 {
sandboxError = fmt.Errorf("target SDK version %d requires a minimum of signature scheme v2; the APK is not signed with this or a later signature scheme", targetSdkVersion)
}
var certsv1 [][]*x509.Certificate
certsv1, err = verifySchemeV1(optionalZip, signingBlockError == nil, minSdkVersion, maxSdkVersion)
if len(res.SignerCerts) == 0 {
res.SignerCerts = certsv1
}
if sandboxError != nil {
err = sandboxError
} else if err == nil {
if res.SigningSchemeId != 1 && manifestError != nil {
err = manifestError
} else if fileMagic == dexHeaderMagic {
err = ErrMixedDexApkFile
}
}
return
}
// ExtractCerts Extract certs without verifying the signature.
func ExtractCerts(path string, optionalZip *apkparser.ZipReader) ([][]*x509.Certificate, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return ExtractCertsReader(f, optionalZip)
}
func ExtractCertsReader(r io.ReadSeeker, optionalZip *apkparser.ZipReader) ([][]*x509.Certificate, error) {
var err error
if optionalZip == nil {
optionalZip, err = apkparser.OpenZipReader(r)
if err != nil {
return nil, err
}
defer optionalZip.Close()
}
certs, signingBlockError := signingblock.ExtractCertsReader(r, apilevel.V_AnyMin, apilevel.V_AnyMax)
if !signingblock.IsSigningBlockNotFoundError(signingBlockError) {
return certs, signingBlockError
}
var certsv1 [][]*x509.Certificate
certsv1, err = extractCertsSchemeV1(optionalZip, apilevel.V_AnyMin, apilevel.V_AnyMax)
certs = append(certs, certsv1...)
return certs, err
}
type sandboxVersionEncoder struct {
minSdkVersion int32
targetSdkVersion int32
sandboxVersion int32
}
func (e *sandboxVersionEncoder) EncodeToken(t xml.Token) error {
st, ok := t.(xml.StartElement)
if !ok {
return nil
}
switch st.Name.Local {
case "manifest":
val, err := e.getAttrIntValue(&st, "targetSandboxVersion")
if err == nil {
e.sandboxVersion = val
} else if err != io.EOF {
return err
}
case "uses-sdk":
val, err := e.getAttrIntValue(&st, "minSdkVersion")
if err == nil {
e.minSdkVersion = val
} else if err != io.EOF {
return err
}
val, err = e.getAttrIntValue(&st, "targetSdkVersion")
if err == nil {
e.targetSdkVersion = val
} else if err != io.EOF {
return err
}
return apkparser.ErrEndParsing
}
return nil
}
func (e *sandboxVersionEncoder) Flush() error {
return nil
}
func (e *sandboxVersionEncoder) getAttrIntValue(st *xml.StartElement, name string) (int32, error) {
for _, attr := range st.Attr {
if attr.Name.Local == name {
val, err := strconv.ParseInt(attr.Value, 10, 32)
if err != nil {
return 0, fmt.Errorf("failed to decode %s '%s': %s", name, attr.Value, err.Error())
}
return int32(val), nil
}
}
return 0, io.EOF
}
func getManifestInfo(zip *apkparser.ZipReader) (minSdkVersion, targetSdkVersion, sandboxVersion int32, err error) {
manifest := zip.File["AndroidManifest.xml"]
if manifest == nil {
return 1, 0, 1, nil
}
if err = manifest.Open(); err != nil {
err = fmt.Errorf("failed to open AndroidManifest.xml: %s", err.Error())
return
}
defer manifest.Close()
for manifest.Next() {
enc := sandboxVersionEncoder{1, 0, 1}
if err = apkparser.ParseXml(manifest, &enc, nil); err != nil {
err = fmt.Errorf("failed to parse AndroidManifest.xml: %s", err.Error())
return
}
return enc.minSdkVersion, enc.targetSdkVersion, enc.sandboxVersion, nil
}
return
}