File: manifest.go

package info (click to toggle)
golang-github-avast-apkverifier 0.0~git20191015.7330a51-11
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 1,224 kB
  • sloc: makefile: 11; sh: 8
file content (224 lines) | stat: -rw-r--r-- 4,746 bytes parent folder | download | duplicates (2)
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
package apkverifier

import (
	"errors"
	"fmt"
	"github.com/avast/apkparser"
	"io/ioutil"
	"strings"
)

const (
	attrSignatureVersionCase = "Signature-Version"
	attrManifestVersionCase  = "Manifest-Version"

	attrSignatureVersion     = "signature-version"
	attrName                 = "name"
	attrCreatedBy            = "created-by"
	attrDigestMainAttrSuffix = "-digest-manifest-main-attributes"
	attrDigestSuffix         = "-digest"
	attrDigestSigntoolSuffix = "-digest-manifest"
	attrAndroidApkSigned     = "x-android-apk-signed"
)

type manifest struct {
	rawData            []byte
	main               map[string]string
	entries            map[string]map[string]string
	chunks             map[string][]byte
	mainAttributtesEnd int
}

type manifestParserContext struct {
	man *manifest

	data                  []byte
	pos, mark             int
	consecutiveLineBreaks int
}

func parseManifest(f *apkparser.ZipReaderFile, withChunks bool) (*manifest, error) {
	if err := f.Open(); err != nil {
		return nil, err
	}
	defer f.Close()

	var err error
	for f.Next() {
		ctx := manifestParserContext{
			man: &manifest{
				main:    make(map[string]string),
				entries: make(map[string]map[string]string),
				chunks:  make(map[string][]byte),
			},
		}

		ctx.data, err = ioutil.ReadAll(f)
		if err != nil {
			continue
		}
		ctx.man.rawData = ctx.data

		if err = ctx.parse(withChunks); err != nil {
			continue
		}

		return ctx.man, nil
	}

	if err == nil {
		err = fmt.Errorf("Failed to open %s", f.Name)
	}

	return nil, err
}

func (ctx *manifestParserContext) parse(withChunks bool) error {
	for {
		n, v, singleBlock, err := ctx.readHeader()
		if err != nil {
			return err
		} else if !singleBlock {
			break
		}
		ctx.man.main[n] = v
	}

	ctx.man.mainAttributtesEnd = ctx.pos

	mark := ctx.pos
	for {
		n, v, singleBlock, err := ctx.readHeader()
		if err != nil {
			return err
		} else if !singleBlock {
			break
		}

		if n != attrName {
			return fmt.Errorf("Entry is not named")
		}

		entryNameValue := v
		entry := ctx.man.entries[entryNameValue]
		if entry == nil {
			entry = make(map[string]string)
			ctx.man.entries[entryNameValue] = entry
		}

		for {
			n, v, singleBlock, err = ctx.readHeader()
			if err != nil {
				return err
			} else if !singleBlock {
				break
			}
			entry[n] = v
		}

		if withChunks {
			if _, prs := ctx.man.chunks[entryNameValue]; prs {
				return fmt.Errorf("More than one entry with the same name!")
			}
			ctx.man.chunks[entryNameValue] = ctx.data[mark:ctx.pos]
			mark = ctx.pos
		}
	}
	return nil
}

func (ctx *manifestParserContext) readHeader() (name, value string, singleBlock bool, err error) {
	if ctx.consecutiveLineBreaks > 1 {
		ctx.consecutiveLineBreaks = 0
		return
	}

	mark := ctx.pos
	for ; ctx.pos < len(ctx.data); ctx.pos++ {
		if ctx.data[ctx.pos] == ':' {
			name = string(ctx.data[mark:ctx.pos])

			if ctx.pos+1 > len(ctx.data) || ctx.data[ctx.pos+1] != ' ' {
				err = fmt.Errorf("Invalid header structure '%s'", name)
				return
			}

			if !ctx.isValidName(name) {
				err = fmt.Errorf("Invalid attribute name in manifest: '%s'", name)
				return
			}

			// Attributes except for Manifest-Version and Signature-Version are case-insensitive
			// https://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Notes_on_Manifest_and_Signature_Files
			// Android however does not care and has case insensitive everything.
			if true /*name != attrManifestVersionCase && name != attrSignatureVersionCase*/ {
				name = strings.ToLower(name)
			}

			ctx.pos += 2 // For the ': ' separator
			break
		}
	}

	ctx.consecutiveLineBreaks = 0
	mark = ctx.pos
	last := ctx.pos
	lastCr := false

	for ctx.pos < len(ctx.data) {
		next := ctx.data[ctx.pos]
		ctx.pos++

		switch next {
		case 0:
			err = errors.New("NUL character in manifest")
			return
		case '\n':
			if lastCr {
				lastCr = false
			} else {
				ctx.consecutiveLineBreaks++
			}
			continue
		case '\r':
			lastCr = true
			ctx.consecutiveLineBreaks++
			continue
		case ' ':
			if ctx.consecutiveLineBreaks == 1 {
				value += string(ctx.data[mark:last])
				mark = ctx.pos
				ctx.consecutiveLineBreaks = 0
				continue
			}
		}

		if ctx.consecutiveLineBreaks >= 1 {
			ctx.pos--
			break
		}
		last = ctx.pos
	}

	if last > mark {
		value += string(ctx.data[mark:last])
	}
	singleBlock = ctx.consecutiveLineBreaks > 0
	return
}

func (ctx *manifestParserContext) isValidName(name string) bool {
	if len(name) == 0 || len(name) > 70 { // LINE_LENGTH_LIMIT = 72; - 2 for separator
		return false
	}

	for i := 0; i < len(name); i++ {
		c := name[i]
		if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
			c == '_' || c == '-' ||
			(c >= '0' && c <= '9')) {
			return false
		}
	}
	return true
}