Can I setuid a perl script? - perl

I made a perl script to change owner of a file owned by some other user. Script is complete. My administrator save that in /sbin directory and set uid for it using chmod u+s name_of_script. But when I run this script it gives me error that chown operation is not permitted. I made a C program and it works by following same steps. So my question is if setuid is working for perl then I should not get that error because C code did not give me any error. So can i setuid for perl script or I should go with c code.
Don't tell me to ask administrator to change owner each time. Actually in server I have user name staging and I am hosting a joomla site in it. Now when I install some plugin then files related to that plugin are owned by www-data. So that's why I do not want to go to admin each time. Or you can give me some other solution also regarding my problem.

Many unix systems (probably most modern ones) ignore the suid bit on interpreter scripts, as it opens up too many security holes.
However, if you are using perl < 5.12.0, you can run perl scripts with setuid set, and they will run as root. How it works is that when the normal perl interpreter runs, and detects that the file you are trying to execute has the setuid bit set, and it then executes a program called suidperl. Suidperl takes care of elevating the user's privileges, and starting up the perl interpreter in a super-secure mode. suidperl is itself running with setuid root.
One of the consequences of this is that taint mode is turned on automatically. Other additional checks are also performed. You will probably see messages like:
Insecure $ENV{PATH} while running setuid at ./foobar.pl line 3.
perlsec provides some good information about securing such scripts.
suidperl is often not installed by default. You may have to install it via a separate package. If it is not installed then you get this message:
Can't do setuid (cannot exec sperl)
Having said all of that - you would be much better off using sudo to execute actions with elevated privileges. It is much more secure as you can specify exactly what is allowed to be executed via the sudoers file.
As of perl 5.12.0, suidperl was dropped. As a result, if you want to run a perl script on perl >= 5.12.0 with setuid set, you would have to write your own C wrapper. Again I recommend sudo as a better alternative.

No, you cannot use setuid aka chmod +s on scripts. The script's interpreter would be the thing that would actually need to be setuid, but doing that is a really bad idea. REALLY bad.
If you absolutely must have something written in Perl as setuid, the typical thing to do would be to make a small C wrapper that is setuid and executes the Perl script after starting. This gives you the best of both worlds in having a small and limited setuid script but still have a scripting language available to do the work.

If you have a sudo configuration that allows it (as most desktop linux distributions do for normal users), you can start your perl script with this line:
#!/usr/bin/env -S -i MYVAR=foo sudo --preserve-env perl -w -T
Then in your script before you use system() or backticks explicitly set your $ENV{PATH} (to de-taint it):
$ENV{PATH} = '/usr/bin';
Other environment variable that your script explicitly mentions or that get implicitly used by perl itself will have to be similarly de-tainted (see man perlsec).
This will probably (again depending on your exact sudo configuration) get you to the point where you only have to type in your root password once (per terminal) to run the script.
To avoid having to type your password at all you can add a line like this to the bottom of /etc/sudoers:
myusername ALL=(ALL) NOPASSWD:ALL
Of course you'd want to be careful with this on a multi-user system.
The -S options to env splits the string into separate arguments (making it possible to use options and combinations of programs like sudo/perl with the shebang mechanism). You can use -vS instead to see what it's doing.
The -i option to env clears the environment entirely.
MYVAR=foo introduces an environment variable definition.
The --preserve-env option to sudo will preserve MYVAR and others.
sudo sets up a minimal environment for you when it finds e.g. PATH to be missing.
The -i option to env and --preserve-env option to sudo may both be omitted and you'll probably end up with a slightly more extensive list of variables from your original environment including some X-related ones (presumably the ones the sudo configuration considers safe). --preserve-env without -i will end up passing along your entire unsanitized environment.
The -w and -T options to perl are generally advisable for scripts running as root.

Related

How do I get Perl to run an alias I've defined in BASH?

I have a script that opens up different files at the same time.
My problem here is that when I run system() on the alias I've defined in bash which points to /home/user1/Software/nc, perl tells me that it can't execute the alias because there is no file/directory at the current location.
I know that the alias works because when I invoke it directly in a shell, it opens fine.
Funny enough, I can do system("firefox") within my script fine, but not the alias. How do I use this alias in this script without it breaking?
Perl won't run bash, it will execute the command directly. You can call
bash -c your_command
instead of calling the command itself in Perl.
As it is, this doesn't load your aliases. You need to open an interactive shell, as in #MortezaLSC's answer. There supposedly is a way of loading aliases correctly in a non-interactive shell, but I can't figure it out.
But why don't you just use the command you have aliased to directly in perl? The only reason I could see not to do this, is if your alias is going to change in the future, but you will still want to run whatever command it points to. This seems weird and dangerous to say the least.
Aliases are designed to reduce the typing you do if you invoke commands with the same options etc all the time. They're not all-purpose macros for bash. Bash has functions for doing more complicated stuff, but why would you want to call non-trivial bash code from a perl script? It doesn't seem like you really need this here. Keep the complexity, and the potential for modification and failure, in one place (the perl script).
See a couple of answers to similar questions:
https://unix.stackexchange.com/a/1499/41977
https://superuser.com/a/183980/187150
If you're smart, you made it so your alias is only defined for interactive shells, so you'll have to launch bash and specify that you want an interactive shell using -i.
system('bash', '-i', '-c', 'shell command');
Is it working?
system 'bash -i -c "your alias parameter"';

