how to prevent external xml file modification? - java

I'm coding a little library which will handle xml files to store some data, and I need this data to be handled only by the methods I provide in my library.
I know that xml is readable for both human and machine, and that if somebody really wants to modify the xml file he'll probably do it, so... do any of you have an idea that could work?

You can store more information in it, such as a hash of the content (before the hash was inserted of course).
When you will reload this file, you can check the hash. If it doesn't match with the current hash of your file, well it has been modified.

Well, there is no definitive way to block access to that file. But you can use several measures to make it hard on manual overriding of the file.
First thing you can do is lock the file (need to ensure OS compatibility) for as long as your application is running. Anyone can circumvent an OS file lock, but it is not trivial for an average user.
Second, you can consider encrypting the file on application termination. Restoring the key can be done from application code inspection, but again - a non-trivial effort.

As you said above, you have already implented a method that detects file changes, and you want a way how to prevent these modifications.
Usally, that's not possible. I'll explain at the end.
You have a few choices what to do:
If you want to prevent modifications while the program is running, you can lock the file. This will prevent applications from accessing it, but when your program exits, the lock will be released. (Example)
If you want to prevent access while the program is not running, you'll have to change file system permissions to forbid the user to edit the file. This is way more difficult as it is filesystem-related, and some filesystems like FAT haven't got file permissions at all.
You could write a "daemon" script that watches for file changes and revert them.
But all these possibilities have one problem - a program usally has the same permissions as the user, so everything the program does can be undone by the user. If your program has access, the user has too.
If you lock a file, the user could use a tool like Unlocker to release the lock, and edit it anyway. If your program sets file permissions, the user can simply change them back. On some systems, it might be possible to prevent this, but then your program looses access too. Bad. If you write a daemon, the user can kill it.
The only possibility is to have the program running with more rights than the user, and store the data on a place where the user has no access too. As example, on Windows, you can run it as a service. This requries the user to not have Administrator rights (or root, on Unix systems).
If the user is admin or root, you've lost, as he has full access to the system and you can't hide. (on Windows, there is one more level, the SYSTEM user, but an admin user can easily get these rights too).

Append a hash of the file concatenated with a secret key to the end of the file. Like an XML comment
<!-- 0123456789abcdefabcdef0123456789 -->
Upon opening the file you hash it again with the appended secret key and verify it.
Some psuedo code to clarify.
# Read
secret = "Secret key"
file = get_file_contents("file.xml")
content = strip_trailing_comment(file)
hash = get_content_hash(file)
if sha1(content + secret) == hash:
# File is valid
# Write
secret = "Secret key"
content = content_to_xml()
hash = sha1(content + secret)
content_with_hash = append_comment(hash)
write_to_file("file.xml", content_with_hash)
Hope that clears up potential misunderstandings. This way the code is still human readable, if you want that, and hard to tamper with.

As I understand from discussions and your question, you want to store the data as xml, and difficult for user to open/modify it.
In that case you will have to do some additional work:
Create the xml file with hash information as suggested by Colin HEBERT
Zip the file with password protection, the password to which only your app will know
There is a question on stackoverflow on how to password protect your zip file
In this approach, mind you, the xml file does not even become readable.
If you want your files to be readable, then you could probably use a seperate user id for your application (unix user id or windows userid) as owner of the files. and only allow that user to modify the files, but still this won't be a 100% solution.

Related

Locking a file in Java

I'm creating a program in Java that needs to create a file that will store a list of files accessible for various users. However I want to lock the file such that you couldn't just go to the file path outside of the program and view/change the file. Is there a way to do this?
Edit: I was looking into FileLock, but I couldn't tell if that locked the file just while the program was running, or if it locked it all times for anything trying to access it.
I think you are going the wrong way : you need the OS to make a file read-only and everybody with enough privileges will be able to override this and modify the file.
Instead of locking the file just encrypt it. It would be much more appropriate for your needs. See https://stackoverflow.com/a/27962481/1980659 for easy file encryption in Java.

How to check for read permission using JSch with SFTP protocol?

