Validate input and prevent code injection - validation

I have a general software security question.
I have an application. This application can receive a file as an input and write it to the disk.
This file is a text file and i want to make sure the user is not trying to write a script that will be saved on the disk.
FYI - operating system is Linux.
What i have so far is:
1) I can write it with limited permissions. (i do not think this is secure enough)
2) I want to verify this is not a script. << How can i do this?

Set a unprivileged user and write that file disabling execution and reading for other user i think it's the best option.
The second option is impracticable , but you can try to make things difficult to an attacker:
Remove some special delimiters, e.g. PHP's
Remove (if you can)some special characters used normally, e.g. {},<>, etc
Remove any non printablechar (for partially-avoiding any binaryfile)

Related

How to prevent specific line/s inside a notepad file from being edited?

I have a file that can be opened thru notepad application.
Basically, this file(which can be opened thru notepad) is created by a software and that software uses the values inside that file to run. You can edit the values inside the file using its software.
I just want specific lines(values) to be restricted from being edited because I am implementing strict values inside that file that no one will be able to edit except me.
Is there any clever way to restrict specific lines inside that file from being edited?
I tried the basic way - I used the change permission read/write on that file but I can't change ANY values inside the file which is undesirable.
Note: I have very little to no experience about python, c++, or java but any suggestion will give me idea to learn from it.
Edit:
Here's an example inside the file:
[Type Data]
Comment=Standard Dispense
[Shared_A]
802=1
807=750
11=0
12=0
.
What I want is restrict the value from row/column "807" which is equal to number 750.
I want this number 750 not to be edited even from the software so that other people will not mess it up. I want to set this value as standard value.
Is there any program that you can write inside that file so that it cannot be edited from the software unless I open that file and edit it?
I work from a production/manufacturing company that uses the software that is used for dispensing.
A text file is simply a sequence of bytes that represent code units to encode code points in any given character set. Every byte value is a potentially legal character encoding, leaving no values to encode additional semantics (like guard regions).
With that it should be obvious that there is nothing you can do to partially limit editing of a file using a standard text editor. Whatever problem you are trying to solve, this is not a solution. Next time around you might want to ask about the problem you are trying to solve rather than your proposed solution.

Is the ReplaceFile Windows API a convenience function only?

Is the ReplaceFile Windows API a convenience function only, or does it achieve anything beyond what could be coded using multiple calls to MoveFileEx?
I'm currently in the situation where I need to
write a temporary file and then
rename this temporary file to the original filename, possibly replacing the original file.
I thought about using MoveFileEx with MOVEFILE_REPLACE_EXISTING (since I don't need a backup or anything) but there is also the ReplaceFile API and since it is mentioned under Alternatives to TxF.
This got me thinking: Does ReplaceFile actually do anything special, or is it just a convenience wrapper for MoveFile(Ex)?
I think the key to this can be found in this line from the documentation (my emphasis):
The replacement file assumes the name of the replaced file and its identity.
When you use MoveFileEx, the replacement file has a different identity. Its creation date is not preserved, the creator is not preserved, any ACLs are not preserved and so on. Using ReplaceFile allows you to make it look as though you opened the file, and modified its contents.
The documentation says it like this:
Another advantage is that ReplaceFile not only copies the new file data, but also preserves the following attributes of the original file:
Creation time
Short file name
Object identifier
DACLs
Security resource attributes
Encryption
Compression
Named streams not already in the replacement file
For example, if the replacement file is encrypted, but the
replaced file is not encrypted, the resulting file is not
encrypted.
Any app that wants to update a file by writing to a temp and doing the rename/rename/delete dance (handling all the various failure scenarios correctly), would have to change each time a new non-data attribute was added to the system. Rather than forcing all apps to change, they put in an API that is supposed to do this for you.
So you could "just do it yourself", but why? Do you correctly cover all the failure scenarios? Yes, MS may have a bug, but why try to invent the wheel?
NB, I have a number of issues with the programming model (better to do a "CreateUsingTemplate") but it's better than nothing.

Programmatically test whether an arbitrary user has access to an arbitrary file

I'd like to be able to write tests or specs that state that user soandso can read or edit file such_and_such. Although I would ultimately like this to be in RSpec, I'm assuming it will either all boil down to Bash commands (neatly wrapped in Ruby methods, of course), since it doesn't seem to be available in Ruby's File class, or anything else I've looked at. I've been hunting around for something in Bash to do this, and can't find anything (and nothing in the File class looks useful either). (Note: File.owned? does not do what I want, as it only tests if the process running the Ruby code is the owner, not if any arbitrary user has rights to edit or read, so it's significantly different on two counts.)
Is there any way to do this, built into Bash? (Or Ruby, or some Ruby gem, that I missed?) Or do I need to build a system myself, by getting owner and group info for the file, as well as read, write, and execute bits for each, and then looking up members of the group (in case so_and_so is not the owner), and seeing if the desired permissions are available to soandso either through ownership or group membership?
I'm currently only concerned about doing this on Unix-like systems, although something not dependent on a Unix shell that would also run on Windows would be a nice bonus.
Also, I'm interested in testing actual files, so something like FakeFS is not (as far as I can see) useful to me. I'm not trying to test how my Ruby code will interact with a file system, I'm trying to verify that all the necessary operations can be performed on actual files and directories. (Again,) I want to be able to specify that soandso can edit (or read) file such_and_such, NOT specify that file such_and_such is owned by soandso. The whole point of this is not specifying ownership (since that's an implementation detail and may need to change to accommodate other requirements, such as security) but only specify what my application and users actually need to be able to do to/in the file system.
If the user running your Ruby script has the necessary permissions, you could try running a test with the specific user with sudo.
sudo -u soandso test -r such_and_such
-r tests readability, -w writability. The return code is 0 if the test is passed.
By the way, I think that since the feature you are looking for could only be available for the super-user (since figuring out whether someone else has enough permissions would need you to have read permissions at least), it makes sense that it is not readily available in Ruby File class.
I haven't tried it, but I wonder if the FileTest methods would work as they say they operate on the "effective user id".
File.readable?(file_name) → true or false Link
Returns true if the named file is readable by the effective user id of this process.
File.writable?(file_name) → true or false Link
Returns true if the named file is writable by the effective user id of this process.
That in conjunction with seteuid might do the trick.
Process::Sys.seteuid(integer) → nil Link
Set the effective user ID of the calling process to integer. Not available on all platforms.
There is also setegid for group stuff...
Parse Permissions with File::Stat and Etc Modules
While this isn't a pre-packaged solution, you should be able to inspect a given file where you have sufficient access for stat in order to get mode, uid, and gid information. You can then parse /etc/passwd and /etc/group in order to find out whether a given user would have sufficient permissions.
Some building blocks include:
# Get the file's octal mode.
File.stat('/etc/passwd').mode.to_s(8)
#=> "100644"
# Get the group ID assigned to the file.
File.stat('/etc/passwd').gid
#=> 0
# Get the username associated with the given GID.
Etc.getpwuid(0).name
#=> "root"
You could also use the id utility to get information about a given user. For example:
%x{id root}
#=> "uid=0(root) gid=0(root) groups=0(root)\n"
but I think it would be easier to use the standard libraries rather than parse the output from id. YMMV.

