Search in sources :

Example 46 with RandomAccessFile

use of java.io.RandomAccessFile in project android_frameworks_base by ParanoidAndroid.

the class LockSettingsService method checkPassword.

@Override
public boolean checkPassword(byte[] hash, int userId) throws RemoteException {
    checkPasswordReadPermission(userId);
    try {
        // Read all the bytes from the file
        RandomAccessFile raf = new RandomAccessFile(getLockPasswordFilename(userId), "r");
        final byte[] stored = new byte[(int) raf.length()];
        int got = raf.read(stored, 0, stored.length);
        raf.close();
        if (got <= 0) {
            return true;
        }
        // Compare the hash from the file with the entered password's hash
        return Arrays.equals(stored, hash);
    } catch (FileNotFoundException fnfe) {
        Slog.e(TAG, "Cannot read file " + fnfe);
        return true;
    } catch (IOException ioe) {
        Slog.e(TAG, "Cannot read file " + ioe);
        return true;
    }
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException)

Example 47 with RandomAccessFile

use of java.io.RandomAccessFile in project android_frameworks_base by ParanoidAndroid.

the class LockSettingsService method writeFile.

private void writeFile(String name, byte[] hash) {
    try {
        // Write the hash to file
        RandomAccessFile raf = new RandomAccessFile(name, "rw");
        // Truncate the file if pattern is null, to clear the lock
        if (hash == null || hash.length == 0) {
            raf.setLength(0);
        } else {
            raf.write(hash, 0, hash.length);
        }
        raf.close();
    } catch (IOException ioe) {
        Slog.e(TAG, "Error writing to file " + ioe);
    }
}
Also used : RandomAccessFile(java.io.RandomAccessFile) IOException(java.io.IOException)

Example 48 with RandomAccessFile

use of java.io.RandomAccessFile in project android_frameworks_base by ParanoidAndroid.

the class HugeAgent method onBackup.

/**
     * The set of data backed up by this application is very small: just
     * two booleans and an integer.  With such a simple dataset, it's
     * easiest to simply store a copy of the backed-up data as the state
     * blob describing the last dataset backed up.  The state file
     * contents can be anything; it is private to the agent class, and
     * is never stored off-device.
     *
     * <p>One thing that an application may wish to do is tag the state
     * blob contents with a version number.  This is so that if the
     * application is upgraded, the next time it attempts to do a backup,
     * it can detect that the last backup operation was performed by an
     * older version of the agent, and might therefore require different
     * handling.
     */