I know there is getPermissions() method but I don't know how to use it. How can I check using JSch, if user can read files?
First, you should generally ask a functional question (what do you want to achive), to get an useful answer. You ask for an implementation/technical detail, hence my possibly useless technical answer:
SftpATTRS.getPermissions() returns numerical representation of *nix permissions:
https://en.wikipedia.org/wiki/File-system_permissions#Numeric_notation
It's on its own NOT enough to determine, if the current user has permissions to read the file. In addition you have to know: who is the owner of the file (the getUId returns owner ID, but there's no API in SFTP to map that to/from username) and what is a group of the file (the getGId, the same).
So you can only be sure that user can read the file, when everyone have permissions to do so. What you can tell by presence of flag 0004 (read permissions for other class). But lack of the flag does not mean user cannot read the file, e.g. in case user is an owner of the file and there's flag 0400 (read permissions for owner class).
Also note that, when the remote system is not *nix (e.g. it's Windows), the getPermissions() value is usually irrelevant anyway.
Non-trivial, but only reliable way, is to dig into JSch source code and extract new API to open file for reading. Then you can just try to open the file (you do not have to read anything actually) to tell, if user has permissions to do so.
In general, there is no point trying to detect, if you have permissions for an operation. Try the operation and see if it succeeds or not.

java equivalent for mkstemp

Is there any way in Java to write out to a temporary file securely?
As far as I can tell, the only way to create a temporary file (createTempFile) does't actually open it at the same time, so there's a race condition between file open & file write. Am I missing something? I couldn't find the C source code behind createFileExclusively(String) in UnixFileSystem.java, but I doubt it can really do anything since the file open occurs in the Java code after the temp file is created (unless it tries to do something with file locks?).
The problem
Between when the temporary file is created & you open it, a malicious attacker could unlink that temporary file & put malicious stuff there. For example, an attacker could create a named pipe to read sensitive data. Or similarly if you eventually copy the file by reading it, then the named pipe could just ignore everything written & supply malicious content to be read.
I remember reading of numerous examples of temporary file attacks in the past 10+ years that exploit the race condition between when the name appears in the namespace and when the file is actually opened.
Hopefully a mitigating factor is that Java set's the umask correctly so a less-privileged user can't read/write to the file and typically the /tmp directory restricts permissions properly so that you can't perform an unlink attack.
Of course if you pass a custom directory for the temporary file that's owned by a less-privileged user who's compromised, the user could do an unlink attack against you. Hell, with inotify, it's probably even easier to exploit the race condition than just a brute force loop that does a directory listing.
http://kurt.seifried.org/2012/03/14/creating-temporary-files-securely/
Java
use java.io.File.createTempFile() – some interesting info at http://www.veracode.com/blog/2009/01/how-boring-flaws-become-interesting/
for directories there is a helpful posting at How to create a temporary directory/folder in Java?
Java 7
for files use java.io.File.createTempFile()
for directories use createTempDirectory()
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
Since Java 7 we have OpenOption.
An object that configures how to open or create a file.
Objects of this type are used by methods such as newOutputStream, newByteChannel, FileChannel.open, and AsynchronousFileChannel.open when opening or creating a file.
Of particular interest is StandardOpenOptions.CREATE_NEW.
Create a new file, failing if the file already exists. The check for the existence of the file and the creation of the file if it does not exist is atomic with respect to other file system operations.
So, you can do something like this:
FileChannel mkstemp() {
Path path = Files.createTempFile(null, null);
Files.delete(path);
return FileChannel.open(path, WRITE, CREATE_NEW);
}
Implementing the same template behaviour is left as exercise to the reader.
Keep in mind that on many systems, just because a file doesn't have a name doesn't at all mean it's inaccessible. For example, on Linux open file descriptors are available in /proc/<pid>/fd/<fdno>. So you should make sure that your use of temporary files is secure even if someone knows / has a reference to the open file.
You might get a more useful answer if you specify exactly what classes of attacks you are trying to prevent.
Secure against other ordinary userid's? Yes, on any properly functioning multi-user system.
Secure against the your own userid or the superuser? No.

Encrypting a folder for an Android app?

The app I am working on gets all the files from the sdcard but these files are really important and the app should maintain a security issue .So is there a way that the folder or directory that contains the file may be encrypted or locked with a key and only be used by my app?
Please help I am newbie and stuck at this point.
On Android, anything stored on the SD card is not protected by permissions and can be accessed by any application that has permission to touch the SD card (and by anything/anyone that can pull the card out and read it elsewhere). Basically, you need to assume that if you put resources there, they can be accessed by anyone. So, you are correct, you want to encrypt these resources so that even with that access, no one can access them.
Android includes plenty of support for well-known cryptography. In this case, you'll want to use symmetric encryption. The current best practice here is to use AES with 256-bit keys, all of which are natively supported in the Android class libraries. There are plenty of resources on how to do this in the developer documentation online and there is a complete rundown of all the issues you need to think about, and code examples of the entire process, in Application Security for the Android Platform (disclaimer: I'm the author of this book).
You do need a key to encrypt this data, and you need to keep that key secret (anyone that knows it can decrypt the data). You have two options...(1) ask the user for a password every time they use the application and then derive the key from that password, or (2) store the password in your application. (2) is dangerous as Android applications can be readily reverse engineered, where an attacker can simply look into your application and find the key. (1) is preferred as then there is no key stored for an attacker to recover...the tradeoff is that your users need to type in a password to use your application. What you should do here is a function of the risk analysis...how important is this data? Do you need it protected in a strong manner, or are you protecting it to just make things harder for an attacker? Only you can answer that, based on your use cases and the sensitivity/risk of your data.
Have a look at those resources:
http://source.android.com/tech/encryption/android_crypto_implementation.html
http://developer.android.com/reference/javax/crypto/package-summary.html
You should be aware that of course you shouldn't store the key to the encrypted data in cleartext but rather encrypt that itself with a password a user can choose or similar.
This is how to make a new folder:
String SaveFolder = "/Save";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File mySaveFolder = new File(extStorageDirectory + SaveFolder);
mySaveFolder.mkdir();
Got this code in the public void onCreate
Now it makes a folder with the name "Save".
Edit:
I looked there is not a way to set a password or something.
Though I read here http://developer.android.com/guide/topics/data/data-storage.html#filesInternal it is possible to save files in the internal memory, where users can't get acces too, but I never used that, so I can't help you with that.

