2 * Copyright (C) 2012 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server.updates;
19 import android.content.BroadcastReceiver;
20 import android.content.ContentResolver;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.provider.Settings;
24 import android.os.FileUtils;
25 import android.util.Base64;
26 import android.util.EventLog;
27 import android.util.Slog;
29 import com.android.server.EventLogTags;
31 import java.io.ByteArrayInputStream;
33 import java.io.FileNotFoundException;
34 import java.io.FileOutputStream;
35 import java.io.InputStream;
36 import java.io.IOException;
37 import java.security.cert.Certificate;
38 import java.security.cert.CertificateException;
39 import java.security.cert.CertificateFactory;
40 import java.security.cert.X509Certificate;
41 import java.security.MessageDigest;
42 import java.security.NoSuchAlgorithmException;
43 import java.security.Signature;
44 import java.security.SignatureException;
46 import libcore.io.IoUtils;
48 public class ConfigUpdateInstallReceiver extends BroadcastReceiver {
50 private static final String TAG = "ConfigUpdateInstallReceiver";
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";
57 private static final String UPDATE_CERTIFICATE_KEY = "config_update_certificate";
59 private final File updateDir;
60 private final File updateContent;
61 private final File updateVersion;
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);
72 public void onReceive(final Context context, final Intent intent) {
77 // get the certificate from Settings.Secure
78 X509Certificate cert = getCert(context.getContentResolver());
79 // get the content path from the extras
80 String altContent = getAltContent(intent);
81 // 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)) {
92 Slog.i(TAG, "Not installing, new version is <= current version");
93 } else if (!verifyPreviousHash(currentHash, altRequiredHash)) {
94 EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED,
95 "Current hash did not match required value");
96 } else if (!verifySignature(altContent, altVersion, altRequiredHash, altSig,
98 EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED,
99 "Signature did not verify");
101 // install the new content
102 Slog.i(TAG, "Found new update, installing...");
103 install(altContent, altVersion);
104 Slog.i(TAG, "Installation successful");
106 } catch (Exception e) {
107 Slog.e(TAG, "Could not update content!", e);
108 // keep the error message <= 100 chars
109 String errMsg = e.toString();
110 if (errMsg.length() > 100) {
111 errMsg = errMsg.substring(0, 99);
113 EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED, errMsg);
119 private X509Certificate getCert(ContentResolver cr) {
120 // get the cert from settings
121 String cert = Settings.Secure.getString(cr, UPDATE_CERTIFICATE_KEY);
122 // convert it into a real certificate
124 byte[] derCert = Base64.decode(cert.getBytes(), Base64.DEFAULT);
125 InputStream istream = new ByteArrayInputStream(derCert);
126 CertificateFactory cf = CertificateFactory.getInstance("X.509");
127 return (X509Certificate) cf.generateCertificate(istream);
128 } catch (CertificateException e) {
129 throw new IllegalStateException("Got malformed certificate from settings, ignoring");
133 private String getContentFromIntent(Intent i) {
134 String extraValue = i.getStringExtra(EXTRA_CONTENT_PATH);
135 if (extraValue == null) {
136 throw new IllegalStateException("Missing required content path, ignoring.");
141 private int getVersionFromIntent(Intent i) throws NumberFormatException {
142 String extraValue = i.getStringExtra(EXTRA_VERSION_NUMBER);
143 if (extraValue == null) {
144 throw new IllegalStateException("Missing required version number, ignoring.");
146 return Integer.parseInt(extraValue.trim());
149 private String getRequiredHashFromIntent(Intent i) {
150 String extraValue = i.getStringExtra(EXTRA_REQUIRED_HASH);
151 if (extraValue == null) {
152 throw new IllegalStateException("Missing required previous hash, ignoring.");
154 return extraValue.trim();
157 private String getSignatureFromIntent(Intent i) {
158 String extraValue = i.getStringExtra(EXTRA_SIGNATURE);
159 if (extraValue == null) {
160 throw new IllegalStateException("Missing required signature, ignoring.");
162 return extraValue.trim();
165 private int getCurrentVersion() throws NumberFormatException {
167 String strVersion = IoUtils.readFileAsString(updateVersion.getCanonicalPath()).trim();
168 return Integer.parseInt(strVersion);
169 } catch (IOException e) {
170 Slog.i(TAG, "Couldn't find current metadata, assuming first update");
175 private String getAltContent(Intent i) throws IOException {
176 String contents = IoUtils.readFileAsString(getContentFromIntent(i));
177 return contents.trim();
180 private String getCurrentContent() {
182 return IoUtils.readFileAsString(updateContent.getCanonicalPath()).trim();
183 } catch (IOException e) {
184 Slog.i(TAG, "Failed to read current content, assuming first update!");
189 private static String getCurrentHash(String content) {
190 if (content == null) {
194 MessageDigest dgst = MessageDigest.getInstance("SHA512");
195 byte[] encoded = content.getBytes();
196 byte[] fingerprint = dgst.digest(encoded);
197 return IntegralToString.bytesToHexString(fingerprint, false);
198 } catch (NoSuchAlgorithmException e) {
199 throw new AssertionError(e);
203 private boolean verifyVersion(int current, int alternative) {
204 return (current < alternative);
207 private boolean verifyPreviousHash(String current, String required) {
208 // this is an optional value- if the required field is NONE then we ignore it
209 if (required.equals("NONE")) {
212 // otherwise, verify that we match correctly
213 return current.equals(required);
216 private boolean verifySignature(String content, int version, String requiredPrevious,
217 String signature, X509Certificate cert) throws Exception {
218 Signature signer = Signature.getInstance("SHA512withRSA");
219 signer.initVerify(cert);
220 signer.update(content.getBytes());
221 signer.update(Long.toString(version).getBytes());
222 signer.update(requiredPrevious.getBytes());
223 return signer.verify(Base64.decode(signature.getBytes(), Base64.DEFAULT));
226 private void writeUpdate(File dir, File file, String content) throws IOException {
227 FileOutputStream out = null;
230 // create the temporary file
231 tmp = File.createTempFile("journal", "", dir);
232 // create the parents for the destination file
233 File parent = file.getParentFile();
235 // check that they were created correctly
236 if (!parent.exists()) {
237 throw new IOException("Failed to create directory " + parent.getCanonicalPath());
239 // mark tmp -rw-r--r--
240 tmp.setReadable(true, false);
242 out = new FileOutputStream(tmp);
243 out.write(content.getBytes());
247 if (!tmp.renameTo(file)) {
248 throw new IOException("Failed to atomically rename " + file.getCanonicalPath());
254 IoUtils.closeQuietly(out);
258 private void install(String content, int version) throws IOException {
259 writeUpdate(updateDir, updateContent, content);
260 writeUpdate(updateDir, updateVersion, Long.toString(version));