blob: 9601e9ad7ccb050d8613298694ca269b8d600221 [file] [log] [blame]
Geremy Condrab6310842012-08-23 22:00:15 -07001/*
2 * Copyright (C) 2012 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.server.updates;
18
19import android.content.BroadcastReceiver;
20import android.content.ContentResolver;
21import android.content.Context;
22import android.content.Intent;
23import android.provider.Settings;
24import android.os.FileUtils;
25import android.util.Base64;
Geremy Condra7c65e392012-09-11 16:57:17 -070026import android.util.EventLog;
Geremy Condrab6310842012-08-23 22:00:15 -070027import android.util.Slog;
28
Geremy Condra7c65e392012-09-11 16:57:17 -070029import com.android.server.EventLogTags;
30
Geremy Condrab6310842012-08-23 22:00:15 -070031import java.io.ByteArrayInputStream;
32import java.io.File;
33import java.io.FileNotFoundException;
34import java.io.FileOutputStream;
35import java.io.InputStream;
36import java.io.IOException;
37import java.security.cert.Certificate;
38import java.security.cert.CertificateException;
39import java.security.cert.CertificateFactory;
40import java.security.cert.X509Certificate;
41import java.security.MessageDigest;
42import java.security.NoSuchAlgorithmException;
43import java.security.Signature;
44import java.security.SignatureException;
45
46import libcore.io.IoUtils;
47
48public class ConfigUpdateInstallReceiver extends BroadcastReceiver {
49
50 private static final String TAG = "ConfigUpdateInstallReceiver";
51
52 private static final String EXTRA_CONTENT_PATH = "CONTENT_PATH";
53 private static final String EXTRA_REQUIRED_HASH = "REQUIRED_HASH";
54 private static final String EXTRA_SIGNATURE = "SIGNATURE";
55 private static final String EXTRA_VERSION_NUMBER = "VERSION";
56
57 private static final String UPDATE_CERTIFICATE_KEY = "config_update_certificate";
58
Geremy Condraa2dffda2013-04-06 14:01:40 -070059 protected final File updateDir;
60 protected final File updateContent;
61 protected final File updateVersion;
Geremy Condrab6310842012-08-23 22:00:15 -070062
63 public ConfigUpdateInstallReceiver(String updateDir, String updateContentPath,
64 String updateMetadataPath, String updateVersionPath) {
65 this.updateDir = new File(updateDir);
66 this.updateContent = new File(updateDir, updateContentPath);
67 File updateMetadataDir = new File(updateDir, updateMetadataPath);
68 this.updateVersion = new File(updateMetadataDir, updateVersionPath);
69 }
70
71 @Override
72 public void onReceive(final Context context, final Intent intent) {
73 new Thread() {
74 @Override
75 public void run() {
76 try {
77 // get the certificate from Settings.Secure
78 X509Certificate cert = getCert(context.getContentResolver());
79 // get the content path from the extras
Geremy Condraad462d22013-01-30 11:19:54 -080080 byte[] altContent = getAltContent(intent);
Geremy Condrab6310842012-08-23 22:00:15 -070081 // get the version from the extras
82 int altVersion = getVersionFromIntent(intent);
83 // get the previous value from the extras
84 String altRequiredHash = getRequiredHashFromIntent(intent);
85 // get the signature from the extras
86 String altSig = getSignatureFromIntent(intent);
87 // get the version currently being used
88 int currentVersion = getCurrentVersion();
89 // get the hash of the currently used value
90 String currentHash = getCurrentHash(getCurrentContent());
91 if (!verifyVersion(currentVersion, altVersion)) {
Geremy Condra0967a9e2012-09-19 21:22:42 -070092 Slog.i(TAG, "Not installing, new version is <= current version");
Geremy Condrab6310842012-08-23 22:00:15 -070093 } else if (!verifyPreviousHash(currentHash, altRequiredHash)) {
Geremy Condrabeb9d5392012-09-17 13:29:56 -070094 EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED,
95 "Current hash did not match required value");
Geremy Condrab6310842012-08-23 22:00:15 -070096 } else if (!verifySignature(altContent, altVersion, altRequiredHash, altSig,
97 cert)) {
Geremy Condrabeb9d5392012-09-17 13:29:56 -070098 EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED,
99 "Signature did not verify");
Geremy Condrab6310842012-08-23 22:00:15 -0700100 } else {
101 // install the new content
102 Slog.i(TAG, "Found new update, installing...");
103 install(altContent, altVersion);
104 Slog.i(TAG, "Installation successful");
Geremy Condra4e7f7e82013-03-26 21:09:01 -0700105 postInstall(context, intent);
Geremy Condrab6310842012-08-23 22:00:15 -0700106 }
107 } catch (Exception e) {
108 Slog.e(TAG, "Could not update content!", e);
Geremy Condrabeb9d5392012-09-17 13:29:56 -0700109 // keep the error message <= 100 chars
110 String errMsg = e.toString();
111 if (errMsg.length() > 100) {
112 errMsg = errMsg.substring(0, 99);
113 }
114 EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED, errMsg);
Geremy Condrab6310842012-08-23 22:00:15 -0700115 }
116 }
117 }.start();
118 }
119
120 private X509Certificate getCert(ContentResolver cr) {
121 // get the cert from settings
122 String cert = Settings.Secure.getString(cr, UPDATE_CERTIFICATE_KEY);
123 // convert it into a real certificate
124 try {
125 byte[] derCert = Base64.decode(cert.getBytes(), Base64.DEFAULT);
126 InputStream istream = new ByteArrayInputStream(derCert);
127 CertificateFactory cf = CertificateFactory.getInstance("X.509");
128 return (X509Certificate) cf.generateCertificate(istream);
129 } catch (CertificateException e) {
Robert Greenwaltc6fa2372012-09-24 13:57:16 -0700130 throw new IllegalStateException("Got malformed certificate from settings, ignoring");
Geremy Condrab6310842012-08-23 22:00:15 -0700131 }
132 }
133
134 private String getContentFromIntent(Intent i) {
135 String extraValue = i.getStringExtra(EXTRA_CONTENT_PATH);
136 if (extraValue == null) {
137 throw new IllegalStateException("Missing required content path, ignoring.");
138 }
139 return extraValue;
140 }
141
142 private int getVersionFromIntent(Intent i) throws NumberFormatException {
143 String extraValue = i.getStringExtra(EXTRA_VERSION_NUMBER);
144 if (extraValue == null) {
145 throw new IllegalStateException("Missing required version number, ignoring.");
146 }
147 return Integer.parseInt(extraValue.trim());
148 }
149
150 private String getRequiredHashFromIntent(Intent i) {
151 String extraValue = i.getStringExtra(EXTRA_REQUIRED_HASH);
152 if (extraValue == null) {
153 throw new IllegalStateException("Missing required previous hash, ignoring.");
154 }
155 return extraValue.trim();
156 }
157
158 private String getSignatureFromIntent(Intent i) {
159 String extraValue = i.getStringExtra(EXTRA_SIGNATURE);
160 if (extraValue == null) {
161 throw new IllegalStateException("Missing required signature, ignoring.");
162 }
163 return extraValue.trim();
164 }
165
166 private int getCurrentVersion() throws NumberFormatException {
167 try {
168 String strVersion = IoUtils.readFileAsString(updateVersion.getCanonicalPath()).trim();
169 return Integer.parseInt(strVersion);
170 } catch (IOException e) {
Robert Greenwaltc6fa2372012-09-24 13:57:16 -0700171 Slog.i(TAG, "Couldn't find current metadata, assuming first update");
Geremy Condrab6310842012-08-23 22:00:15 -0700172 return 0;
173 }
174 }
175
Geremy Condraad462d22013-01-30 11:19:54 -0800176 private byte[] getAltContent(Intent i) throws IOException {
177 return IoUtils.readFileAsByteArray(getContentFromIntent(i));
Geremy Condrab6310842012-08-23 22:00:15 -0700178 }
179
Geremy Condraad462d22013-01-30 11:19:54 -0800180 private byte[] getCurrentContent() {
Geremy Condrab6310842012-08-23 22:00:15 -0700181 try {
Geremy Condraad462d22013-01-30 11:19:54 -0800182 return IoUtils.readFileAsByteArray(updateContent.getCanonicalPath());
Geremy Condrab6310842012-08-23 22:00:15 -0700183 } catch (IOException e) {
Robert Greenwaltc6fa2372012-09-24 13:57:16 -0700184 Slog.i(TAG, "Failed to read current content, assuming first update!");
Geremy Condrab6310842012-08-23 22:00:15 -0700185 return null;
186 }
187 }
188
Geremy Condraad462d22013-01-30 11:19:54 -0800189 private static String getCurrentHash(byte[] content) {
Geremy Condrab6310842012-08-23 22:00:15 -0700190 if (content == null) {
191 return "0";
192 }
193 try {
194 MessageDigest dgst = MessageDigest.getInstance("SHA512");
Geremy Condraad462d22013-01-30 11:19:54 -0800195 byte[] fingerprint = dgst.digest(content);
Geremy Condrab6310842012-08-23 22:00:15 -0700196 return IntegralToString.bytesToHexString(fingerprint, false);
197 } catch (NoSuchAlgorithmException e) {
198 throw new AssertionError(e);
199 }
200 }
201
202 private boolean verifyVersion(int current, int alternative) {
203 return (current < alternative);
204 }
205
206 private boolean verifyPreviousHash(String current, String required) {
207 // this is an optional value- if the required field is NONE then we ignore it
208 if (required.equals("NONE")) {
209 return true;
210 }
211 // otherwise, verify that we match correctly
212 return current.equals(required);
213 }
214
Geremy Condraad462d22013-01-30 11:19:54 -0800215 private boolean verifySignature(byte[] content, int version, String requiredPrevious,
Geremy Condrab6310842012-08-23 22:00:15 -0700216 String signature, X509Certificate cert) throws Exception {
217 Signature signer = Signature.getInstance("SHA512withRSA");
218 signer.initVerify(cert);
Geremy Condraad462d22013-01-30 11:19:54 -0800219 signer.update(content);
Geremy Condrab6310842012-08-23 22:00:15 -0700220 signer.update(Long.toString(version).getBytes());
221 signer.update(requiredPrevious.getBytes());
222 return signer.verify(Base64.decode(signature.getBytes(), Base64.DEFAULT));
223 }
224
Geremy Condraa2dffda2013-04-06 14:01:40 -0700225 protected void writeUpdate(File dir, File file, byte[] content) throws IOException {
Geremy Condrab6310842012-08-23 22:00:15 -0700226 FileOutputStream out = null;
227 File tmp = null;
228 try {
Geremy Condra755b8772012-09-11 01:11:02 -0700229 // create the parents for the destination file
230 File parent = file.getParentFile();
231 parent.mkdirs();
232 // check that they were created correctly
233 if (!parent.exists()) {
234 throw new IOException("Failed to create directory " + parent.getCanonicalPath());
235 }
Geremy Condra9765f942013-04-04 17:48:09 -0700236 // create the temporary file
237 tmp = File.createTempFile("journal", "", dir);
Geremy Condrab6310842012-08-23 22:00:15 -0700238 // mark tmp -rw-r--r--
239 tmp.setReadable(true, false);
240 // write to it
241 out = new FileOutputStream(tmp);
Geremy Condraad462d22013-01-30 11:19:54 -0800242 out.write(content);
Geremy Condrab6310842012-08-23 22:00:15 -0700243 // sync to disk
Geremy Condra755b8772012-09-11 01:11:02 -0700244 out.getFD().sync();
Geremy Condrab6310842012-08-23 22:00:15 -0700245 // atomic rename
Geremy Condra755b8772012-09-11 01:11:02 -0700246 if (!tmp.renameTo(file)) {
247 throw new IOException("Failed to atomically rename " + file.getCanonicalPath());
248 }
Geremy Condrab6310842012-08-23 22:00:15 -0700249 } finally {
250 if (tmp != null) {
251 tmp.delete();
252 }
253 IoUtils.closeQuietly(out);
254 }
255 }
256
Geremy Condra78a4c712013-01-30 11:20:26 -0800257 protected void install(byte[] content, int version) throws IOException {
Geremy Condrab6310842012-08-23 22:00:15 -0700258 writeUpdate(updateDir, updateContent, content);
Geremy Condraad462d22013-01-30 11:19:54 -0800259 writeUpdate(updateDir, updateVersion, Long.toString(version).getBytes());
Geremy Condrab6310842012-08-23 22:00:15 -0700260 }
Geremy Condra4e7f7e82013-03-26 21:09:01 -0700261
262 protected void postInstall(Context context, Intent intent) {
263 }
Geremy Condrab6310842012-08-23 22:00:15 -0700264}