I would like to determine the operating system of the host that my Java program is running programmatically (for example: I would like to be able to load different propertie
If you're working in a security sensitive environment, then please read this through.
Please refrain from ever trusting a property obtained via the System#getProperty(String)
subroutine! Actually, almost every property including os.arch
, os.name
, and os.version
isn't readonly as you'd might expect — instead, they're actually quite the opposite.
First of all, any code with sufficient permission of invoking the System#setProperty(String, String)
subroutine can modify the returned literal at will. However, that's not necessarily the primary issue here, as it can be resolved through the use of a so called SecurityManager
, as described in greater detail over here.
The actual issue is that any user is able to edit these properties when running the JAR
in question (through -Dos.name=
, -Dos.arch=
, etc.). This means that there's no way to determine if these properties are indeed actually accurate. Because of this, here are a few additional checks to try and avoid tampering:
// The first thing we're able to do is to query the filesystem.
switch (java.io.File.separator)
{
case "/":
// Windows is a potential candidate.
break;
case "\\":
// And here it could really be anything else.
break;
default:
// There's probably something really wrong here by now.
break;
}