| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | package signjar |
| 18 | |
| 19 | import ( |
| 20 | "bytes" |
| 21 | "crypto" |
| 22 | "encoding/base64" |
| 23 | "errors" |
| 24 | "fmt" |
| 25 | "net/http" |
| 26 | "sort" |
| 27 | "strings" |
| 28 | |
| 29 | "github.com/sassoftware/relic/v7/config" |
| 30 | "github.com/sassoftware/relic/v7/lib/x509tools" |
| 31 | ) |
| 32 | |
| 33 | // See https://docs.oracle.com/javase/8/docs/technotes/guides/jar/jar.html#JAR_Manifest |
| 34 | |
| 35 | const ( |
| 36 | metaInf = "META-INF/" |
| 37 | manifestName = metaInf + "MANIFEST.MF" |
| 38 | ) |
| 39 | |
| 40 | var ErrManifestLineEndings = errors.New("manifest has incorrect line ending sequence") |
| 41 | |
| 42 | type FilesMap struct { |
| 43 | Main http.Header |
| 44 | Order []string |
| 45 | Files map[string]http.Header |
| 46 | } |
| 47 | |
| 48 | func ParseManifest(manifest []byte) (files *FilesMap, err error) { |
| 49 | files, malformed, err := parseManifest(manifest) |
| 50 | if err != nil { |
| 51 | return nil, err |
| 52 | } else if malformed { |
| 53 | return nil, ErrManifestLineEndings |
| 54 | } |
| 55 | return files, nil |
| 56 | } |
| 57 | |
| 58 | func parseManifest(manifest []byte) (files *FilesMap, malformed bool, err error) { |
| 59 | sections, malformed := splitManifest(manifest) |
| 60 | if len(sections) == 0 { |
| 61 | return nil, false, errors.New("manifest has no sections") |
| 62 | } |
| 63 | files = &FilesMap{ |
| 64 | Order: make([]string, 0, len(sections)-1), |
| 65 | Files: make(map[string]http.Header, len(sections)-1), |
| 66 | } |
| 67 | for i, section := range sections { |
| 68 | if i > 0 && len(section) == 0 { |
| 69 | continue |
| 70 | } |
| 71 | hdr, err := parseSection(section) |
| 72 | if err != nil { |
| 73 | return nil, false, err |
| 74 | } |
| 75 | if i == 0 { |
| 76 | files.Main = hdr |
| 77 | } else { |
| 78 | name := hdr.Get("Name") |
| 79 | if name == "" { |
| 80 | return nil, false, errors.New("manifest has section with no \"Name\" attribute") |
| 81 | } |
| 82 | files.Order = append(files.Order, name) |
| 83 | files.Files[name] = hdr |
| 84 | } |
| 85 | } |
| 86 | return files, malformed, nil |
| 87 | } |
| 88 | |
| 89 | func (m *FilesMap) Dump() []byte { |
| 90 | var out bytes.Buffer |
| 91 | writeSection(&out, m.Main, "Manifest-Version") |
| 92 | for _, name := range m.Order { |
| 93 | section := m.Files[name] |
| 94 | if section != nil { |
| 95 | writeSection(&out, section, "Name") |
| 96 | } |
| 97 | } |
| 98 | return out.Bytes() |
| 99 | } |
| 100 | |
| 101 | func splitManifest(manifest []byte) ([][]byte, bool) { |
| 102 | var malformed bool |
| 103 | sections := make([][]byte, 0) |
| 104 | for len(manifest) != 0 { |
| 105 | i1 := bytes.Index(manifest, []byte("\r\n\r\n")) |
| 106 | i2 := bytes.Index(manifest, []byte("\n\n")) |
| 107 | var idx int |
| 108 | switch { |
| 109 | case i1 >= 0: |
| 110 | idx = i1 + 4 |
| 111 | case i2 >= 0: |
| 112 | idx = i2 + 2 |
| 113 | default: |
| 114 | // If there is not a proper 2x line ending, |
| 115 | // then it's technically not valid but we can sign it anyway |
| 116 | // as long as it gets rewritten with correct endings. |
| 117 | idx = len(manifest) |
| 118 | malformed = true |
| 119 | } |
| 120 | section := manifest[:idx] |
| 121 | manifest = manifest[idx:] |
| 122 | if len(bytes.TrimSpace(section)) == 0 { |
| 123 | // Excessive line endings have created an empty section |
| 124 | malformed = true |
| 125 | continue |
| 126 | } |
| 127 | sections = append(sections, section) |
| 128 | } |
| 129 | return sections, malformed |
| 130 | } |
| 131 | |
| 132 | func parseSection(section []byte) (http.Header, error) { |
| 133 | section = bytes.ReplaceAll(section, []byte("\r\n"), []byte{'\n'}) |
| 134 | section = bytes.ReplaceAll(section, []byte("\n "), []byte{}) |
| 135 | keys := bytes.Split(section, []byte{'\n'}) |
| 136 | hdr := make(http.Header) |
| 137 | for _, line := range keys { |
| 138 | if len(line) == 0 { |
| 139 | continue |
| 140 | } |
| 141 | idx := bytes.IndexRune(line, ':') |
| 142 | if idx < 0 { |
| 143 | return nil, errors.New("jar manifest is malformed") |
| 144 | } |
| 145 | key := strings.TrimSpace(string(line[:idx])) |
| 146 | value := strings.TrimSpace(string(line[idx+1:])) |
| 147 | hdr.Set(key, value) |
| 148 | } |
| 149 | return hdr, nil |
| 150 | } |
| 151 | |
| 152 | func hashSection(hash crypto.Hash, section []byte) string { |
| 153 | d := hash.New() |
| 154 | d.Write(section) |
| 155 | return base64.StdEncoding.EncodeToString(d.Sum(nil)) |
| 156 | } |
| 157 | |
| 158 | // Transform a MANIFEST.MF into a *.SF by digesting each section with the |
| 159 | // specified hash |
| 160 | func DigestManifest(manifest []byte, hash crypto.Hash, sectionsOnly, apkV2 bool) ([]byte, error) { |
| 161 | sections, malformed := splitManifest(manifest) |
| 162 | if malformed { |
| 163 | return nil, ErrManifestLineEndings |
| 164 | } |
| 165 | hashName := x509tools.HashNames[hash] |
| 166 | if hashName == "" { |
| 167 | return nil, errors.New("unsupported hash type") |
| 168 | } |
| 169 | var output bytes.Buffer |
| 170 | writeAttribute(&output, "Signature-Version", "1.0") |
| 171 | writeAttribute(&output, hashName+"-Digest-Manifest-Main-Attributes", hashSection(hash, sections[0])) |
| 172 | if !sectionsOnly { |
| 173 | writeAttribute(&output, hashName+"-Digest-Manifest", hashSection(hash, manifest)) |
| 174 | } |
| 175 | writeAttribute(&output, "Created-By", fmt.Sprintf("%s (%s)", config.UserAgent, config.Author)) |
| 176 | if apkV2 { |
| 177 | writeAttribute(&output, "X-Android-APK-Signed", "2") |
| 178 | } |
| 179 | output.WriteString("\r\n") |
| 180 | for _, section := range sections[1:] { |
| 181 | hdr, err := parseSection(section) |
| 182 | if err != nil { |
| 183 | return nil, err |
| 184 | } |
| 185 | name := hdr.Get("Name") |
| 186 | if name == "" { |
| 187 | return nil, errors.New("File section was missing Name attribute") |
| 188 | } |
| 189 | writeAttribute(&output, "Name", name) |
| 190 | writeAttribute(&output, hashName+"-Digest", hashSection(hash, section)) |
| 191 | output.WriteString("\r\n") |
| 192 | } |
| 193 | return output.Bytes(), nil |
| 194 | } |
| 195 | |
| 196 | const maxLineLength = 70 |
| 197 | |
| 198 | // Write a key-value pair, wrapping long lines as necessary |
| 199 | func writeAttribute(out *bytes.Buffer, key, value string) { |
| 200 | line := []byte(fmt.Sprintf("%s: %s", key, value)) |
| 201 | for i := 0; i < len(line); { |
| 202 | goal := maxLineLength |
| 203 | if i != 0 { |
| 204 | out.Write([]byte{' '}) |
| 205 | goal-- |
| 206 | } |
| 207 | j := i + goal |
| 208 | if j > len(line) { |
| 209 | j = len(line) |
| 210 | } |
| 211 | out.Write(line[i:j]) |
| 212 | out.Write([]byte("\r\n")) |
| 213 | i = j |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | func writeSection(out *bytes.Buffer, hdr http.Header, first string) { |
| 218 | value := hdr.Get(first) |
| 219 | if value != "" { |
| 220 | writeAttribute(out, first, value) |
| 221 | } |
| 222 | keys := make([]string, 0, len(hdr)) |
| 223 | for key := range hdr { |
| 224 | if key == first { |
| 225 | continue |
| 226 | } |
| 227 | keys = append(keys, key) |
| 228 | } |
| 229 | sort.Strings(keys) |
| 230 | for _, key := range keys { |
| 231 | for _, value := range hdr[key] { |
| 232 | writeAttribute(out, key, value) |
| 233 | } |
| 234 | } |
| 235 | out.Write([]byte("\r\n")) |
| 236 | } |