Escaping special characters in User Input in IzPack Installer

I have an IzPack installer that takes in a lot of User Inputs and substitutes them in an XML file. This XML file is actually the configuration file for my application.
There is a major problem that I have hit and I cant move on from it.
In the Input fields (in the installer) user can enter any text and also special characters like & # % ' etc. These special characters messes up my XML file as they are no allowed in the XML syntax and needs to be escaped. for example for & one would need &
So far I have been asking the user to do this, as in escape the special characters themselves, but thats now working either.
Is there a way to have this done automatically? I really need a solution fast.
I am using IzPack V 4.1
You should use a proper XML Api (SAX, DOM) to generate the XML file, this will apply the correct encoding automatically. This may look more complicated first but guarantees that a well formed, syntactically correct file is written.
Searching for JAXP should give you a proper starting point.

What are the best practices for building multi-lingual applications on win32?

I have to build a GUI application on Windows Mobile, and would like it to be able user to choose the language she wants, or application to choose the language automatically. I consider using multiple dlls containing just required resources.
1) What is the preferred (default?) way to get the application choose the proper resource language automatically, without user intervention? Any samples?
2) What are my options to allow user / application control what language should it display?
3) If possible, how do I create a dll that would contain multiple language resources and then dynamically choose the language?
For #1, you can use the GetSystemDefaultLangID function to get the language identifier for the machine.
For #2, you could list languages you support and when the user selects one, write the selection into a text file or registry (is there a registry on Windows Mobile?). On startup, use the function in #1 only if there is no selection in the file or registry.
For #3, the way we do it is to have one resource DLL per language, each of which contains the same resource IDs. Once you figure out the language, load the DLL for that language and the rest just works.
Re 1: The previous GetSystemDefuaultLangID suggestion is a good one.
Re 2: You can ask as a first step in your installation. Or you can package different installers for each language.
Re 3:
In theory the DLL method mentioned above sounds great, however in practice it didn't work very well at all for me personally.
A better method is to surround all of the strings in your program with either: Localize or NoLocalize.
MessageBox(Localize("Hello"), Localize("Title"), MB_OK);
RegOpenKey(NoLocalize("\\SOFTWARE\\RegKey"), ...);
Localize is just a function that converts your english text to a the selected language. NoLocalize does nothing.
You want to surround your strings with these values though because you can build a couple of useful scripts in your scripting language of choice.
1) A script that searches for all the Localize(" prefixes and outputs a .ini file with english=otherlangauge name value pairs. If the output .ini file already contains a mapping you don't add it again. You never re-create the ini file completely, your script just adds the missing ones each time you run your script.
2) A script that searches all the strings and makes sure they are surrounded by either Localize(" or NoLocalize(". If not it tells you which strings you still need to localize.
The reason #2 is important is because you need to make sure all of your strings are actually consciously marked as needing localization or not. Otherwise it is absolutely impossible to make sure you have proper localization.
The reason for #1 instead of loading from a DLL is because it takes no work to maintain this solution and you can add new strings that need to be translated on the fly.
You ship the ini files that are output with your program. You also give these ini files to your translators so they can convert the english=otherlanguage pairs. When they send it back to you, you simply replace your checked in .ini file with the one given by your translator. Running your script as mentioned in #1 will re-add any missing translations if any were done while the translator was translating.

Resources