@Override
public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) throws IOException {
    // backup operation.
    synchronized (HugeBackupActivity.sDataLock) {
        RandomAccessFile file = new RandomAccessFile(mDataFile, "r");
        mFilling = file.readInt();
        mAddMayo = file.readBoolean();
        mAddTomato = file.readBoolean();
    }
    // If the new state file descriptor is null, this is the first time
    // a backup is being performed, so we know we have to write the
    // data.  If there <em>is</em> a previous state blob, we want to
    // double check whether the current data is actually different from
    // our last backup, so that we can avoid transmitting redundant
    // data to the storage backend.
    boolean doBackup = (oldState == null);
    if (!doBackup) {
        doBackup = compareStateFile(oldState);
    }
    // transport under the single key string.
    if (doBackup) {
        ByteArrayOutputStream bufStream = new ByteArrayOutputStream();
        // We use a DataOutputStream to write structured data into
        // the buffering stream
        DataOutputStream outWriter = new DataOutputStream(bufStream);
        outWriter.writeInt(mFilling);
        outWriter.writeBoolean(mAddMayo);
        outWriter.writeBoolean(mAddTomato);
        // Okay, we've flattened the data for transmission.  Pull it
        // out of the buffering stream object and send it off.
        byte[] buffer = bufStream.toByteArray();
        int len = buffer.length;
        data.writeEntityHeader(APP_DATA_KEY, len);
        data.writeEntityData(buffer, len);
        // ***** pathological behavior *****
        // Now, in order to incur deliberate too-much-data failures,
        // try to back up 20 MB of data besides what we already pushed.
        final int MEGABYTE = 1024 * 1024;
        final int NUM_MEGS = 20;
        buffer = new byte[MEGABYTE];
        data.writeEntityHeader(HUGE_DATA_KEY, NUM_MEGS * MEGABYTE);
        for (int i = 0; i < NUM_MEGS; i++) {
            data.writeEntityData(buffer, MEGABYTE);
        }
    }
    // Finally, in all cases, we need to write the new state blob
    writeStateFile(newState);
}
Also used : RandomAccessFile(java.io.RandomAccessFile) DataOutputStream(java.io.DataOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 49 with RandomAccessFile

use of java.io.RandomAccessFile in project android_frameworks_base by ParanoidAndroid.

the class HugeBackupActivity method recordNewUIState.

/**
     * Another helper; this one reads the current UI state and writes that
     * to the persistent store, then tells the backup manager that we need
     * a backup.
     */
void recordNewUIState() {
    boolean addMayo = mAddMayoCheckbox.isChecked();
    boolean addTomato = mAddTomatoCheckbox.isChecked();
    int whichFilling = mFillingGroup.getCheckedRadioButtonId();
    try {
        synchronized (HugeBackupActivity.sDataLock) {
            RandomAccessFile file = new RandomAccessFile(mDataFile, "rw");
            writeDataToFileLocked(file, addMayo, addTomato, whichFilling);
        }
    } catch (IOException e) {
        Log.e(TAG, "Unable to record new UI state");
    }
    mBackupManager.dataChanged();
}
Also used : RandomAccessFile(java.io.RandomAccessFile) IOException(java.io.IOException)

Example 50 with RandomAccessFile

use of java.io.RandomAccessFile in project android_frameworks_base by ParanoidAndroid.

the class RecoverySystem method verifyPackage.

/**
     * Verify the cryptographic signature of a system update package
     * before installing it.  Note that the package is also verified
     * separately by the installer once the device is rebooted into
     * the recovery system.  This function will return only if the
     * package was successfully verified; otherwise it will throw an
     * exception.
     *
     * Verification of a package can take significant time, so this
     * function should not be called from a UI thread.  Interrupting
     * the thread while this function is in progress will result in a
     * SecurityException being thrown (and the thread's interrupt flag
     * will be cleared).
     *
     * @param packageFile  the package to be verified
     * @param listener     an object to receive periodic progress
     * updates as verification proceeds.  May be null.
     * @param deviceCertsZipFile  the zip file of certificates whose
     * public keys we will accept.  Verification succeeds if the
     * package is signed by the private key corresponding to any
     * public key in this file.  May be null to use the system default
     * file (currently "/system/etc/security/otacerts.zip").
     *
     * @throws IOException if there were any errors reading the
     * package or certs files.
     * @throws GeneralSecurityException if verification failed
     */
public static void verifyPackage(File packageFile, ProgressListener listener, File deviceCertsZipFile) throws IOException, GeneralSecurityException {
    long fileLen = packageFile.length();
    RandomAccessFile raf = new RandomAccessFile(packageFile, "r");
    try {
        int lastPercent = 0;
        long lastPublishTime = System.currentTimeMillis();
        if (listener != null) {
            listener.onProgress(lastPercent);
        }
        raf.seek(fileLen - 6);
        byte[] footer = new byte[6];
        raf.readFully(footer);
        if (footer[2] != (byte) 0xff || footer[3] != (byte) 0xff) {
            throw new SignatureException("no signature in file (no footer)");
        }
        int commentSize = (footer[4] & 0xff) | ((footer[5] & 0xff) << 8);
        int signatureStart = (footer[0] & 0xff) | ((footer[1] & 0xff) << 8);
        byte[] eocd = new byte[commentSize + 22];
        raf.seek(fileLen - (commentSize + 22));
        raf.readFully(eocd);
        // end-of-central-directory record.
        if (eocd[0] != (byte) 0x50 || eocd[1] != (byte) 0x4b || eocd[2] != (byte) 0x05 || eocd[3] != (byte) 0x06) {
            throw new SignatureException("no signature in file (bad footer)");
        }
        for (int i = 4; i < eocd.length - 3; ++i) {
            if (eocd[i] == (byte) 0x50 && eocd[i + 1] == (byte) 0x4b && eocd[i + 2] == (byte) 0x05 && eocd[i + 3] == (byte) 0x06) {
                throw new SignatureException("EOCD marker found after start of EOCD");
            }
        }
        // The following code is largely copied from
        // JarUtils.verifySignature().  We could just *call* that
        // method here if that function didn't read the entire
        // input (ie, the whole OTA package) into memory just to
        // compute its message digest.
        BerInputStream bis = new BerInputStream(new ByteArrayInputStream(eocd, commentSize + 22 - signatureStart, signatureStart));
        ContentInfo info = (ContentInfo) ContentInfo.ASN1.decode(bis);
        SignedData signedData = info.getSignedData();
        if (signedData == null) {
            throw new IOException("signedData is null");
        }
        Collection encCerts = signedData.getCertificates();
        if (encCerts.isEmpty()) {
            throw new IOException("encCerts is empty");
        }
        // Take the first certificate from the signature (packages
        // should contain only one).
        Iterator it = encCerts.iterator();
        X509Certificate cert = null;
        if (it.hasNext()) {
            cert = new X509CertImpl((org.apache.harmony.security.x509.Certificate) it.next());
        } else {
            throw new SignatureException("signature contains no certificates");
        }
        List sigInfos = signedData.getSignerInfos();
        SignerInfo sigInfo;
        if (!sigInfos.isEmpty()) {
            sigInfo = (SignerInfo) sigInfos.get(0);
        } else {
            throw new IOException("no signer infos!");
        }
        // Check that the public key of the certificate contained
        // in the package equals one of our trusted public keys.
        HashSet<Certificate> trusted = getTrustedCerts(deviceCertsZipFile == null ? DEFAULT_KEYSTORE : deviceCertsZipFile);
        PublicKey signatureKey = cert.getPublicKey();
        boolean verified = false;
        for (Certificate c : trusted) {
            if (c.getPublicKey().equals(signatureKey)) {
                verified = true;
                break;
            }
        }
        if (!verified) {
            throw new SignatureException("signature doesn't match any trusted key");
        }
        // The signature cert matches a trusted key.  Now verify that
        // the digest in the cert matches the actual file data.
        // The verifier in recovery *only* handles SHA1withRSA
        // signatures.  SignApk.java always uses SHA1withRSA, no
        // matter what the cert says to use.  Ignore
        // cert.getSigAlgName(), and instead use whatever
        // algorithm is used by the signature (which should be
        // SHA1withRSA).
        String da = sigInfo.getDigestAlgorithm();
        String dea = sigInfo.getDigestEncryptionAlgorithm();
        String alg = null;
        if (da == null || dea == null) {
            // fall back to the cert algorithm if the sig one
            // doesn't look right.
            alg = cert.getSigAlgName();
        } else {
            alg = da + "with" + dea;
        }
        Signature sig = Signature.getInstance(alg);
        sig.initVerify(cert);
        // The signature covers all of the OTA package except the
        // archive comment and its 2-byte length.
        long toRead = fileLen - commentSize - 2;
        long soFar = 0;
        raf.seek(0);
        byte[] buffer = new byte[4096];
        boolean interrupted = false;
        while (soFar < toRead) {
            interrupted = Thread.interrupted();
            if (interrupted)
                break;
            int size = buffer.length;
            if (soFar + size > toRead) {
                size = (int) (toRead - soFar);
            }
            int read = raf.read(buffer, 0, size);
            sig.update(buffer, 0, read);
            soFar += read;
            if (listener != null) {
                long now = System.currentTimeMillis();
                int p = (int) (soFar * 100 / toRead);
                if (p > lastPercent && now - lastPublishTime > PUBLISH_PROGRESS_INTERVAL_MS) {
                    lastPercent = p;
                    lastPublishTime = now;
                    listener.onProgress(lastPercent);
                }
            }
        }
        if (listener != null) {
            listener.onProgress(100);
        }
        if (interrupted) {
            throw new SignatureException("verification was interrupted");
        }
        if (!sig.verify(sigInfo.getEncryptedDigest())) {
            throw new SignatureException("signature digest verification failed");
        }
    } finally {
        raf.close();
    }
}
Also used : SignedData(org.apache.harmony.security.pkcs7.SignedData) PublicKey(java.security.PublicKey) SignatureException(java.security.SignatureException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) SignerInfo(org.apache.harmony.security.pkcs7.SignerInfo) RandomAccessFile(java.io.RandomAccessFile) ByteArrayInputStream(java.io.ByteArrayInputStream) ContentInfo(org.apache.harmony.security.pkcs7.ContentInfo) X509CertImpl(org.apache.harmony.security.provider.cert.X509CertImpl) Signature(java.security.Signature) Iterator(java.util.Iterator) Collection(java.util.Collection) List(java.util.List) BerInputStream(org.apache.harmony.security.asn1.BerInputStream) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

RandomAccessFile (java.io.RandomAccessFile)1607 IOException (java.io.IOException)761 File (java.io.File)691 FileChannel (java.nio.channels.FileChannel)284 ByteBuffer (java.nio.ByteBuffer)174 FileNotFoundException (java.io.FileNotFoundException)167 Test (org.junit.Test)152 FileOutputStream (java.io.FileOutputStream)91 FileLock (java.nio.channels.FileLock)91 MappedByteBuffer (java.nio.MappedByteBuffer)83 InputStream (java.io.InputStream)68 FileInputStream (java.io.FileInputStream)63 EOFException (java.io.EOFException)55 ArrayList (java.util.ArrayList)45 ByteArrayOutputStream (java.io.ByteArrayOutputStream)39 BufferedInputStream (java.io.BufferedInputStream)35 ByteArrayInputStream (java.io.ByteArrayInputStream)35 Random (java.util.Random)33 HashMap (java.util.HashMap)24 BinaryMapIndexReader (net.osmand.binary.BinaryMapIndexReader)23