ConfigUpdateInstallReceiver.java revision 103173e16da609bcf57a88961ca57a8de17e0ee7
1/*
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.net.Uri;
24import android.provider.Settings;
25import android.util.Base64;
26import android.util.EventLog;
27import android.util.Slog;
28
29import com.android.server.EventLogTags;
30
31import java.io.ByteArrayInputStream;
32import java.io.File;
33import java.io.FileOutputStream;
34import java.io.InputStream;
35import java.io.IOException;
36import java.security.cert.CertificateException;
37import java.security.cert.CertificateFactory;
38import java.security.cert.X509Certificate;
39import java.security.MessageDigest;
40import java.security.NoSuchAlgorithmException;
41import java.security.Signature;
42
43import libcore.io.IoUtils;
44import libcore.io.Streams;
45
46public class ConfigUpdateInstallReceiver extends BroadcastReceiver {
47
48    private static final String TAG = "ConfigUpdateInstallReceiver";
49
50    private static final String EXTRA_CONTENT_PATH = "CONTENT_PATH";
51    private static final String EXTRA_REQUIRED_HASH = "REQUIRED_HASH";
52    private static final String EXTRA_SIGNATURE = "SIGNATURE";
53    private static final String EXTRA_VERSION_NUMBER = "VERSION";
54
55    private static final String UPDATE_CERTIFICATE_KEY = "config_update_certificate";
56
57    protected final File updateDir;
58    protected final File updateContent;
59    protected final File updateVersion;
60
61    public ConfigUpdateInstallReceiver(String updateDir, String updateContentPath,
62                                       String updateMetadataPath, String updateVersionPath) {
63        this.updateDir = new File(updateDir);
64        this.updateContent = new File(updateDir, updateContentPath);
65        File updateMetadataDir = new File(updateDir, updateMetadataPath);
66        this.updateVersion = new File(updateMetadataDir, updateVersionPath);
67    }
68
69    @Override
70    public void onReceive(final Context context, final Intent intent) {
71        new Thread() {
72            @Override
73            public void run() {
74                try {
75                    // get the certificate from Settings.Secure
76                    X509Certificate cert = getCert(context.getContentResolver());
77                    // get the content path from the extras
78                    byte[] altContent = getAltContent(context, intent);
79                    // get the version from the extras
80                    int altVersion = getVersionFromIntent(intent);
81                    // get the previous value from the extras
82                    String altRequiredHash = getRequiredHashFromIntent(intent);
83                    // get the signature from the extras
84                    String altSig = getSignatureFromIntent(intent);
85                    // get the version currently being used
86                    int currentVersion = getCurrentVersion();
87                    // get the hash of the currently used value
88                    String currentHash = getCurrentHash(getCurrentContent());
89                    if (!verifyVersion(currentVersion, altVersion)) {
90                        Slog.i(TAG, "Not installing, new version is <= current version");
91                    } else if (!verifyPreviousHash(currentHash, altRequiredHash)) {
92                        EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED,
93                                            "Current hash did not match required value");
94                    } else if (!verifySignature(altContent, altVersion, altRequiredHash, altSig,
95                               cert)) {
96                        EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED,
97                                            "Signature did not verify");
98                    } else {
99                        // install the new content
100                        Slog.i(TAG, "Found new update, installing...");
101                        install(altContent, altVersion);
102                        Slog.i(TAG, "Installation successful");
103                        postInstall(context, intent);
104                    }
105                } catch (Exception e) {
106                    Slog.e(TAG, "Could not update content!", e);
107                    // keep the error message <= 100 chars
108                    String errMsg = e.toString();
109                    if (errMsg.length() > 100) {
110                        errMsg = errMsg.substring(0, 99);
111                    }
112                    EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED, errMsg);
113                }
114            }
115        }.start();
116    }
117
118    private X509Certificate getCert(ContentResolver cr) {
119        // get the cert from settings
120        String cert = Settings.Secure.getString(cr, UPDATE_CERTIFICATE_KEY);
121        // convert it into a real certificate
122        try {
123            byte[] derCert = Base64.decode(cert.getBytes(), Base64.DEFAULT);
124            InputStream istream = new ByteArrayInputStream(derCert);
125            CertificateFactory cf = CertificateFactory.getInstance("X.509");
126            return (X509Certificate) cf.generateCertificate(istream);
127        } catch (CertificateException e) {
128            throw new IllegalStateException("Got malformed certificate from settings, ignoring");
129        }
130    }
131
132    private Uri getContentFromIntent(Intent i) {
133        Uri data = i.getData();
134        if (data == null) {
135            throw new IllegalStateException("Missing required content path, ignoring.");
136        }
137        return data;
138    }
139
140    private int getVersionFromIntent(Intent i) throws NumberFormatException {
141        String extraValue = i.getStringExtra(EXTRA_VERSION_NUMBER);
142        if (extraValue == null) {
143            throw new IllegalStateException("Missing required version number, ignoring.");
144        }
145        return Integer.parseInt(extraValue.trim());
146    }
147
148    private String getRequiredHashFromIntent(Intent i) {
149        String extraValue = i.getStringExtra(EXTRA_REQUIRED_HASH);
150        if (extraValue == null) {
151            throw new IllegalStateException("Missing required previous hash, ignoring.");
152        }
153        return extraValue.trim();
154    }
155
156    private String getSignatureFromIntent(Intent i) {
157        String extraValue = i.getStringExtra(EXTRA_SIGNATURE);
158        if (extraValue == null) {
159            throw new IllegalStateException("Missing required signature, ignoring.");
160        }
161        return extraValue.trim();
162    }
163
164    private int getCurrentVersion() throws NumberFormatException {
165        try {
166            String strVersion = IoUtils.readFileAsString(updateVersion.getCanonicalPath()).trim();
167            return Integer.parseInt(strVersion);
168        } catch (IOException e) {
169            Slog.i(TAG, "Couldn't find current metadata, assuming first update");
170            return 0;
171        }
172    }
173
174    private byte[] getAltContent(Context c, Intent i) throws IOException {
175        Uri content = getContentFromIntent(i);
176        InputStream is = c.getContentResolver().openInputStream(content);
177        try {
178            return Streams.readFullyNoClose(is);
179        } finally {
180            is.close();
181        }
182    }
183
184    private byte[] getCurrentContent() {
185        try {
186            return IoUtils.readFileAsByteArray(updateContent.getCanonicalPath());
187        } catch (IOException e) {
188            Slog.i(TAG, "Failed to read current content, assuming first update!");
189            return null;
190        }
191    }
192
193    private static String getCurrentHash(byte[] content) {
194        if (content == null) {
195            return "0";
196        }
197        try {
198            MessageDigest dgst = MessageDigest.getInstance("SHA512");
199            byte[] fingerprint = dgst.digest(content);
200            return IntegralToString.bytesToHexString(fingerprint, false);
201        } catch (NoSuchAlgorithmException e) {
202            throw new AssertionError(e);
203        }
204    }
205
206    private boolean verifyVersion(int current, int alternative) {
207        return (current < alternative);
208    }
209
210    private boolean verifyPreviousHash(String current, String required) {
211        // this is an optional value- if the required field is NONE then we ignore it
212        if (required.equals("NONE")) {
213            return true;
214        }
215        // otherwise, verify that we match correctly
216        return current.equals(required);
217    }
218
219    private boolean verifySignature(byte[] content, int version, String requiredPrevious,
220                                   String signature, X509Certificate cert) throws Exception {
221        Signature signer = Signature.getInstance("SHA512withRSA");
222        signer.initVerify(cert);
223        signer.update(content);
224        signer.update(Long.toString(version).getBytes());
225        signer.update(requiredPrevious.getBytes());
226        return signer.verify(Base64.decode(signature.getBytes(), Base64.DEFAULT));
227    }
228
229    protected void writeUpdate(File dir, File file, byte[] content) throws IOException {
230        FileOutputStream out = null;
231        File tmp = null;
232        try {
233            // create the parents for the destination file
234            File parent = file.getParentFile();
235            parent.mkdirs();
236            // check that they were created correctly
237            if (!parent.exists()) {
238                throw new IOException("Failed to create directory " + parent.getCanonicalPath());
239            }
240            // create the temporary file
241            tmp = File.createTempFile("journal", "", dir);
242            // mark tmp -rw-r--r--
243            tmp.setReadable(true, false);
244            // write to it
245            out = new FileOutputStream(tmp);
246            out.write(content);
247            // sync to disk
248            out.getFD().sync();
249            // atomic rename
250            if (!tmp.renameTo(file)) {
251                throw new IOException("Failed to atomically rename " + file.getCanonicalPath());
252            }
253        } finally {
254            if (tmp != null) {
255                tmp.delete();
256            }
257            IoUtils.closeQuietly(out);
258        }
259    }
260
261    protected void install(byte[] content, int version) throws IOException {
262        writeUpdate(updateDir, updateContent, content);
263        writeUpdate(updateDir, updateVersion, Long.toString(version).getBytes());
264    }
265
266    protected void postInstall(Context context, Intent intent) {
267    }
268}
269