How can I find out what script, program, or shell executed my Perl script?

How would I determine what script, program, or shell executed my Perl script?
Example: I might want to have human readable output if executed from shell (customized for each type of shell), a different type of output if called as a script from another perl script, and a machine readable format if executed from a program such as a continuous integration server.
Motivation: I have a tool that changes its output based on which shell executes it. I'd normally implement this behavior as an option to the script, but this tool's design doesn't allow for options. Other shells have environment variables that indicate what shell is running. I'm working on a patch to support Powershell, which has no such special variable.
Edit: Many of these answers happen to be linux specific. Unfortuantely, Powershell is for Windows. getppid, the $ENV{SHELL} variable, and shelling out to ps won't help in this case. This script needs to run cross-platform.
You use getppid(). Take this snippet in child.pl:
my $ppid = getppid();
system("ps --no-headers $ppid");
If you run it from the command line, system will show bash or similar (among other things). Execute it with system("perl child.pl"); in another script, e.g. parent.pl, and you will see that perl parent.pl executed it.
To capture just the name of the process with arguments (thanks to ikegami for the correct ps syntax):
my $ppid = getppid();
my $ps = `ps --no-headers -o cmd $ppid`;
chomp $ps;
EDIT: An alternative to this approach, might be to create soft links to your script, make the different contexts use different links to access your script and inspect $0 to build logic around that.
I would suggest a different approach to accomplish your goal. Instead of guessing at the context, make it more explicit. Each use case is wholly separate, so have three different interfaces.
A function which can be called inside a Perl program. This would likely return a Perl data structure. This is far easier, faster and more reliable than parsing script output. It would also serve as the basis for the scripts.
A script which outputs for the current shell. It can look at $ENV{SHELL} to discover what shell is running. For bonus points, provide a switch to explicitly override.
A script which can be called inside a non-Perl program, such as your continuous integration server, and issue machine readable output. XML and/or JSON or whatever.
2 and 3 would be just thin wrappers to format the data coming out of 1.
Each is tailored to fit its specific need. Each will work without heuristics. Each will be far simpler than trying to guess the context and what the user wants.
If you can't separate 2 and 3, have the continuous integration server set an environment variable and look for it.
Depending on your environment, you may be able to pick it up from the environment variables. Consider the following code:
/usr/bin/perl -MData::Dumper -e 'print Dumper(\%ENV);' | grep sh
On my Ubuntu system, it gets me:
'SHELL' => '/bin/bash',
So I guess that says I'm running perl from a bash shell. If you use something else, the SHELL variable may give you a hint.
But let's say you know you're in bash, but perl is run from a subshell. Then try:
/bin/sh -c "/usr/bin/perl -MData::Dumper -e 'print Dumper(\%ENV);'" | grep sh
You will find:
'_' => '/bin/sh',
'SHELL' => '/bin/bash',
So the shell is still bash, but bash has a variable $_ which also show the absolute filename of the shell or script being executed, which may also give a valuable hint. Similarily, for other environments there will most probably be clues left in the perl %ENV hash that should give you valuable hints.
If you're running PowerShell 2.0 or above (most likely), you can infer the shell as a parent process by examining the environment variable %psmodulepath%. By default, it points to the system modules under %windir%\system32\windowspowershell\v1.0\modules; this is what you would see if you examine the variable from cmd.exe.
However, when PowerShell starts up, it prepends the user's default module search path to this environment variable which looks like: %userprofile%\documents\windowspowershell\modules. This is inherited by child processes. So, your logic would be to test if %psmodulepath% starts with %userprofile% to detect powershell 2.0 or higher. This won't work in PowerShell 1.0 because it does not support modules.
This is on Windows XP with PowerShell v2.0, so take it with a grain of salt.
In a cmd.exe shell, I get:
PSModulePath=C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\
whereas in the PowerShell console window, I get:
PSModulePath=E:\Home\user\WindowsPowerShell\Modules;C:\WINDOWS\system32\WindowsP
owerShell\v1.0\Modules\
where E:\Home\user is where my "My Documents" folder is. So, one heuristic may be to check if PSModulePath contains a user dependent path.
In addition, in a console window, I get:
!::=::\
in the environment. From the PowerShell ISE, I get:
!::=::\
!C:=C:\Documents and Settings\user

