ConfigUpdateInstallReceiver.java revision 7c65e39964a1aa8fffbd940c5ee9e77691aa9656
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.provider.Settings;
24import android.os.FileUtils;
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.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
59    private final File updateDir;
60    private final File updateContent;
61    private final File updateVersion;
62
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
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.e(TAG, "New version is not greater than current version, aborting!");
93                    } else if (!verifyPreviousHash(currentHash, altRequiredHash)) {
94                        Slog.e(TAG, "Current hash did not match required value, aborting!");
95                    } else if (!verifySignature(altContent, altVersion, altRequiredHash, altSig,
96                               cert)) {
97                        Slog.e(TAG, "Signature did not verify, aborting!");
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                    }
104                } catch (Exception e) {
105                    Slog.e(TAG, "Could not update content!", e);
106                    EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED,
107                                        updateDir.toString());
108                }
109            }
110        }.start();
111    }
112
113    private X509Certificate getCert(ContentResolver cr) {
114        // get the cert from settings
115        String cert = Settings.Secure.getString(cr, UPDATE_CERTIFICATE_KEY);
116        // convert it into a real certificate
117        try {
118            byte[] derCert = Base64.decode(cert.getBytes(), Base64.DEFAULT);
119            InputStream istream = new ByteArrayInputStream(derCert);
120            CertificateFactory cf = CertificateFactory.getInstance("X.509");
121            return (X509Certificate) cf.generateCertificate(istream);
122        } catch (CertificateException e) {
123            throw new IllegalStateException("Got malformed certificate from settings, ignoring", e);
124        }
125    }
126
127    private String getContentFromIntent(Intent i) {
128        String extraValue = i.getStringExtra(EXTRA_CONTENT_PATH);
129        if (extraValue == null) {
130            throw new IllegalStateException("Missing required content path, ignoring.");
131        }
132        return extraValue;
133    }
134
135    private int getVersionFromIntent(Intent i) throws NumberFormatException {
136        String extraValue = i.getStringExtra(EXTRA_VERSION_NUMBER);
137        if (extraValue == null) {
138            throw new IllegalStateException("Missing required version number, ignoring.");
139        }
140        return Integer.parseInt(extraValue.trim());
141    }
142
143    private String getRequiredHashFromIntent(Intent i) {
144        String extraValue = i.getStringExtra(EXTRA_REQUIRED_HASH);
145        if (extraValue == null) {
146            throw new IllegalStateException("Missing required previous hash, ignoring.");
147        }
148        return extraValue.trim();
149    }
150
151    private String getSignatureFromIntent(Intent i) {
152        String extraValue = i.getStringExtra(EXTRA_SIGNATURE);
153        if (extraValue == null) {
154            throw new IllegalStateException("Missing required signature, ignoring.");
155        }
156        return extraValue.trim();
157    }
158
159    private int getCurrentVersion() throws NumberFormatException {
160        try {
161            String strVersion = IoUtils.readFileAsString(updateVersion.getCanonicalPath()).trim();
162            return Integer.parseInt(strVersion);
163        } catch (IOException e) {
164            Slog.i(TAG, "Couldn't find current metadata, assuming first update", e);
165            return 0;
166        }
167    }
168
169    private String getAltContent(Intent i) throws IOException {
170        String contents = IoUtils.readFileAsString(getContentFromIntent(i));
171        return contents.trim();
172    }
173
174    private String getCurrentContent() {
175        try {
176            return IoUtils.readFileAsString(updateContent.getCanonicalPath()).trim();
177        } catch (IOException e) {
178            Slog.i(TAG, "Failed to read current content, assuming first update!", e);
179            return null;
180        }
181    }
182
183    private static String getCurrentHash(String content) {
184        if (content == null) {
185            return "0";
186        }
187        try {
188            MessageDigest dgst = MessageDigest.getInstance("SHA512");
189            byte[] encoded = content.getBytes();
190            byte[] fingerprint = dgst.digest(encoded);
191            return IntegralToString.bytesToHexString(fingerprint, false);
192        } catch (NoSuchAlgorithmException e) {
193            throw new AssertionError(e);
194        }
195    }
196
197    private boolean verifyVersion(int current, int alternative) {
198        return (current < alternative);
199    }
200
201    private boolean verifyPreviousHash(String current, String required) {
202        // this is an optional value- if the required field is NONE then we ignore it
203        if (required.equals("NONE")) {
204            return true;
205        }
206        // otherwise, verify that we match correctly
207        return current.equals(required);
208    }
209
210    private boolean verifySignature(String content, int version, String requiredPrevious,
211                                   String signature, X509Certificate cert) throws Exception {
212        Signature signer = Signature.getInstance("SHA512withRSA");
213        signer.initVerify(cert);
214        signer.update(content.getBytes());
215        signer.update(Long.toString(version).getBytes());
216        signer.update(requiredPrevious.getBytes());
217        return signer.verify(Base64.decode(signature.getBytes(), Base64.DEFAULT));
218    }
219
220    private void writeUpdate(File dir, File file, String content) {
221        FileOutputStream out = null;
222        File tmp = null;
223        try {
224            // create the temporary file
225            tmp = File.createTempFile("journal", "", dir);
226            // create the parents for the destination file
227            File parent = file.getParentFile();
228            parent.mkdirs();
229            // check that they were created correctly
230            if (!parent.exists()) {
231                throw new IOException("Failed to create directory " + parent.getCanonicalPath());
232            }
233            // mark tmp -rw-r--r--
234            tmp.setReadable(true, false);
235            // write to it
236            out = new FileOutputStream(tmp);
237            out.write(content.getBytes());
238            // sync to disk
239            out.getFD().sync();
240            // atomic rename
241            if (!tmp.renameTo(file)) {
242                throw new IOException("Failed to atomically rename " + file.getCanonicalPath());
243            }
244        } catch (IOException e) {
245            Slog.e(TAG, "Failed to write update", e);
246        } finally {
247            if (tmp != null) {
248                tmp.delete();
249            }
250            IoUtils.closeQuietly(out);
251        }
252    }
253
254    private void install(String content, int version) {
255        writeUpdate(updateDir, updateContent, content);
256        writeUpdate(updateDir, updateVersion, Long.toString(version));
257    }
258}
259