Java - How to find that the user has changed the configuration file?

I am developing a Java Desktop Application. This app needs a configuration to be started. For this, I want to supply a defaultConfig.properties or defaultConfig.xml file with the application so that If user doesn't select any configuration, then the application will start with the help of defaultConfig file.
But I am afraid of my application crash if the user accidentally edit the defaultConfig file. So Is there any mechanism through which I can check before the start of the application that whether the config file has changed or not.
How other applications (out in the market) deal with this type of situation in which their application depends on a configuration file?
If the user edited the config file accidentally or intentionally, then the application won't run in future unless he re-installs the application.
I agree with David in that using a MD5 hash is a good and simple way to accomplish what you want.
Basically you would use the MD5 hashing code provided by the JDK (or somewhere else) to generate a hash-code based on the default data in Config.xml, and save that hash-code to a file (or hardcode it into the function that does the checking). Then each time your application starts load the hash-code that you saved to the file, and then load the Config.xml file and again generate a hash-code from it, compare the saved hash-code to the one generated from the loaded config file, if they are the same then the data has not changed, if they are different, then the data has been modified.
However as others are suggesting if the file should not be editable by the user then you should consider storing the configuration in a manner that the user can not easily edit. The easiest thing I can think of would be to wrap the Output Stream that you are using to write the Config.xml file in a GZIP Output Stream. Not only will this make it difficult for the user to edit the configuration file, but it will also cause the Config.xml file to take up less space.
I am not at all sure that this is a good approach but if you want to go ahead with this you can compute a hash of the configuration file (say md5) and recompute and compare every time the app starts.
Come to think of it, if the user is forbidden to edit a file why expose it? Stick it in a jar file for example, far away from the user's eyes.
If the default configuration is not supposed to be edited, perhaps you don't really want to store it in a file in the first place? Could you not store the default values of the configuration in the code directly?
Remove write permissions for the file. This way the user gets a warning before trying to change the file.
Add a hash or checksum and verify this before loading file
For added security, you can replace the simple hash with a cryptographic signature.
From I have found online so far there seems to be different approaches code wise. none appear to be a 100 hundred percent fix, ex:
The DirectoryWatcher implements
AbstractResourceWatcher to monitor a
specified directory.
Code found here twit88.com develop-a-java-file-watcher
one problem encountered was If I copy
a large file from a remote network
source to the local directory being
monitored, that file will still show
up in the directory listing, but
before the network copy has completed.
If I try to do almost anything non
trivial to the file at that moment
like move it to another directory or
open it for writing, an exception will
be thrown because really the file is
not yet completely there and the OS
still has a write lock on it.
found on the same site, further below.
How the program works It accepts a ResourceListener class, which is FileListener. If a change is detected in the program a onAdd, onChange, or onDelete event will be thrown and passing the file to.
will keep searching for more solutions.

Categories

Resources