I'm not an experienced Linux user and I wanted an easy way to run shell scripts as root from a PHP script, I came up with this:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
int main(int argc, char *argv[])
{
if (access(argv[1], F_OK) != -1)
{
struct stat filestat;
if (stat(argv[1], &filestat) == 0)
{
if ((filestat.st_uid == 0) && (filestat.st_gid == 0) && (filestat.st_mode & S_IXUSR) && (!(filestat.st_mode & S_IWOTH)))
{
char* match = strrchr(argv[1], '.');
if ((match != NULL) && (strcasecmp(match, ".sh") == 0))
{
if (setuid(0) != -1)
{
execl("/usr/bin/sudo", "/usr/bin/sudo", argv[1], (char*) NULL);
return 0;
}
}
}
}
}
return 1;
}
Any potential security issues with this? If so how can I improve it?
Example Usage:
Lets say I have a script located at:
/some/path/script.sh
With the following in it:
#!/bin/bash
echo $USER
Now lets say I compile the above C code to a binary and place it at:
/some/path/run-as
and do:
chown root:root /some/path/run-as
chmod 6755 /some/path/run-as
Now I run this PHP script owned by www-data (via browser / local apache web server):
<?php
echo exec('/some/path/run-as /some/path/script.sh');
?>
I expect the script to output 'root' when ran.