My Question is, is it possible to execute my above command in java without making any changes anywhere i.e. by having default settings?
sudo -u -S pwd
The short answer is no, you will need to change settings to get sudo to do things differently than it currently does.
sudo may be the wrong tool for this. Sudo's rules are there to help system administrators configure a way to gain elevate privileges that is difficult to abuse to get additional/unintended privileges.
If you consider what sudo does for you:
- prompts for password to verify identity
- elevate privileges
- then optionally get privileges as another user
- logs sudo use to gain access or run commands
If you want your java to run arbitrary commands as arbitrary users without providing password for either those users or your own you are essentially replacing sudo. In that case you should create your own rules for how to prevent abuse.
There are basically two ways to do this:
- run your java with elevated privileges and carefully take and give back privileges you need (see setuid() seteuid() C function calls).
- run an external program to grab elevated privileges when you want them
In the case of #1 your java program is performing itself what sudo does, and you should implement your own set of rules to protect from abuse.
There are programs other than sudo to do #2. One example can be found in https://code.google.com/archive/p/exec-wrapper/downloads
This handy shell script creates a C program to run another command (usually a script). Then you compile the C program to a binary and mark that setuid root or really it could be setuid to any user. (mode :4555 and owner: root)
As long as you are on a filesystem that allows it, running the binary program will run the configured command as the userid that owns the binary program itself.