Deleting file (including content cleaning) - android

In my application I need to delete file with sensitive information. For that I'm writing to file some garbage generated by random bytes and then deleting using File.delete() method, like here:
long size=file.length();
Random r=new SecureRandom();
OutputStream os=new BufferedOutputStream(new FileOutputStream(file));
while(size > 0)
{
os.write(r.nextInt());
size--;
}
os.close();
file.delete();
So the question is: does this method guarantee that if someone will undelete file one will find only garbage instead of real content? I'm not completely sure that writing to file would guarantee that the same sectors in underline Linux filesystem will be overwritten... Please give a hint - what to do - to be sure that file content is destroyed.

No, it doesn't guarantee that. The reason for that is the filesystem implementation underneath - it is not forced by any standards to ever overwrite existing data. A fully valid, (POSIX-)standard-conforming way of implementing a write operation for a filesystem is to allocate a brand new block of storage, put your "new" data into there, and then change the block structure of the file in such a way that the new data block is referenced for the location you write in the file and the previously-used data block is "released" - whatever that means in detail. After that, you can't access the old data anymore (through the filesystem) but it's still on disk, so save erasing the entire storage medium you're not erasing the traces.
Many filesystem implementations of functionality like snapshots or replication rely on this mechanism (Copy-On-Write). Linux Btrfs or Solaris ZFS use it extensively. I think Android's YAFFS does too. As Chris mentioned, the wear leveling FTL in any flash memory will behave like that as well.
The answer that's usually given how to deal with this problem on filesytems employing copy-on-write is to never have it occur in the first place. I.e. encrypt the file when writing it, and "throw away the key" when deleting the file. What you can't decrypt you can't recover ... but I agree there's the chicken-egg problem of where/how to store the encryption key.

No, it does not guarantee that the original blocks are overwritten - on a flash device it's extremely unlikely that they would be, though one might need tools below the O/S level or even below the chip data sheet interface level to do the recovery.
You really cannot guarantee erasure except if you have flash memory with no on-board controller that can substitute blocks and repeatedly erase and overwrite it from its low level driver, or you physically destroy the media.
If you are talking about the SDcard with a fat filesystem, I believe based on past recovery of an accidentally saved back picture edit that linux doesn't even try to write back to the same blocks of the file system.
You can confirm that the data is still recoverable by putting the card in a linux box and grepping the raw device file for something known to be in the deleted file; unfortunately this will not prove that the data might not still be there in a block that's been re-mapped by the device driver or an on-chip controller, and potential accessible by a lower-level tool.

Related

Permanently delete files Android