In Perl CGI, how can I use UNIX commands?

I'm trying to run ssh, mkdir from a Perl CGI script. It's not working. But in normal Perl script, it is working fine. Can any one tell me how to run commands in a Perl CGI script?
If you're running this script via a webserver, chances are the active user (e.g. "nobody", "www", etc) may not have the necessary privileges to execute commands like mkdir and ssh. If so, that is not something that perl can fix. You can test who the active user is with something like:
print "The active user is: ", `whoami`;
It is also a security concern, to have your web user privileges set to create files and perform commands.
system() or popen() are probably what you're looking for, if you're feeling dirty I think you can use back ticks too.
Do you need to run unix commands? Perl has a built-in mkdir, and there are modules to handle SSH. Normally a CGI process is going to have limited capabilities or access to the system. The more you can do in Perl the better.

How can i run perl script from anywhere in unix environment?

I have this perl script that I need to distribute to my coworkers who want to run the script from anywhere in the unix environment. What can I do on my part to make running this PERL script easy for them? For example, they can just have the PERL script somewhere in their directory and run just typing
./xyz.pl ttt.conf
with no path declared (like /home/abc/bin/ddd/xyz.pl ttt.conf).
The way I used to do it is add a "bin" directory in your home directory, and add it to the $PATH variable.. then you can add any script you want to use to that directory.
I am no longer familiar with the exact syntax, but something like:
in .bashrc:
$PATH = ( $PATH , $HOME/bin )
Then place the script in /home/user/bin (assuming $HOME == /home/user). When you reload the shell, it will be usable like any normal command/program.
ETA: See robert's comment below on syntax. Also, to allow your co-workers to use a script of yours, you can simply use a hard-coded path, such as /home/patrick/bin.
Put the script in /usr/local/bin (or anywhere else in $PATH). Your sysadmin may have to help you.
The technique I use is:
#!/usr/bin/env perl
This is a common way of getting the command interpreter to find Perl without either (a) moving the file, or (b) declaring the explicit path for Perl in the shebang.
It's mentioned under portability at: http://en.wikipedia.org/wiki/Shebang_(Unix)
You all are kind of right... but that perl script can sit in your path till the cows come home... and it ain't gonna run... until you set the executable bit....
:bin localadmin$ ./perlextip
-bash: ./perlextip: Permission denied
:bin localadmin$ chmod +x perlextip
:bin localadmin$ ./perlextip
Exit 0! Yeehaw.
Also, it should be noted that it need not be IN your path.... You can just call it by the full path, preceeded with a period and a slash, to execute it..
:/ localadmin$ ./ServiceData/UNIX/bin/extip
Exit 0! Yeehaw.
You can also create an alias for such a command in your ~/.bash_profile, or the such, which will let you make a system-wide shortcut of sorts, and you can even throw in a sudo, or the like, if you were so inclined... Then just call that "extip" by name anywhere, you'll be prompted for a password and, all will be well in the world.
alias extip='sudo ./ServiceData/UNIX/bin/extip'

Redirecting stdin/stdout to/from a remote host via ssh

I'm trying to write a perl script that redirects its stdin to a remote machine and at the same time redirects the stdout of the remote machine to its stdout:
callingProgram <--> myScript <--> sshTunnelToRemote
See this question and bdonlan's answer for the purpose of the script.
First I tried to use the open2() function from the IPC library but for reasons described here it doesn't seem to be a good approach, I didn't even get a simple grep command working.
My second idea was to use the Net::SSH::Perl or the Expect libraries but they're not available on the machine where the script is supposed to be executed and I can't install libraries there.
So my question is what could be a simple way to achieve what I want? Solutions using [ba]sh or even C++ are also possible. The targeted platform is Solaris 10.
Seems like you could probably get away with nothing more than system() — don't pass the data from your stdin to ssh's stdin and from your stdout to ssh's stdout; just let ssh inherit your stdin and stdout. Unless you need to modify the data in transit somehow.
cpanminus can do this for you
Running:
cd ~/bin
curl -LO http://xrl.us/cpanm
chmod +x cpanm
Now you can try your problem using the right tools (e.g. Net::SSH::Perl).
The power of perl is cpan, and cpanminus gives you the ability to install whatever you need even if you don't have permission to install to the system-wide libraries.
Read the module documentation for the full details.