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.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,
97                               cert)) {
98                        EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED,
99                                            "Signature did not verify");
100                    } else {
101                        // install the new content
102                        Slog.i(TAG, "Found new update, installing...");
103                        install(altContent, altVersion);
104                        Slog.i(TAG, "Installation successful");
105                    }
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);
112                    }
113                    EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED, errMsg);
114                }
115            }
116        }.start();
117    }
118
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
123        try {
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");
130        }
131    }
132
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.");
137        }
138        return extraValue;
139    }
140
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.");
145        }
146        return Integer.parseInt(extraValue.trim());
147    }
148
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.");
153        }
154        return extraValue.trim();
155    }
156
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.");
161        }
162        return extraValue.trim();
163    }
164
165    private int getCurrentVersion() throws NumberFormatException {
166        try {
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");
171            return 0;
172        }
173    }
174
175    private String getAltContent(Intent i) throws IOException {
176        String contents = IoUtils.readFileAsString(getContentFromIntent(i));
177        return contents.trim();
178    }
179
180    private String getCurrentContent() {
181        try {
182            return IoUtils.readFileAsString(updateContent.getCanonicalPath()).trim();
183        } catch (IOException e) {
184            Slog.i(TAG, "Failed to read current content, assuming first update!");
185            return null;
186        }
187    }
188
189    private static String getCurrentHash(String content) {
190        if (content == null) {
191            return "0";
192        }
193        try {
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);
200        }
201    }
202
203    private boolean verifyVersion(int current, int alternative) {
204        return (current < alternative);
205    }
206
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")) {
210            return true;
211        }
212        // otherwise, verify that we match correctly
213        return current.equals(required);
214    }
215
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));
224    }
225
226    private void writeUpdate(File dir, File file, String content) throws IOException {
227        FileOutputStream out = null;
228        File tmp = null;
229        try {
230            // create the temporary file
231            tmp = File.createTempFile("journal", "", dir);
232            // create the parents for the destination file
233            File parent = file.getParentFile();
234            parent.mkdirs();
235            // check that they were created correctly
236            if (!parent.exists()) {
237                throw new IOException("Failed to create directory " + parent.getCanonicalPath());
238            }
239            // mark tmp -rw-r--r--
240            tmp.setReadable(true, false);
241            // write to it
242            out = new FileOutputStream(tmp);
243            out.write(content.getBytes());
244            // sync to disk
245            out.getFD().sync();
246            // atomic rename
247            if (!tmp.renameTo(file)) {
248                throw new IOException("Failed to atomically rename " + file.getCanonicalPath());
249            }
250        } finally {
251            if (tmp != null) {
252                tmp.delete();
253            }
254            IoUtils.closeQuietly(out);
255        }
256    }
257
258    private void install(String content, int version) throws IOException {
259        writeUpdate(updateDir, updateContent, content);
260        writeUpdate(updateDir, updateVersion, Long.toString(version));
261    }
262}
263