I found an android app named Super Erase that deletes files and folder permanently from android device so that the file deleted cant be recovered anymore..here is the application i am talking about ...but i was wondering how to that and i know it is made with android studio ..i tried the regular way to delete file.delete() but still the file can be recovered.can i have any help .
For starters, secure file deletion on flash media is a complex problem, with no quick and easy answers. The paper Reliably Erasing Data From Flash-Based Solid State Drives gives a good overview of the problems, the potential solutions, and their limitations. They conclude that
For sanitizing entire disks, ... software techniques work most, but not
all, of the time. We found that none of the available software
techniques for sanitizing individual files were effective. [emphasis added]
NIST 800-88 also has a good overview of the technology trends contributing to the problem, along with some minimum recommendations (appendix A) for Android devices. However they tend to be either whole-disk erasure (factory reset), or rely on cryptographic erasure (CE), rather than being general file erasure methods.
But all is not lost. Even if you can't sanitize individual files, you could hope to wipe all the unallocated space after deleting files. The article Secure Deletion on Log-structured File Systems (Reardon, et al.) describes a fairly promising way to do that in user-mode software. Android's internal memory uses (always?) a log-structured file system.
This paper's "purging" method does not require kernel-level access, and doesn't seem to require any native code on Android. (Note that the term "purging" is used a little differently in documents like NIST 800-88.) The basic idea is to delete all the sensitive data, then fill in the remaining space on the drive with a junk data file, and finally delete the junk data file.
While that takes more time and effort than just overwriting the deleted files themselves (several times in different patterns), it seems to be very robust even when you have to deal with the possibility of wear-leveling and log-structure FS.
Caveat and Further Measures
The main caveat for me is about the conditions mentioned by Reardon et al. in the above paper:
Purging will work for any log-structured file system provided both the
user’s disk quota is unlimited and the file system always performs
garbage collection to reclaim even a single chunk of memory before
declaring that the drive is unwritable. [emphasis mine]
The second condition seems pretty likely to be fulfilled, but I don't know about the first one. Does Android (or some manufacturers' versions of it) enforce quotas on disk space used by apps? I have not found any info about user quotas, but there are quotas for other niches like browser persistent storage. Does Android reserve some space for system use, or for each app's caching, for example, that can't be used for other things? If so, it should help (albeit with no guarantees) if we begin purging immediately after the sensitive files are deleted, so there is little time for other filesystem activity to stake a claim to the recently freed space.
Maybe we could mitigate these risks by cyclical purging:
Determine the remaining space available (call it S) on the relevant partition, e.g. using File.getUsableSpace()
Write a series of files to the partition; each one is, say, 20% of the initial S (subject to file size limits).
When we run out of space, delete the first couple of files that we created, then write another file or two as space allows.
Repeat that last step a few times, until you've reached a threshold you're satisfied with. Maybe up to the point where you've written 2*S worth of filler files; tweak that number to balance speed against thoroughness. How much you actually need to do this would be an area for more research.
Delete the remaining filler files.
The idea with cyclical purging is that if we run out of quota to overwrite all free space, deleting the filler files just written will free up more quota; and then the way log-structured filesystems allocate new blocks should allow us to continue overwriting the remaining blocks of free space in sequence, rather than rewriting the same space again.
I'm implementing this method in a test app, and will post it when it's working.
What about FAT-formatted microSD cards?
Would the same methods work on external storage or microSD cards? FAT is block-structured, so would the purge method apply to FAT-formatted SD cards?
On most contemporary flash memory devices, such as CompactFlash and
Secure Digital cards, [wear leveling] techniques are implemented in
hardware by a built-in microcontroller. On such devices, wear leveling
is transparent and most conventional file systems can be used on them
as-is. (https://en.wikipedia.org/wiki/Wear_leveling)
...which suggests to me that even on a FAT-formatted SD card, wear leveling means that the traditional Gutmann methods would not work (see his "Even Further Epilogue") and that a method like "purging" would be necessary.
Whether purging is sufficient, depends on your security parameters. Wear leveling seems to imply that a block could potentially be "retired" at any time, in which case there is no way to erase it without bypassing the microcontroller's wear leveling. AFAIK this can't be done in software, even if you had kernel privileges; you'd have to design special hardware.
However, "retiring" a bad block should be a fairly rare event relative to the life of the media, so for many scenarios, a purging method would be secure enough.
Erasing the traces
Note that Gutmann's method has an important strength, namely, to erase possible traces of old data on the storage media that could remain even after a block is overwritten with new data. These traces could theoretically be read by a determined attacker with lots of resources. A truly thorough approach to secure deletion would augment a method like Gutmann's with purging, rather than replacing it.
However, on log-structured and wear-leveled filesystems, the much bigger problem is trying to ensure that the sensitive blocks get overwritten at all.
Do existing apps use these methods?
I don't have any inside information about apps in the app store, but looking at reviews for apps like iShredder would suggest that at best, they use methods like Reardon's "purging." For example, they can take several hours to do a single-pass wipe of 32GB of free space.
Also note limitations: The reviews on some of the secure deletion apps say that in some cases, the "deleted" files were still accessible after running the "secure delete" operation. Of course we take these reviews with a grain of salt -- there is a possibility of user error. Nevertheless, I wouldn't assume these apps are effective, without good testing.
iShredder 4 Enterprise helpfully names some of the algorithms they use, in their app description:
Depending on the edition, the iShredderâ„¢ package comes with deletion
algorithms such as DoD 5220.22-M E, US Air Force (AFSSI-5020), US Army
AR380-19, DoD 5220.22-M ECE, BSI/VS-ITR TL-03423 Standard,
BSI-VS-2011, NATO Standard, Gutmann, HMG InfoSec No.5, DoD 5220.22 SSD
and others.
This impressive-sounding list gives us some pointers for further research. It's not clear how these methods are used -- singly or in combination -- and in particular whether any of them are represented as being effective on their own. We know that Gutmann's method would not be. Similarly, DoD 5220.22-M, AFSSI-5020, AR380-19, and Infosec No. 5 specify Gutmann-like procedures for overwriting sectors on hard drives, which would not be effective for flash-based media. In fact, "The U.S. Department of Defense no longer references DoD 5220.22-M as a method for secure HDD erasure", let alone for flash-based media, so this reference is misleading to the uninformed. (The DoD is said to reference NIST 800-88 instead.) "DoD 5220.22 SSD" sounds promising, but I can't find any informative references for it. I haven't chased down the other algorithms listed, but the results so far are not encouraging.
When you delete file with standard methods like file.delete() or runtime.exec("rm -f my_file") the only job that kernel does is removing info about file from auxiliary filesystem structures. But storage sectors that contain actual data remain untouched. And because of this recovering is possible.
This gives an idea about how we can try to remove file entirely - we should erase all sectors somehow. Easiest approach is to rewrite all file content with random data few times. After each pass we must flush file buffers to ensure that new content is written to storage. All existing methods of secure file removal spin around above principle. For example this one. Note that there is no universal method that works well across all storage types and filesystems. I guess you should experiment by yourself and try to implement some of the existing approaches or design your own. E.g. you can start from next:
Overwrite and flush file 10 times with random data (use FileOutputStream methods). Note!!! Don't use zeros or another low entropy data. Some filesystems may optimize such sparse files and leave some sectors with original content. You can use /dev/urandom file as source of random data (this is a virtual file and it is endless). It gives better results and works faster then well-known Random class.
Rename and move file 10 times. Choose new file names randomly.
Then truncate file with FileChannel.truncate().
And finally remove file with File.delete().
Of course you can write all logic in native code, it may be even somewhat easier than in Java. Described algorithm is just an example. Try doing in that way.
The standard filesystem API won't give you a simple function call for that.
You will have to use the underlaying native API for FileIO. Although I have never used it, theres a library for that:
https://github.com/johanneslumpe/react-native-fs
There are two answers to this question.
First, to answer the direct question of how some of these apps might be doing secure single file delete: what you do is actually open the file and replace the contents with zeros many times. The method sounds stupid, but I have worked with filesystem-level encryption on Android in the past and I found that the above holds true for many secure file delete solutions out there. For a seemingly compliant security, you can repeat writing zeros 7 times (or whatever the NIST standards specify for your hardware type).
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("*", "0");
Files.write(path, content.getBytes(charset));
The right answer to this question is however different. On modern SSD drives and operating systems, it is insecure to delete single files. Therefore, these apps don't really offer a compelling product. Modern operating systems store fragments of the file in different places, and it is possible that even after you have zeroed out the most recent version of the file block-by-block and also overwrote all metadata, that a fragment from an older version of the file might be left over in another part of the drive.
The only secure way to delete sensitive content from a disk is to zero out the entire disk multiple times before discarding the disk.
#LarsH's answer about wiping all unallocated space after deleting files is compelling, but perhaps impractical. If you simply want to secure delete files so no one can scan the disk to recover it, then a better solution is the full-disk encryption. This was in-fact the entire appeal of full-disk encryption. This is why Apple stopped supporting secure file delete in their Mac OSX and iOS, and switched to full-disk encryption as default on all iPhones. Android phones have full-disk encryption as well now.
EDIT:
If you are looking for a true solution for a customer, your best bet is to use single file encryption. Once you destroy your key which only your app would know, there is no way to decrypt the file even if someone found it on the disk.
There exists no real solution for deleting files securely on SSDs. You can only give a false sense of security to non-technical people who still remember the old HDD days.

FileUtils.copyDirectory doesn't write date modified correctly unless the Android SD card is unmounted

FileUtils.copyDirectory doesn't write date modified correctly unless the Android SD card is unmounted. Using this simple bit of code from FileUtils:
try {
FileUtils.copyDirectory(srcDir2, destDir2);
} catch (IOException e) {
I can copy a directory from the internal storage on the phone to the sd card preserving the date modified information on the files in the directory which is essential for my app.
Sadly if the SD card is removed without ejecting it all the date modified information on the files in the copied dir is set to the time the files were copied. if the SD is unmounted correctly then the date modified information is preserved correctly.
I have tried the flush and close functions but they are not relevant to this kind of file. What code am I missing to finalize the directories without unmounting? I am using an android device will a full size SD slot and I cant risk loosing all the information if it gets knocked out without a proper eject
There's a version of this method that accepts a flag as third parameter to try to control the date of last modification. You can check the docs here. But looks like the method you are using also tries to preserve the date by default. In fact, reading the source code, the method you are using just calls this method with the third parameter set to true.
In the docs for your method it is said:
Note: This method tries to preserve the files' last modified date/times using File.setLastModified(long), however it is not guaranteed that those operations will succeed. If the modification operation fails, no indication is provided.
In the end what this library does each time it copies a file or dir is to call File.setLastModified over the destination file with the last modified date of the source file. This method has been reported to be unreliable in Android, as you can see in these other questions:
Android set last modified time for the file
file.lastModified() is never what was set with file.setLastModified()
Is it possible to reset the last modified date of an Android file?
But in your case, I think you are trying to provide a workaround for something that is just designed that way. I'm no expert, but this is managed by either the OS or the FileSystem. The unmounting mechanism serves a purpose, I think you can't do much about it as an app developer.

RandomAccessFile on Android

I have a file on android phone which I would like to securely wipe it.
I read this.
It mentions This is especially true on mobile devices containing flash, which has wear-leveling to prolong its life and isn't guaranteed to overwrite the same block internally when you overwrite a block on the filesystem.
So, if I would to use the code on.Would it securely wiped on android phone ? Or when I use RandomAccessFile to write data to the file, it would be on a new block instead of the original block ?
Is it totally 100% impossible to get known of the exact block pointer on android ?
Or I have to recursively create a file, write with random data until the storage space hits the max. Then I try to edit the file I wish to delete. Which the flash will be force to use the original block while I rewrite the content and delete it.
Try to read the documentation about the Objects and Methods used in the code you mentioned This , nothing points that you write over the real Blocks used to save the file, and note the file can be written in Non-Sequential blocks, i think my friend told me about article discuss this issue, and they solved it using C++.

How to copy cut files safely

Do you know any way for safe copy cut operation in Android?
I want to make a file manager. I can do them with FileReader/Writer, but as is not safe (if app crashes), I want another safe way to do this.
You should probably design a fail-safe order of operations. For example (just making this up, haven't validated it thoroughly):
Record in a persistent worklist file (/shared preference, etc) what you intend to do
Copy the file
Verify the copy is complete
Only then remove the original
Cleanup the record in the worklist
You should not do the work on the UI thread. You may want to consider doing it in a service to handle the case of huge files (or large numbers of files) which may take a while.
You may also want to consider if you can in some cases use the File.renameTo() method - this would require that the source and destination be on the same partition (ie, both on external storage). Also you would have to make sure that the destination directory exists.
Also put some thought into what you are going to do if the selected object is a directory rather than a file...

How to encrypt whole disk?

I would like to write application (as background service) which will encrypt whole file system totally. The questions are:
Is it possible, such that all Android services will work smoothly? Like, say Microsoft's BitLocker?
If so - can someone point me to some sources/docs?
No this is not possible thought the API.
You'd have to get the source code of Android and try to implement that yourself baking your own custom system image.
However I don't think it is possible at all.
Encrypted file system would be possible only via kernel-mode driver, which means a custom ROM for a device.
Its not clear if you are doing this to be secure, or only in order for a trojan to claim payment for restoring the files ;)
Encrypting files after they have been written in plaintext will leave the plaintext spread around your Flash (or disk) until that space is later reclaimed for new files. Its basically not secure. You have to encrypt before bytes get written to disk.
Android runs on Linux, and device drivers for storage, whilst modular, are compiled into the kernel. So unless you are distributing a custom Android image, you cannot post-install install a driver on someone's device.
There has been discussion like this on the mailing list here.

Categories

Resources