FileDocCategorySizeDatePackage
ConfigUpdateInstallReceiver.javaAPI DocAndroid 5.1 API10883Thu Mar 12 22:22:42 GMT 2015com.android.server.updates

ConfigUpdateInstallReceiver

public class ConfigUpdateInstallReceiver extends android.content.BroadcastReceiver

Fields Summary
private static final String
TAG
private static final String
EXTRA_CONTENT_PATH
private static final String
EXTRA_REQUIRED_HASH
private static final String
EXTRA_SIGNATURE
private static final String
EXTRA_VERSION_NUMBER
private static final String
UPDATE_CERTIFICATE_KEY
protected final File
updateDir
protected final File
updateContent
protected final File
updateVersion
Constructors Summary
public ConfigUpdateInstallReceiver(String updateDir, String updateContentPath, String updateMetadataPath, String updateVersionPath)


        
                                           
        this.updateDir = new File(updateDir);
        this.updateContent = new File(updateDir, updateContentPath);
        File updateMetadataDir = new File(updateDir, updateMetadataPath);
        this.updateVersion = new File(updateMetadataDir, updateVersionPath);
    
Methods Summary
private byte[]getAltContent(android.content.Context c, android.content.Intent i)

        Uri content = getContentFromIntent(i);
        InputStream is = c.getContentResolver().openInputStream(content);
        try {
            return Streams.readFullyNoClose(is);
        } finally {
            is.close();
        }
    
private java.security.cert.X509CertificategetCert(android.content.ContentResolver cr)

        // get the cert from settings
        String cert = Settings.Secure.getString(cr, UPDATE_CERTIFICATE_KEY);
        // convert it into a real certificate
        try {
            byte[] derCert = Base64.decode(cert.getBytes(), Base64.DEFAULT);
            InputStream istream = new ByteArrayInputStream(derCert);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            return (X509Certificate) cf.generateCertificate(istream);
        } catch (CertificateException e) {
            throw new IllegalStateException("Got malformed certificate from settings, ignoring");
        }
    
private android.net.UrigetContentFromIntent(android.content.Intent i)

        Uri data = i.getData();
        if (data == null) {
            throw new IllegalStateException("Missing required content path, ignoring.");
        }
        return data;
    
private byte[]getCurrentContent()

        try {
            return IoUtils.readFileAsByteArray(updateContent.getCanonicalPath());
        } catch (IOException e) {
            Slog.i(TAG, "Failed to read current content, assuming first update!");
            return null;
        }
    
private static java.lang.StringgetCurrentHash(byte[] content)

        if (content == null) {
            return "0";
        }
        try {
            MessageDigest dgst = MessageDigest.getInstance("SHA512");
            byte[] fingerprint = dgst.digest(content);
            return IntegralToString.bytesToHexString(fingerprint, false);
        } catch (NoSuchAlgorithmException e) {
            throw new AssertionError(e);
        }
    
private intgetCurrentVersion()

        try {
            String strVersion = IoUtils.readFileAsString(updateVersion.getCanonicalPath()).trim();
            return Integer.parseInt(strVersion);
        } catch (IOException e) {
            Slog.i(TAG, "Couldn't find current metadata, assuming first update");
            return 0;
        }
    
private java.lang.StringgetRequiredHashFromIntent(android.content.Intent i)

        String extraValue = i.getStringExtra(EXTRA_REQUIRED_HASH);
        if (extraValue == null) {
            throw new IllegalStateException("Missing required previous hash, ignoring.");
        }
        return extraValue.trim();
    
private java.lang.StringgetSignatureFromIntent(android.content.Intent i)

        String extraValue = i.getStringExtra(EXTRA_SIGNATURE);
        if (extraValue == null) {
            throw new IllegalStateException("Missing required signature, ignoring.");
        }
        return extraValue.trim();
    
