Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(39)

Side by Side Diff: chrome/android/webapk/libs/client/src/org/chromium/webapk/lib/client/WebApkVerifySignature.java

Issue 2772483002: Commment signed webapks working and verified. (Closed)
Patch Set: Fix setting of flags. Created 3 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2017 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 package org.chromium.webapk.lib.client;
6
7 import static java.nio.ByteOrder.LITTLE_ENDIAN;
8
9 import android.support.annotation.IntDef;
10 import android.util.Log;
11
12 import java.nio.ByteBuffer;
13 import java.security.PublicKey;
14 import java.security.Signature;
15 import java.util.ArrayList;
16 import java.util.Collections;
17 import java.util.regex.Matcher;
18 import java.util.regex.Pattern;
19
20 /**
21 * WebApkVerifySignature reads in the APK file and verifies the WebApk signature . It reads the
22 * signature from the zip comment and verifies that it was signed by the public key passed.
23 */
24 public class WebApkVerifySignature {
25 /** Errors codes. */
26 @IntDef({
27 ERROR_OK, ERROR_BAD_APK, ERROR_EXTRA_FIELD_TOO_LARGE, ERROR_COMMENT_ TOO_LARGE,
28 ERROR_INCORRECT_SIGNATURE, ERROR_SIGNATURE_NOT_FOUND, ERROR_TOO_MANY _META_INF_FILES,
29 })
30 public @interface Error {}
31 public static final int ERROR_OK = 0;
32 public static final int ERROR_BAD_APK = 1;
33 public static final int ERROR_EXTRA_FIELD_TOO_LARGE = 2;
34 public static final int ERROR_COMMENT_TOO_LARGE = 3;
35 public static final int ERROR_INCORRECT_SIGNATURE = 4;
36 public static final int ERROR_SIGNATURE_NOT_FOUND = 5;
37 public static final int ERROR_TOO_MANY_META_INF_FILES = 6;
38
39 private static final String TAG = "WebApkVerifySignature";
40
41 /** End Of Central Directory Signature. */
42 private static final long EOCD_SIG = 0x06054b50;
43
44 /** Central Directory Signature. */
45 private static final long CD_SIG = 0x02014b50;
46
47 /** Local File Header Signature. */
48 private static final long LFH_SIG = 0x04034b50;
49
50 /** Minimum end-of-central-directory size in bytes, including variable lengt h file comment. */
51 private static final int MIN_EOCD_SIZE = 22;
52
53 /** Max end-of-central-directory size in bytes permitted. */
54 private static final int MAX_EOCD_SIZE = 64 * 1024;
55
56 /** Maximum number of META-INF/ files (allowing for dual signing). */
57 private static final int MAX_META_INF_FILES = 5;
58
59 /** The signature algorithm used (must also match with HASH). */
60 private static final String SIGNING_ALGORITHM = "SHA256withECDSA";
61
62 /**
63 * The pattern we look for in the APK/zip comment for signing key.
64 * An example is "webapk:0000:<hexvalues>". This pattern can appear anywhere
65 * in the comment but must be separated from any other parts with a
66 * separator that doesn't look like a hex character.
67 */
68 private static final Pattern WEBAPK_COMMENT_PATTERN =
69 Pattern.compile("webapk:\\d+:([a-fA-F0-9]+)");
70
71 /** Maximum comment length permitted. */
72 private static final int MAX_COMMENT_LENGTH = 0;
73
74 /** Maximum extra field length permitted. */
75 private static final int MAX_EXTRA_LENGTH = 8;
76
77 /** The memory buffer we are going to read the zip from. */
78 private final ByteBuffer mBuffer;
79
80 /** Number of total central directory (zip entry) records. */
81 private int mRecordCount;
82
83 /** Byte offset from the start where the central directory is found. */
84 private int mCentralDirOffset;
85
86 /** The zip archive comment as a UTF-8 string. */
87 private String mComment;
88
89 /**
90 * Sorted list of 'blocks' of memory we will cryptographically hash. We sort the blocks by
91 * filename to ensure a repeatable order.
92 */
93 private ArrayList<Block> mBlocks;
94
95 /** Block contains metadata about a zip entry. */
96 private static class Block implements Comparable<Block> {
97 String mFilename;
98 int mPosition;
99 int mHeaderSize;
100 int mCompressedSize;
101
102 Block(String filename, int position, int compressedSize) {
103 mFilename = filename;
104 mPosition = position;
105 mHeaderSize = 0;
106 mCompressedSize = compressedSize;
107 }
108
109 /** Added for Comparable, sort lexicographically. */
110 @Override
111 public int compareTo(Block o) {
112 return mFilename.compareTo(o.mFilename);
113 }
114
115 @Override
116 public boolean equals(Object o) {
117 if (!(o instanceof Block)) return false;
118 return mFilename.equals(((Block) o).mFilename);
119 }
120
121 @Override
122 public int hashCode() {
123 return mFilename.hashCode();
124 }
125 }
126
127 /** Constructor simply 'connects' to buffer passed. */
128 public WebApkVerifySignature(ByteBuffer buffer) {
129 mBuffer = buffer;
130 mBuffer.order(LITTLE_ENDIAN);
131 }
132
133 /**
134 * Read in the comment and directory. If there is no parseable comment we wo n't read the
135 * directory as there is no point (for speed). On success, all of our privat e variables will be
136 * set.
137 * @return OK on success.
138 */
139 public int read() {
140 try {
141 int err = readEOCD();
142 if (err != ERROR_OK) {
143 return err;
144 }
145 // Short circuit if no comment found.
146 if (parseCommentSignature(mComment) == null) {
147 return ERROR_SIGNATURE_NOT_FOUND;
148 }
149 err = readDirectory();
150 if (err != ERROR_OK) {
151 return err;
152 }
153 } catch (Exception e) {
154 return ERROR_BAD_APK;
155 }
156 return ERROR_OK;
157 }
158
159 /**
160 * verifySignature hashes all the files and then verifies the signature.
161 * @param pub The public key that it should be verified against.
162 * @return ERROR_OK if the public key signature verifies.
163 */
164 public int verifySignature(PublicKey pub) {
165 byte[] sig = parseCommentSignature(mComment);
166 if (sig == null || sig.length == 0) {
167 return ERROR_SIGNATURE_NOT_FOUND;
168 }
169 try {
170 Signature signature = Signature.getInstance(SIGNING_ALGORITHM);
171 signature.initVerify(pub);
172 int err = calculateHash(signature);
173 if (err != ERROR_OK) {
174 return err;
175 }
176 return signature.verify(sig) ? ERROR_OK : ERROR_INCORRECT_SIGNATURE;
177 } catch (Exception e) {
178 Log.e(TAG, "Exception calculating signature", e);
179 return ERROR_INCORRECT_SIGNATURE;
180 }
181 }
182
183 /**
184 * calculateHash goes through each file listed in blocks and calculates the SHA-256
185 * cryptographic hash.
186 * @param sig Signature object you can call update on.
187 */
188 public int calculateHash(Signature sig) throws Exception {
189 Collections.sort(mBlocks);
190 int metaInfCount = 0;
191 for (Block block : mBlocks) {
192 if (block.mFilename.indexOf("META-INF/") == 0) {
193 metaInfCount++;
194 if (metaInfCount > MAX_META_INF_FILES) {
195 // TODO(scottkirkwood): Add whitelist of files.
196 return ERROR_TOO_MANY_META_INF_FILES;
197 }
198
199 // Files that begin with META-INF/ are not part of the hash.
200 // This is because these signatures are added after we comment s igned the rest of
201 // the APK.
202 continue;
203 }
204
205 // Hash the filename length and filename to prevent Horton principle violation.
206 byte[] filename = block.mFilename.getBytes();
207 sig.update(intToLittleEndian(filename.length));
208 sig.update(filename);
209
210 // Also hash the block length for the same reason.
211 sig.update(intToLittleEndian(block.mCompressedSize));
212
213 seek(block.mPosition + block.mHeaderSize);
214 ByteBuffer slice = mBuffer.slice();
215 slice.limit(block.mCompressedSize);
216 sig.update(slice);
217 }
218 return ERROR_OK;
219 }
220
221 /**
222 * intToLittleEndian converts an integer to a little endian array of bytes.
223 * @param value Integer value to convert.
224 * @return Array of bytes.
225 */
226 private byte[] intToLittleEndian(int value) {
227 ByteBuffer buffer = ByteBuffer.allocate(4);
228 buffer.order(LITTLE_ENDIAN);
229 buffer.putInt(value);
230 return buffer.array();
231 }
232
233 /**
234 * Extract the bytes of the signature from the comment. We expect
235 * "webapk:0000:<hexvalues>" comment followed by hex values. Currently we ig nore the
236 * "key id" which is always "0000".
237 * @return the bytes of the signature.
238 */
239 static byte[] parseCommentSignature(String comment) {
240 Matcher m = WEBAPK_COMMENT_PATTERN.matcher(comment);
241 if (!m.find()) {
242 return null;
243 }
244 String s = m.group(1);
245 return hexToBytes(s);
246 }
247
248 /**
249 * Reads the End of Central Directory Record.
250 * @return ERROR_OK on success.
251 */
252 private int readEOCD() {
253 int start = findEOCDStart();
254 if (start < 0) {
255 return ERROR_BAD_APK;
256 }
257 // Signature(4), Disk Number(2), Start disk number(2), Records on this disk (2)
258 seek(start + 10);
259 mRecordCount = read2(); // Number of Central Directory records
260 seekDelta(4); // Size of central directory
261 mCentralDirOffset = read4(); // as bytes from start of file.
262 int commentLength = read2();
263 mComment = readString(commentLength);
264 return ERROR_OK;
265 }
266
267 /**
268 * Reads the central directory and populates {@link mBlocks} with data about each entry.
269 * @return ERROR_OK on success.
270 */
271 @Error
272 int readDirectory() {
273 mBlocks = new ArrayList<>(mRecordCount);
274 seek(mCentralDirOffset);
275 for (int i = 0; i < mRecordCount; i++) {
276 int signature = read4();
277 if (signature != CD_SIG) {
278 Log.d(TAG, "Missing Central Directory Signature");
279 return ERROR_BAD_APK;
280 }
281 // CreatorVersion(2), ReaderVersion(2), Flags(2), CompressionMethod( 2)
282 // ModifiedTime(2), ModifiedDate(2), CRC32(4) = 16 bytes
283 seekDelta(16);
284 int compressedSize = read4();
285 seekDelta(4); // uncompressed size
286 int fileNameLength = read2();
287 int extraLen = read2();
288 int fileCommentLength = read2();
289 seekDelta(8); // DiskNumberStart(2), Internal Attrs(2), External Att rs(4)
290 int offset = read4();
291 String filename = readString(fileNameLength);
292 seekDelta(extraLen + fileCommentLength);
293 if (extraLen > MAX_EXTRA_LENGTH) {
294 return ERROR_EXTRA_FIELD_TOO_LARGE;
295 }
296 if (fileCommentLength > MAX_COMMENT_LENGTH) {
297 return ERROR_COMMENT_TOO_LARGE;
298 }
299 mBlocks.add(new Block(filename, offset, compressedSize));
300 }
301
302 // Read the 'local file header' block to the size of the header in bytes .
303 for (Block block : mBlocks) {
304 seek(block.mPosition);
305 int signature = read4();
306 if (signature != LFH_SIG) {
307 Log.d(TAG, "LFH Signature missing");
308 return ERROR_BAD_APK;
309 }
310 // ReaderVersion(2), Flags(2), CompressionMethod(2),
311 // ModifiedTime (2), ModifiedDate(2), CRC32(4), CompressedSize(4),
312 // UncompressedSize(4) = 22 bytes
313 seekDelta(22);
314 int fileNameLength = read2();
315 int extraFieldLength = read2();
316 if (extraFieldLength > MAX_EXTRA_LENGTH) {
317 return ERROR_EXTRA_FIELD_TOO_LARGE;
318 }
319
320 block.mHeaderSize =
321 (mBuffer.position() - block.mPosition) + fileNameLength + ex traFieldLength;
322 }
323 return ERROR_OK;
324 }
325
326 /**
327 * We search buffer for EOCD_SIG and return the location where we found it. If the file has no
328 * comment it should seek only once.
329 * TODO(scottkirkwood): Use a Boyer-Moore search algorithm.
330 * @return Offset from start of buffer or -1 if not found.
331 */
332 private int findEOCDStart() {
333 int offset = mBuffer.limit() - MIN_EOCD_SIZE;
334 int minSearchOffset = Math.max(0, offset - MAX_EOCD_SIZE);
335 for (; offset >= minSearchOffset; offset--) {
336 seek(offset);
337 if (read4() == EOCD_SIG) {
338 // found!
339 return offset;
340 }
341 }
342 return -1;
343 }
344
345 /**
346 * Seek to this position.
347 * @param offset offset from start of file.
348 */
349 private void seek(int offset) {
350 mBuffer.position(offset);
351 }
352
353 /**
354 * Skip forward this number of bytes.
355 * @param delta number of bytes to seek forward.
356 */
357 private void seekDelta(int delta) {
358 mBuffer.position(mBuffer.position() + delta);
359 }
360
361 /**
362 * Reads two bytes in little endian format.
363 * @return short value read (as an int).
364 */
365 private int read2() {
366 return mBuffer.getShort();
367 }
368
369 /**
370 * Reads four bytes in little endian format.
371 * @return value read.
372 */
373 private int read4() {
374 return mBuffer.getInt();
375 }
376
377 /** Read {@link length} many bytes into a string. */
378 private String readString(int length) {
379 if (length <= 0) {
380 return "";
381 }
382 byte[] bytes = new byte[length];
383 mBuffer.get(bytes);
384 return new String(bytes);
385 }
386
387 /**
388 * Convert a hex string into bytes. We store hex in the signature as zip
389 * tools often don't like binary strings.
390 */
391 static byte[] hexToBytes(String s) {
392 int len = s.length();
393 if (len % 2 != 0) {
394 // Odd number of nibbles.
395 return null;
396 }
397 byte[] data = new byte[len / 2];
398 for (int i = 0; i < len; i += 2) {
399 data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
400 + Character.digit(s.charAt(i + 1), 16));
401 }
402 return data;
403 }
404 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698