Debian Codegraph @

binxml.go

raw symbols SCIP
1 package apkparser
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "encoding/xml"
7 "errors"
8 "fmt"
9 "io"
10 "io/ioutil"
11 "strconv"
12 "strings"
13 "unsafe"
14 )
15
16 type binxmlParseInfo struct {
17 strings stringTable
18 resourceIds []uint32
19
20 encoder ManifestEncoder
21 res *ResourceTable
22 }
23
24 // Some samples have manifest in plaintext, this is an error.
25 // 2c882a2376034ed401be082a42a21f0ac837689e7d3ab6be0afb82f44ca0b859
26 var ErrPlainTextManifest = errors.New("xml is in plaintext, binary form expected")
27
28 // Deprecated: just calls ParseXML
29 func ParseManifest(r io.Reader, enc ManifestEncoder, resources *ResourceTable) error {
30 return ParseXml(r, enc, resources)
31 }
32
33 // Parse the binary Xml format. The resources are optional and can be nil.
34 func ParseXml(r io.Reader, enc ManifestEncoder, resources *ResourceTable) error {
35 x := binxmlParseInfo{
36 encoder: enc,
37 res: resources,
38 }
39
40 id, headerLen, totalLen, err := parseChunkHeader(r)
41 if err != nil {
42 return err
43 }
44
45 if (id & 0xFF) == '<' {
46 buf := bytes.NewBuffer(make([]byte, 0, 8))
47 binary.Write(buf, binary.LittleEndian, &id)
48 binary.Write(buf, binary.LittleEndian, &headerLen)
49 binary.Write(buf, binary.LittleEndian, &totalLen)
50
51 if s := buf.String(); strings.HasPrefix(s, "<?xml ") || strings.HasPrefix(s, "<manif") {
52 return ErrPlainTextManifest
53 }
54 }
55
56 // Android doesn't care.
57 /*if id != chunkAxmlFile {
58 return fmt.Errorf("Invalid top chunk id: 0x%08x", id)
59 }*/
60
61 defer x.encoder.Flush()
62
63 totalLen -= chunkHeaderSize
64
65 var len uint32
66 var lastId uint16
67 for i := uint32(0); i < totalLen; i += len {
68 id, _, len, err = parseChunkHeader(r)
69 if err != nil {
70 return fmt.Errorf("Error parsing header at 0x%08x of 0x%08x %08x: %s", i, totalLen, lastId, err.Error())
71 }
72
73 lastId = id
74
75 lm := &io.LimitedReader{R: r, N: int64(len) - 2*4}
76
77 switch id {
78 case chunkStringTable:
79 x.strings, err = parseStringTable(lm)
80 case chunkResourceIds:
81 err = x.parseResourceIds(lm)
82 default:
83 if (id & chunkMaskXml) == 0 {
84 err = fmt.Errorf("Unknown chunk id 0x%x", id)
85 break
86 }
87
88 // skip line number and unknown 0xFFFFFFFF
89 if _, err = io.CopyN(ioutil.Discard, lm, 2*4); err != nil {
90 break
91 }
92
93 switch id {
94 case chunkXmlNsStart:
95 err = x.parseNsStart(lm)
96 case chunkXmlNsEnd:
97 err = x.parseNsEnd(lm)
98 case chunkXmlTagStart:
99 err = x.parseTagStart(lm)
100 case chunkXmlTagEnd:
101 err = x.parseTagEnd(lm)
102 case chunkXmlText:
103 err = x.parseText(lm)
104 default:
105 err = fmt.Errorf("Unknown chunk id 0x%x", id)
106 }
107 }
108
109 if err == ErrEndParsing {
110 break
111 } else if err != nil {
112 return fmt.Errorf("Chunk: 0x%08x: %s", id, err.Error())
113 } else if lm.N != 0 {
114 return fmt.Errorf("Chunk: 0x%08x: was not fully read", id)
115 }
116 }
117
118 return x.encoder.Flush()
119 }
120
121 func (x *binxmlParseInfo) parseResourceIds(r *io.LimitedReader) error {
122 if (r.N % 4) != 0 {
123 return fmt.Errorf("Invalid chunk size!")
124 }
125
126 count := uint32(r.N / 4)
127 var id uint32
128 for i := uint32(0); i < count; i++ {
129 if err := binary.Read(r, binary.LittleEndian, &id); err != nil {
130 return err
131 }
132 x.resourceIds = append(x.resourceIds, id)
133 }
134 return nil
135 }
136
137 func (x *binxmlParseInfo) parseNsStart(r *io.LimitedReader) error {
138 var err error
139 ns := &xml.Name{}
140
141 var idx uint32
142 if err = binary.Read(r, binary.LittleEndian, &idx); err != nil {
143 return err
144 }
145
146 if ns.Local, err = x.strings.get(idx); err != nil {
147 return err
148 }
149
150 if err = binary.Read(r, binary.LittleEndian, &idx); err != nil {
151 return err
152 }
153
154 if ns.Space, err = x.strings.get(idx); err != nil {
155 return err
156 }
157
158 // TODO: what to do with this?
159 _ = ns
160 return nil
161 }
162
163 func (x *binxmlParseInfo) parseNsEnd(r *io.LimitedReader) error {
164 if _, err := io.CopyN(ioutil.Discard, r, 2*4); err != nil {
165 return fmt.Errorf("error skipping: %s", err.Error())
166 }
167
168 // TODO: what to do with this?
169 return nil
170 }
171
172 func (x *binxmlParseInfo) parseTagStart(r *io.LimitedReader) error {
173 var namespaceIdx, nameIdx, attrCnt, classAttrIdx uint32
174
175 if err := binary.Read(r, binary.LittleEndian, &namespaceIdx); err != nil {
176 return fmt.Errorf("error reading namespace idx: %s", err.Error())
177 }
178
179 if err := binary.Read(r, binary.LittleEndian, &nameIdx); err != nil {
180 return fmt.Errorf("error reading name idx: %s", err.Error())
181 }
182
183 if _, err := io.CopyN(ioutil.Discard, r, 4); err != nil {
184 return fmt.Errorf("error skipping flag: %s", err.Error())
185 }
186
187 if err := binary.Read(r, binary.LittleEndian, &attrCnt); err != nil {
188 return fmt.Errorf("error reading attrCnt: %s", err.Error())
189 }
190
191 if err := binary.Read(r, binary.LittleEndian, &classAttrIdx); err != nil {
192 return fmt.Errorf("error reading classAttr: %s", err.Error())
193 }
194
195 idAttributeIdx := (attrCnt >> 16) - 1
196 attrCnt = (attrCnt & 0xFFFF)
197
198 styleAttrIdx := (classAttrIdx >> 16) - 1
199 classAttrIdx = (classAttrIdx & 0xFFFF)
200
201 _ = styleAttrIdx
202 _ = idAttributeIdx
203
204 namespace, err := x.strings.get(namespaceIdx)
205 if err != nil {
206 return fmt.Errorf("error decoding namespace: %s", err.Error())
207 }
208
209 name, err := x.strings.get(nameIdx)
210 if err != nil {
211 return fmt.Errorf("error decoding name: %s", err.Error())
212 }
213
214 tok := xml.StartElement{
215 Name: xml.Name{Local: name, Space: namespace},
216 }
217
218 var attrData [attrValuesCount]uint32
219 for i := uint32(0); i < attrCnt; i++ {
220 if err := binary.Read(r, binary.LittleEndian, &attrData); err != nil {
221 return fmt.Errorf("error reading attrData: %s", err.Error())
222 }
223
224 // Android actually reads attributes purely by their IDs (see frameworks/base/core/res/res/values/attrs_manifest.xml
225 // and its generated R class, that's where the indexes come from, namely the AndroidManifestActivity array)
226 // but good guy android actually puts the strings into the string table on the same indexes anyway, most of the time.
227 // This is for the samples that don't have it, mostly due to obfuscators/minimizers.
228 // The ID can't change, because it would break current APKs.
229 // Sample: 98d2e837b8f3ac41e74b86b2d532972955e5352197a893206ecd9650f678ae31
230 //
231 // The exception to this rule is the "package" attribute in the root manifest tag. That one MUST NOT use
232 // resource ids, instead, it needs to use the string table. The meta attrs 'platformBuildVersion*'
233 // are the same, except Android never parses them so it's just for manual analysis.
234 // Sample: a3ee88cf1492237a1be846df824f9de30a6f779973fe3c41c7d7ed0be644ba37
235 //
236 // In general, android doesn't care about namespaces, but if a resource ID is used, it has to have been
237 // in the android: namespace, so we fix that up.
238
239 // frameworks/base/core/jni/android_util_AssetManager.cpp android_content_AssetManager_retrieveAttributes
240 // frameworks/base/core/java/android/content/pm/PackageParser.java parsePackageSplitNames
241 var attrName string
242 if attrData[attrIdxName] < uint32(len(x.resourceIds)) {
243 attrName = getAttributteName(x.resourceIds[attrData[attrIdxName]])
244 }
245
246 var attrNameFromStrings string
247 if attrName == "" || name == "manifest" {
248 attrNameFromStrings, err = x.strings.get(attrData[attrIdxName])
249 if err != nil {
250 if attrName == "" {
251 return fmt.Errorf("error decoding attrNameIdx: %s", err.Error())
252 }
253 } else if attrName != "" && attrNameFromStrings != "package" && !strings.HasPrefix(attrNameFromStrings, "platformBuildVersion") {
254 attrNameFromStrings = ""
255 }
256 }
257
258 attrNameSpace, err := x.strings.get(attrData[attrIdxNamespace])
259 if err != nil {
260 return fmt.Errorf("error decoding attrNamespaceIdx: %s", err.Error())
261 }
262
263 if attrNameFromStrings != "" {
264 attrName = attrNameFromStrings
265 } else if attrNameSpace == "" {
266 attrNameSpace = "http://schemas.android.com/apk/res/android"
267 }
268
269 attr := xml.Attr{
270 Name: xml.Name{Local: attrName, Space: attrNameSpace},
271 }
272
273 switch attrData[attrIdxType] >> 24 {
274 case AttrTypeString:
275 attr.Value, err = x.strings.get(attrData[attrIdxString])
276 if err != nil {
277 return fmt.Errorf("error decoding attrStringIdx: %s", err.Error())
278 }
279 case AttrTypeIntBool:
280 attr.Value = strconv.FormatBool(attrData[attrIdxData] != 0)
281 case AttrTypeIntHex:
282 attr.Value = fmt.Sprintf("0x%x", attrData[attrIdxData])
283 case AttrTypeFloat:
284 val := (*float32)(unsafe.Pointer(&attrData[attrIdxData]))
285 attr.Value = fmt.Sprintf("%g", *val)
286 case AttrTypeReference:
287 isValidString := false
288 if x.res != nil {
289 cfg := ConfigFirst
290 if attr.Name.Local == "icon" {
291 cfg = ConfigPngIcon
292 }
293
294 e, err := x.res.GetResourceEntryEx(attrData[attrIdxData], cfg)
295 if err == nil {
296 for i := 0; e.value.dataType == AttrTypeReference && i < 5; i++ {
297 lower, err := x.res.GetResourceEntryEx(e.value.data, cfg)
298 if err != nil {
299 break
300 }
301 e = lower
302 }
303 attr.Value, err = e.value.String()
304 isValidString = err == nil
305 }
306 }
307
308 if !isValidString && attr.Value == "" {
309 attr.Value = fmt.Sprintf("@%x", attrData[attrIdxData])
310 }
311 default:
312 attr.Value = strconv.FormatInt(int64(int32(attrData[attrIdxData])), 10)
313 }
314 tok.Attr = append(tok.Attr, attr)
315 }
316
317 return x.encoder.EncodeToken(tok)
318 }
319
320 func (x *binxmlParseInfo) parseTagEnd(r *io.LimitedReader) error {
321 var namespaceIdx, nameIdx uint32
322 if err := binary.Read(r, binary.LittleEndian, &namespaceIdx); err != nil {
323 return fmt.Errorf("error reading namespace idx: %s", err.Error())
324 }
325
326 if err := binary.Read(r, binary.LittleEndian, &nameIdx); err != nil {
327 return fmt.Errorf("error reading name idx: %s", err.Error())
328 }
329
330 namespace, err := x.strings.get(namespaceIdx)
331 if err != nil {
332 return fmt.Errorf("error decoding namespace: %s", err.Error())
333 }
334
335 name, err := x.strings.get(nameIdx)
336 if err != nil {
337 return fmt.Errorf("error decoding name: %s", err.Error())
338 }
339
340 return x.encoder.EncodeToken(xml.EndElement{Name: xml.Name{Local: name, Space: namespace}})
341 }
342
343 func (x *binxmlParseInfo) parseText(r *io.LimitedReader) error {
344 var idx uint32
345 if err := binary.Read(r, binary.LittleEndian, &idx); err != nil {
346 return fmt.Errorf("error reading idx: %s", err.Error())
347 }
348
349 text, err := x.strings.get(idx)
350 if err != nil {
351 return fmt.Errorf("error decoding idx: %s", err.Error())
352 }
353
354 if _, err := io.CopyN(ioutil.Discard, r, 2*4); err != nil {
355 return fmt.Errorf("error skipping: %s", err.Error())
356 }
357
358 return x.encoder.EncodeToken(xml.CharData(text))
359 }