private intgetVersionFromIntent(android.content.Intent i)

        String extraValue = i.getStringExtra(EXTRA_VERSION_NUMBER);
        if (extraValue == null) {
            throw new IllegalStateException("Missing required version number, ignoring.");
        }
        return Integer.parseInt(extraValue.trim());
    
protected voidinstall(byte[] content, int version)

        writeUpdate(updateDir, updateContent, content);
        writeUpdate(updateDir, updateVersion, Long.toString(version).getBytes());
    
public voidonReceive(android.content.Context context, android.content.Intent intent)

        new Thread() {
            @Override
            public void run() {
                try {
                    // get the certificate from Settings.Secure
                    X509Certificate cert = getCert(context.getContentResolver());
                    // get the content path from the extras
                    byte[] altContent = getAltContent(context, intent);
                    // get the version from the extras
                    int altVersion = getVersionFromIntent(intent);
                    // get the previous value from the extras
                    String altRequiredHash = getRequiredHashFromIntent(intent);
                    // get the signature from the extras
                    String altSig = getSignatureFromIntent(intent);
                    // get the version currently being used
                    int currentVersion = getCurrentVersion();
                    // get the hash of the currently used value
                    String currentHash = getCurrentHash(getCurrentContent());
                    if (!verifyVersion(currentVersion, altVersion)) {
                        Slog.i(TAG, "Not installing, new version is <= current version");
                    } else if (!verifyPreviousHash(currentHash, altRequiredHash)) {
                        EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED,
                                            "Current hash did not match required value");
                    } else if (!verifySignature(altContent, altVersion, altRequiredHash, altSig,
                               cert)) {
                        EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED,
                                            "Signature did not verify");
                    } else {
                        // install the new content
                        Slog.i(TAG, "Found new update, installing...");
                        install(altContent, altVersion);
                        Slog.i(TAG, "Installation successful");
                        postInstall(context, intent);
                    }
                } catch (Exception e) {
                    Slog.e(TAG, "Could not update content!", e);
                    // keep the error message <= 100 chars
                    String errMsg = e.toString();
                    if (errMsg.length() > 100) {
                        errMsg = errMsg.substring(0, 99);
                    }
                    EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED, errMsg);
                }
            }
        }.start();
    
protected voidpostInstall(android.content.Context context, android.content.Intent intent)

    
private booleanverifyPreviousHash(java.lang.String current, java.lang.String required)

        // this is an optional value- if the required field is NONE then we ignore it
        if (required.equals("NONE")) {
            return true;
        }
        // otherwise, verify that we match correctly
        return current.equals(required);
    
private booleanverifySignature(byte[] content, int version, java.lang.String requiredPrevious, java.lang.String signature, java.security.cert.X509Certificate cert)

        Signature signer = Signature.getInstance("SHA512withRSA");
        signer.initVerify(cert);
        signer.update(content);
        signer.update(Long.toString(version).getBytes());
        signer.update(requiredPrevious.getBytes());
        return signer.verify(Base64.decode(signature.getBytes(), Base64.DEFAULT));
    
private booleanverifyVersion(int current, int alternative)

        return (current < alternative);
    
protected voidwriteUpdate(java.io.File dir, java.io.File file, byte[] content)

        FileOutputStream out = null;
        File tmp = null;
        try {
            // create the parents for the destination file
            File parent = file.getParentFile();
            parent.mkdirs();
            // check that they were created correctly
            if (!parent.exists()) {
                throw new IOException("Failed to create directory " + parent.getCanonicalPath());
            }
            // create the temporary file
            tmp = File.createTempFile("journal", "", dir);
            // mark tmp -rw-r--r--
            tmp.setReadable(true, false);
            // write to it
            out = new FileOutputStream(tmp);
            out.write(content);
            // sync to disk
            out.getFD().sync();
            // atomic rename
            if (!tmp.renameTo(file)) {
                throw new IOException("Failed to atomically rename " + file.getCanonicalPath());
            }
        } finally {
            if (tmp != null) {
                tmp.delete();
            }
            IoUtils.closeQuietly(out);
        }