blob: c45224a7fc4b02ccc20c64bd88d6806f4697792d [file] [log] [blame]
Geremy Condracee5bfd2014-06-11 13:38:45 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
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
17package com.android.verity;
18
Sami Tolvanen3380f2f2014-10-31 17:18:23 -070019import java.io.ByteArrayInputStream;
Geremy Condracee5bfd2014-06-11 13:38:45 -070020import java.io.IOException;
Paul Lawrence29131b92014-11-13 22:15:30 +000021import java.nio.ByteBuffer;
22import java.nio.ByteOrder;
Geremy Condracee5bfd2014-06-11 13:38:45 -070023import java.security.PrivateKey;
Sami Tolvanen3380f2f2014-10-31 17:18:23 -070024import java.security.PublicKey;
Paul Lawrence29131b92014-11-13 22:15:30 +000025import java.security.Security;
26import java.security.cert.X509Certificate;
Sami Tolvanen3380f2f2014-10-31 17:18:23 -070027import java.security.cert.Certificate;
28import java.security.cert.CertificateFactory;
Paul Lawrence29131b92014-11-13 22:15:30 +000029import java.security.cert.CertificateEncodingException;
Geremy Condracee5bfd2014-06-11 13:38:45 -070030import java.util.Arrays;
31import org.bouncycastle.asn1.ASN1Encodable;
32import org.bouncycastle.asn1.ASN1EncodableVector;
33import org.bouncycastle.asn1.ASN1Integer;
34import org.bouncycastle.asn1.ASN1Object;
Sami Tolvanen3380f2f2014-10-31 17:18:23 -070035import org.bouncycastle.asn1.ASN1ObjectIdentifier;
36import org.bouncycastle.asn1.ASN1OctetString;
Geremy Condracee5bfd2014-06-11 13:38:45 -070037import org.bouncycastle.asn1.ASN1Primitive;
Sami Tolvanen3380f2f2014-10-31 17:18:23 -070038import org.bouncycastle.asn1.ASN1Sequence;
Paul Lawrence29131b92014-11-13 22:15:30 +000039import org.bouncycastle.asn1.ASN1InputStream;
Geremy Condracee5bfd2014-06-11 13:38:45 -070040import org.bouncycastle.asn1.DEROctetString;
41import org.bouncycastle.asn1.DERPrintableString;
42import org.bouncycastle.asn1.DERSequence;
Geremy Condracee5bfd2014-06-11 13:38:45 -070043import org.bouncycastle.asn1.util.ASN1Dump;
44import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
Paul Lawrence29131b92014-11-13 22:15:30 +000045import org.bouncycastle.jce.provider.BouncyCastleProvider;
Geremy Condracee5bfd2014-06-11 13:38:45 -070046
47/**
48 * AndroidVerifiedBootSignature DEFINITIONS ::=
49 * BEGIN
Paul Lawrence29131b92014-11-13 22:15:30 +000050 * formatVersion ::= INTEGER
51 * certificate ::= Certificate
52 * algorithmIdentifier ::= SEQUENCE {
Geremy Condracee5bfd2014-06-11 13:38:45 -070053 * algorithm OBJECT IDENTIFIER,
54 * parameters ANY DEFINED BY algorithm OPTIONAL
55 * }
Paul Lawrence29131b92014-11-13 22:15:30 +000056 * authenticatedAttributes ::= SEQUENCE {
Geremy Condracee5bfd2014-06-11 13:38:45 -070057 * target CHARACTER STRING,
58 * length INTEGER
59 * }
Paul Lawrence29131b92014-11-13 22:15:30 +000060 * signature ::= OCTET STRING
Geremy Condracee5bfd2014-06-11 13:38:45 -070061 * END
62 */
63
64public class BootSignature extends ASN1Object
65{
66 private ASN1Integer formatVersion;
Paul Lawrence29131b92014-11-13 22:15:30 +000067 private ASN1Encodable certificate;
Geremy Condracee5bfd2014-06-11 13:38:45 -070068 private AlgorithmIdentifier algorithmIdentifier;
69 private DERPrintableString target;
70 private ASN1Integer length;
71 private DEROctetString signature;
Sami Tolvanen3380f2f2014-10-31 17:18:23 -070072 private PublicKey publicKey;
Geremy Condracee5bfd2014-06-11 13:38:45 -070073
Paul Lawrence29131b92014-11-13 22:15:30 +000074 private static final int FORMAT_VERSION = 1;
75
Sami Tolvanen3380f2f2014-10-31 17:18:23 -070076 /**
77 * Initializes the object for signing an image file
78 * @param target Target name, included in the signed data
79 * @param length Length of the image, included in the signed data
80 */
Geremy Condracee5bfd2014-06-11 13:38:45 -070081 public BootSignature(String target, int length) {
Paul Lawrence29131b92014-11-13 22:15:30 +000082 this.formatVersion = new ASN1Integer(FORMAT_VERSION);
Geremy Condracee5bfd2014-06-11 13:38:45 -070083 this.target = new DERPrintableString(target);
84 this.length = new ASN1Integer(length);
Geremy Condracee5bfd2014-06-11 13:38:45 -070085 }
86
Sami Tolvanen3380f2f2014-10-31 17:18:23 -070087 /**
88 * Initializes the object for verifying a signed image file
89 * @param signature Signature footer
90 */
91 public BootSignature(byte[] signature)
92 throws Exception {
93 ASN1InputStream stream = new ASN1InputStream(signature);
94 ASN1Sequence sequence = (ASN1Sequence) stream.readObject();
95
96 formatVersion = (ASN1Integer) sequence.getObjectAt(0);
97 if (formatVersion.getValue().intValue() != FORMAT_VERSION) {
98 throw new IllegalArgumentException("Unsupported format version");
99 }
100
101 certificate = sequence.getObjectAt(1);
102 byte[] encoded = ((ASN1Object) certificate).getEncoded();
103 ByteArrayInputStream bis = new ByteArrayInputStream(encoded);
104
105 CertificateFactory cf = CertificateFactory.getInstance("X.509");
106 X509Certificate c = (X509Certificate) cf.generateCertificate(bis);
107 publicKey = c.getPublicKey();
108
109 ASN1Sequence algId = (ASN1Sequence) sequence.getObjectAt(2);
110 algorithmIdentifier = new AlgorithmIdentifier(
111 (ASN1ObjectIdentifier) algId.getObjectAt(0));
112
113 ASN1Sequence attrs = (ASN1Sequence) sequence.getObjectAt(3);
114 target = (DERPrintableString) attrs.getObjectAt(0);
115 length = (ASN1Integer) attrs.getObjectAt(1);
116
117 this.signature = (DEROctetString) sequence.getObjectAt(4);
118 }
119
Geremy Condracee5bfd2014-06-11 13:38:45 -0700120 public ASN1Object getAuthenticatedAttributes() {
121 ASN1EncodableVector attrs = new ASN1EncodableVector();
122 attrs.add(target);
123 attrs.add(length);
124 return new DERSequence(attrs);
125 }
126
127 public byte[] getEncodedAuthenticatedAttributes() throws IOException {
128 return getAuthenticatedAttributes().getEncoded();
129 }
130
Paul Lawrence29131b92014-11-13 22:15:30 +0000131 public void setSignature(byte[] sig, AlgorithmIdentifier algId) {
132 algorithmIdentifier = algId;
Geremy Condracee5bfd2014-06-11 13:38:45 -0700133 signature = new DEROctetString(sig);
134 }
135
Paul Lawrence29131b92014-11-13 22:15:30 +0000136 public void setCertificate(X509Certificate cert)
137 throws Exception, IOException, CertificateEncodingException {
138 ASN1InputStream s = new ASN1InputStream(cert.getEncoded());
139 certificate = s.readObject();
140 }
141
Geremy Condracee5bfd2014-06-11 13:38:45 -0700142 public byte[] generateSignableImage(byte[] image) throws IOException {
143 byte[] attrs = getEncodedAuthenticatedAttributes();
144 byte[] signable = Arrays.copyOf(image, image.length + attrs.length);
145 for (int i=0; i < attrs.length; i++) {
146 signable[i+image.length] = attrs[i];
147 }
148 return signable;
149 }
150
151 public byte[] sign(byte[] image, PrivateKey key) throws Exception {
152 byte[] signable = generateSignableImage(image);
Geremy Condrad66cefd2014-08-14 16:44:31 -0700153 return Utils.sign(key, signable);
Geremy Condracee5bfd2014-06-11 13:38:45 -0700154 }
155
Sami Tolvanen3380f2f2014-10-31 17:18:23 -0700156 public boolean verify(byte[] image) throws Exception {
157 if (length.getValue().intValue() != image.length) {
158 throw new IllegalArgumentException("Invalid image length");
159 }
160
161 byte[] signable = generateSignableImage(image);
162 return Utils.verify(publicKey, signable, signature.getOctets(),
163 algorithmIdentifier);
164 }
165
Geremy Condracee5bfd2014-06-11 13:38:45 -0700166 public ASN1Primitive toASN1Primitive() {
167 ASN1EncodableVector v = new ASN1EncodableVector();
168 v.add(formatVersion);
Paul Lawrence29131b92014-11-13 22:15:30 +0000169 v.add(certificate);
Geremy Condracee5bfd2014-06-11 13:38:45 -0700170 v.add(algorithmIdentifier);
171 v.add(getAuthenticatedAttributes());
172 v.add(signature);
173 return new DERSequence(v);
174 }
175
Paul Lawrence29131b92014-11-13 22:15:30 +0000176 public static int getSignableImageSize(byte[] data) throws Exception {
177 if (!Arrays.equals(Arrays.copyOfRange(data, 0, 8),
178 "ANDROID!".getBytes("US-ASCII"))) {
179 throw new IllegalArgumentException("Invalid image header: missing magic");
180 }
181
182 ByteBuffer image = ByteBuffer.wrap(data);
183 image.order(ByteOrder.LITTLE_ENDIAN);
184
185 image.getLong(); // magic
186 int kernelSize = image.getInt();
187 image.getInt(); // kernel_addr
188 int ramdskSize = image.getInt();
189 image.getInt(); // ramdisk_addr
190 int secondSize = image.getInt();
191 image.getLong(); // second_addr + tags_addr
192 int pageSize = image.getInt();
193
194 int length = pageSize // include the page aligned image header
195 + ((kernelSize + pageSize - 1) / pageSize) * pageSize
196 + ((ramdskSize + pageSize - 1) / pageSize) * pageSize
197 + ((secondSize + pageSize - 1) / pageSize) * pageSize;
198
199 length = ((length + pageSize - 1) / pageSize) * pageSize;
200
201 if (length <= 0) {
202 throw new IllegalArgumentException("Invalid image header: invalid length");
203 }
204
205 return length;
206 }
207
Geremy Condracee5bfd2014-06-11 13:38:45 -0700208 public static void doSignature( String target,
209 String imagePath,
210 String keyPath,
Paul Lawrence29131b92014-11-13 22:15:30 +0000211 String certPath,
Geremy Condracee5bfd2014-06-11 13:38:45 -0700212 String outPath) throws Exception {
Paul Lawrence29131b92014-11-13 22:15:30 +0000213
Geremy Condracee5bfd2014-06-11 13:38:45 -0700214 byte[] image = Utils.read(imagePath);
Paul Lawrence29131b92014-11-13 22:15:30 +0000215 int signableSize = getSignableImageSize(image);
216
217 if (signableSize < image.length) {
218 System.err.println("NOTE: truncating file " + imagePath +
219 " from " + image.length + " to " + signableSize + " bytes");
220 image = Arrays.copyOf(image, signableSize);
221 } else if (signableSize > image.length) {
222 throw new IllegalArgumentException("Invalid image: too short, expected " +
223 signableSize + " bytes");
224 }
225
Geremy Condracee5bfd2014-06-11 13:38:45 -0700226 BootSignature bootsig = new BootSignature(target, image.length);
Paul Lawrence29131b92014-11-13 22:15:30 +0000227
228 X509Certificate cert = Utils.loadPEMCertificate(certPath);
229 bootsig.setCertificate(cert);
230
231 PrivateKey key = Utils.loadDERPrivateKeyFromFile(keyPath);
232 bootsig.setSignature(bootsig.sign(image, key),
233 Utils.getSignatureAlgorithmIdentifier(key));
234
Geremy Condrad66cefd2014-08-14 16:44:31 -0700235 byte[] encoded_bootsig = bootsig.getEncoded();
236 byte[] image_with_metadata = Arrays.copyOf(image, image.length + encoded_bootsig.length);
Paul Lawrence29131b92014-11-13 22:15:30 +0000237
238 System.arraycopy(encoded_bootsig, 0, image_with_metadata,
239 image.length, encoded_bootsig.length);
240
Geremy Condrad66cefd2014-08-14 16:44:31 -0700241 Utils.write(image_with_metadata, outPath);
Geremy Condracee5bfd2014-06-11 13:38:45 -0700242 }
243
Sami Tolvanen3380f2f2014-10-31 17:18:23 -0700244 public static void verifySignature(String imagePath) throws Exception {
245 byte[] image = Utils.read(imagePath);
246 int signableSize = getSignableImageSize(image);
247
248 if (signableSize >= image.length) {
249 throw new IllegalArgumentException("Invalid image: not signed");
250 }
251
252 byte[] signature = Arrays.copyOfRange(image, signableSize, image.length);
253 BootSignature bootsig = new BootSignature(signature);
254
255 try {
256 if (bootsig.verify(Arrays.copyOf(image, signableSize))) {
257 System.err.println("Signature is VALID");
258 System.exit(0);
259 } else {
260 System.err.println("Signature is INVALID");
261 }
262 } catch (Exception e) {
263 e.printStackTrace(System.err);
264 }
265 System.exit(1);
266 }
267
Sami Tolvanen40193d92014-11-14 11:00:18 +0000268 /* Example usage for signing a boot image using dev keys:
269 java -cp \
270 ../../../out/host/common/obj/JAVA_LIBRARIES/BootSignature_intermediates/ \
271 classes/com.android.verity.BootSignature \
272 /boot \
273 ../../../out/target/product/$PRODUCT/boot.img \
274 ../../../build/target/product/security/verity.pk8 \
275 ../../../build/target/product/security/verity.x509.pem \
276 /tmp/boot.img.signed
Paul Lawrence29131b92014-11-13 22:15:30 +0000277 */
Geremy Condracee5bfd2014-06-11 13:38:45 -0700278 public static void main(String[] args) throws Exception {
Paul Lawrence29131b92014-11-13 22:15:30 +0000279 Security.addProvider(new BouncyCastleProvider());
Sami Tolvanen3380f2f2014-10-31 17:18:23 -0700280
281 if ("-verify".equals(args[0])) {
Sami Tolvanen40193d92014-11-14 11:00:18 +0000282 /* args[1] is the path to a signed boot image */
Sami Tolvanen3380f2f2014-10-31 17:18:23 -0700283 verifySignature(args[1]);
284 } else {
Sami Tolvanen40193d92014-11-14 11:00:18 +0000285 /* args[0] is the target name, typically /boot
286 args[1] is the path to a boot image to sign
287 args[2] is the path to a private key
288 args[3] is the path to the matching public key certificate
289 args[4] is the path where to output the signed boot image
290 */
Sami Tolvanen3380f2f2014-10-31 17:18:23 -0700291 doSignature(args[0], args[1], args[2], args[3], args[4]);
292 }
Geremy Condracee5bfd2014-06-11 13:38:45 -0700293 }
Paul Lawrence29131b92014-11-13 22:15:30 +0000294}