Perl CGI Script backticks with root

410 Views Asked by At

I wanted to run a Perl CGI script with backticks.

EXAMPLE:

#!/usr/bin/perl -w

use warnings;
use strict;

use JSON;
use CGI;
use CGI::Carp 'fatalsToBrowser';

my $cgi = CGI->new;  

my $result = `lpc status all`;
print $cgi->header(-type => "plain/text", -charset => "utf-8"); 
print $result;  

The script runs without issue but returns an empty string.
When I use a command like ls it works perfectly.
My guess is that in this case the lpc command I need elevated privileges because when i just run the script from the bash as root it works fine.

The Question:
Is there a way to run such a script with backticks over Apache? Is there a Perl module that can help me achieve it otherwise?

The only solution that came to my mind would be to write a service programm that listens to TCP ports themselves but I didn't want to go down that route.

NEW TRY:
I have also tried making a bash script with the following content

#!/bin/bash
sudo lpc status all  

I edited /etc/sudoers to this

apache   ALL=(ALL)   NOPASSWD:/path/to/script/lpcsa.sh

and changed the perl script as followed

my  $result = qx(bash lpcsa.sh);

out of the command line it works now but over HTTP it just does not want to :/

1

There are 1 best solutions below

1
On BEST ANSWER

The key is to remember that the web server is running your program not you. When you run ls or lpc it works because you have /bin and /usr/sbin in your PATH. Run: which lpc ... when I do I get /usr/sbin/lpc which means that I need /usr/sbin in my PATH in order to run lpc without giving full path. Try adding the line:

print "\nPATH=" . $ENV{'PATH'};

to the end of your program. If the required directory is not present, one thing you could do is add:

$ENV{'PATH'} .= ":/usr/sbin";

or some such to your program before any system or back-tick calls