ACBobby Posted August 28, 2008 Share Posted August 28, 2008 I know there's a way to do this, but I'm just not quite sure how. Basically what I want to do is have a PHP script on my local machine running Apache (and obviously PHP as well) that when ran, I can have the option of opening programs from another location. Very handy if I'm at work and wish to launch something before I get home. I was just wondering if anyone knew exactly how to do this, and if there's any limitations. Quote Link to comment Share on other sites More sharing options...
digip Posted August 28, 2008 Share Posted August 28, 2008 I know there's a way to do this, but I'm just not quite sure how. Basically what I want to do is have a PHP script on my local machine running Apache (and obviously PHP as well) that when ran, I can have the option of opening programs from another location. Very handy if I'm at work and wish to launch something before I get home. I was just wondering if anyone knew exactly how to do this, and if there's any limitations. This has been discussed a few other thrads already now. few things to know. CLI programs run fine, as well as bat scripts(If windows) GUI programs will cause the script to hang and wait until the GUI app closes, so if anything needs to be done in the script after starting a GUI app, then it won't run until the GUI app is closed. Best way to get around this, multiple scripts. Eventually PHP will timeout the script, but the gui app should still be running. Use another script to close the app if needed. Windows example: <? system("drive:\Apppath\appname.exe"); //where it can be something like "c:\windows\sysem32\calc.exe" or any CLI commands ?> Linux requires user permissions set for the programs you want to launch. If you don't have the program in you path or permissions, they just won't run. http://hak5.org/forums/index.php?showtopic=9527 http://hak5.org/forums/index.php?showtopic=9618 Quote Link to comment Share on other sites More sharing options...
Steve8x Posted August 28, 2008 Share Posted August 28, 2008 digital pirate!! have you tried running an GUI exe from php with any of those commands like System() or exec()? At first I thought they weren't working and just making the php script hang! but actually, I took a look at my task manager and found a bunch of calc.exe's running!! (the program i was testing to run) I specified System("start d:\\windows\\system32\\calc.exe"); you need the double slashes because php is like c++ it uses a backslash as an escape character, so putting two results in 1... Why is php weird like that and not showing the GUI window of GUI programs? it runs indeed but it seems as if it doesn't just hide the window but somehow makes it never be created!! I tried unhiding the calculator window with Ghost(my window hider program from the coding section) and it doesn't find the window which leads me to believe it doesn't exist! So i've been trying to figure out a way to actually allow GUI programs to appear! Since you said batch scripts run fine, I thought of the idea of doing a fopen + fwrite and writing a string like this "start d:\\windows\\system32\\calc.exe" to a batch file named "execute.bat" or "execute.cmd" (.cmd is the same as .bat i think) neither worked! well it did run the calc.exe but the window was still not visible, and as far as i know non existant... also cmd.exe seems to run along with the program you made run, and it doesn't exit until you terminate calc.exe with the task manager... also the php script stops hanging and finishes once you end the process... When that didn't work I came up with a new idea... Create a simple program that reads a text file into a memory buffer, and does a shellexecute, executing the program which the path to was contained in the text file... the php script saves a text file with the path to the exe, (without the start) just the path, and then does a System("run.exe")... .data file db 'runinfo.txt',0 op db 'open',0 fhandle dd 0 buffer dd 0 bytesread dd 0 hInstance dd 0 .code start: invoke GetModuleHandle, 0 mov [hInstance], eax invoke CreateFile, addr file, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0 mov [fhandle], eax .if eax == INVALID_HANDLE_VALUE; file doesn't exist invoke ExitProcess, 0 .endif invoke VirtualAlloc, 0, 1000, MEM_COMMIT, PAGE_READWRITE mov [buffer], eax invoke ReadFile, [fhandle], [buffer], 1000, addr bytesread, 0 invoke CloseHandle, [fhandle] ;path to the exe to execute is now loaded into the memory buffer invoke ShellExecute, 0, addr op, [buffer], 0, 0, SW_SHOWNORMAL ;SW_SHOWNORMAL was my attempt at getting the window to show ;since the window doesn't ever exist it doesn't work! invoke ExitProcess, 0 end start Now im getting closer! the run.exe executes fine, reads the file, does the shellexecute, and calc.exe is running... still no window, but cmd.exe no longer runs, and the php script no longer hangs it returns immediately after run.exe terminates itself... Ive enumerated all windows with spy++ and an example app that comes with masm32 and the calculator window does not appear on the list!!! the enumerated windows list shows all windows hidden or visible, so php is somehow preventing windows from appearing! Why would they want to do that? I think I've thought of an alternative way, to get this to work! it involves not using any execute commands from php itself... since php isn't doing the executing im confident the windows will appear... i'll code it and post back in a short while! Quote Link to comment Share on other sites More sharing options...
Tenzer Posted August 28, 2008 Share Posted August 28, 2008 The reason why the programs are launching in the background is probably because the webserver is launched as a service on your computer. When it is launched as a service, it doesn't have any desktop attached to it, and hence don't have anywhere to launch the programs you are launching, except from in the background where the webserver is running. I believe that if you could run the webserver in the foreground it would work. Quote Link to comment Share on other sites More sharing options...
Steve8x Posted August 29, 2008 Share Posted August 29, 2008 OK, well i like running my apache as a service, so that's out of the question... But thanks for that info, I suspect that you probably are correct! I have found a way around this though! I was at first thinking to create a server app and a client app, and have you run the client app wherever you are and connect to the server to make it run a program, though that would require portforwarding, + the thread starter wanted to control what programs are executed on his server machine THROUGH PHP! So i've done just that! Heres how it works, you run this program your self NOT FROM PHP called "run.exe" from the same folder where a couple php files ive created go... create a new dir on your webserver folder called /remotecontrol/ or something similar but that no one will think of... The run.exe constantly runs on your machine, like httpd.exe... every 1 minute it reads from a file called "runinfo.txt" the first line contains a string number 1, or 0. The next line contains a path to the exe to execute, If the first line is a 1 it executes the file, and re-saves the file with the first line as a zero so that it doesn't keep running the program every minute... If its zero it does nothing... If you don't have a MYSQL database, I recommend getting one as its a nice thing to have! I couldn't imagine having a webserver without a database! My php script uses a database to store, names and paths to programs you want to execute, and you can easily add and remove from the list, with the web front! the ID field is used to delete from the list or execute a program simply type the id into the box and press delete from list or execute button... other fields are ignored for these two actions. The "Name" and "Path" fields are used to add to the list, you can see from the picture what to do! Make sure that paths include \\ double slashes, or no slashes will show up in the table below and it wont work if you try to execute it... The path is limited to MAX_PATH characters, which is 260... So make sure your programs have a path equal to or shorter than that. and thats about it! heres the source code to the Remote Execution Control Panel be sure to change the $username and $password variables at the top, you will use them to login! <?php include('config.php'); //Username and password protect this page! //so that only you can access it and run programs remotely on your machine! //change both and don't tell anyone! $username = "ACBobby"; $password = "ilikephp"; if(isset($_POST['auth'])) // you submitted your login info, so store it in a cookie { $user = $_POST['user']; $pass = $_POST['pword']; $logininfo = "$user-$pass"; setcookie("adminaccess", $logininfo, time()+1200); // 1200 = 20 minutes echo "<meta http-equiv='refresh' content='0;url=$Self'>"; } if(isset($_COOKIE['adminaccess'])) // every time you refresh the page the cookie's expire time will be extended 20 minutes { $logininfo = $_COOKIE['adminaccess']; setcookie("adminaccess", $logininfo, time()+1200); } echo "<html>"; echo "<head>"; echo "<title>Remote Code Execution Through PHP</title>"; echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"; echo "<center>"; //if no cookie is set, then show the login form if(!isset($_COOKIE['adminaccess'])) { echo "<h1> Admin Login: </h1>"; echo "<p><form method='post' action='$Self'>"; echo "<table border='2' cellspacing='2' cellpadding='0'><tr>"; echo "<td>Username: </td><td> <input name='user' type='text' id='user'> </td> </tr>"; echo "<td>Password: </td><td> <input name='pword' type='password' id='pword'></td></tr> </table>"; echo "<p> <input type='submit' name='auth' id='auth' value='Login'>"; echo "</form>"; die(); } else { //otherwise validate the username and password stored in the cookie! $logininfo = $_COOKIE['adminaccess']; list($usr, $pass) = split('-', $logininfo); //If you enter the wrong username or password you'll have to clear the cookie from your browser //its made that way as an annoyance to deter someone from attempting to guess // HOWEVER they shouldn't know about your page anyway... if($usr != $username) { die("<h1>INVALID CREDENTIALS!!!</h1>"); } if($pass != $password) { die("<h1>INVALID CREDENTIALS!!!</h1>"); } //everything is valid!! continue! if(isset($_POST['add'])) { if(isset($_POST['exename']) && isset($_POST['path'])) { //count number of entries + 1 $nextid = 0; $query = "SELECT * FROM exes"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { $nextid++; } $nextid++; $exe = $_POST['exename']; $path = $_POST['path']; $query = "INSERT INTO exes (id, name, path) VALUES ('$nextid', '$exe', '$path')"; mysql_query($query); echo "<b>Successfully added entry to the database!</b><p>"; } else { echo "<b>Insertion Failed! provide name + path!</b><p>"; } } if(isset($_POST['del'])) { if(isset($_POST['id'])) { $deletebyitemid = $_POST['id']; $query = "DELETE FROM exes WHERE id = $deletebyitemid"; mysql_query($query); //since were deleting an item update the id's after it to minus 1 $query = "UPDATE exes SET id = id - 1 WHERE id > $deletebyitemid"; mysql_query($query); echo "<b>Sucessfully removed entry!</b><p>"; } else { echo "<b>Failed to remove entry!</b><p>"; } } if(isset($_POST['exec'])) { if(isset($_POST['id'])) { $id = $_POST['id']; $query = "SELECT * FROM exes WHERE id = $id"; $result = mysql_query($query); $row = mysql_fetch_array($result); $path = $row[2]; $writestring = "1\r\n$path"; // '1' means run the program '\r\n' means newline $f = fopen("runinfo.txt", "wb"); fwrite($f, $writestring); fclose($f); echo "<b> Program Will Execute In Approximately 1 Minute!</b><p>"; } } echo "<h1> Remote Execution Control Panel </h1>"; echo "<form method='POST' action='$Self'>"; echo "<table border='0' cellpadding='0' cellspacing='4'>"; echo "<tr><td>ID</td><td><input type='text' name='id' size='5'></td></tr>"; echo "<tr><td>Name</td><td><input type='text' name='exename'></td></tr>"; echo "<tr><td>Path</td><td><input type='text' name='path' size='50'></td></tr>"; echo "</table><br><input type='submit' name='add' value='Add To List'> "; echo "<input type='submit' name='del' value='Delete From List'> "; echo "<input type='submit' name='exec' value='Execute!'> "; echo "</form>"; $query = "SELECT * FROM exes"; $result = mysql_query($query); echo "<table border='1' cellspacing='1' cellpadding='1'>"; echo "<tr><th>ID</th><th>Name</th><th>Path</th></tr>"; while($row = mysql_fetch_array($result)) { $id = $row[0]; $name = $row[1]; $path = $row[2]; echo "<tr><td>"; echo $id; echo "</td><td>"; echo $name; echo "</td><td>"; echo $path; echo "</td></tr>"; } } heres the config.php which you put in the same folder as the other php file and run.exe change the database info to match yours, don't worry about creating a database/schema & table as it does it for you <?php $dbhost = 'localhost:3306'; $dbuser = 'root'; $dbpass = 'ilikephp'; $dbname = 'RemoteExecute'; $Self = $_SERVER['PHP_SELF']; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); //Create a database to use if it does not exist yet! $query = "CREATE DATABASE IF NOT EXISTS RemoteExecute"; $result = mysql_query($query); mysql_select_db($dbname); //Create a table which will hold the name and path to the programs we want to execute $query = "CREATE TABLE IF NOT EXISTS exes(id INT NOT NULL, name VARCHAR(64) NOT NULL, path VARCHAR(260) NOT NULL, PRIMARY KEY(id))"; mysql_query($query); ?> run.exe source: ; ««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««««« .486 ; create 32 bit code .model flat, stdcall ; 32 bit memory model option casemap :none ; case sensitive include \masm32\include\windows.inc include \masm32\include\masm32.inc include \masm32\include\gdi32.inc include \masm32\include\user32.inc include \masm32\include\kernel32.inc include \masm32\include\Comctl32.inc include \masm32\include\comdlg32.inc include \masm32\include\shell32.inc include \masm32\include\oleaut32.inc include \masm32\include\msvcrt.inc includelib \masm32\lib\masm32.lib includelib \masm32\lib\gdi32.lib includelib \masm32\lib\user32.lib includelib \masm32\lib\kernel32.lib includelib \masm32\lib\Comctl32.lib includelib \masm32\lib\comdlg32.lib includelib \masm32\lib\shell32.lib includelib \masm32\lib\oleaut32.lib includelib \masm32\lib\msvcrt.lib CheckFile PROTO .data file db 'runinfo.txt',0 op db 'open',0 fhandle dd 0 buffer dd 0 bytesread dd 0 hInstance dd 0 .code start: invoke GetModuleHandle, 0 mov [hInstance], eax InfiniteLoop: call CheckFile invoke Sleep, 60000; sleep for 1 minute then check file again jmp InfiniteLoop CheckFile proc LOCAL byteswritten:DWORD invoke CreateFile, addr file, GENERIC_READ + GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0 mov [fhandle], eax .if eax == INVALID_HANDLE_VALUE; file doesn't exist ret .endif invoke VirtualAlloc, 0, 1000, MEM_COMMIT, PAGE_READWRITE mov [buffer], eax invoke ReadFile, [fhandle], [buffer], 1000, addr bytesread, 0 mov ecx, [buffer] cmp byte ptr [ecx], 31h; 31h = '1' formatted text jne exitfunc add ecx, 3; add 3 to get past the \r\n (newline) so ecx now points to the path string ;we know the file read had a '1' at the first byte so that means we want it to execute invoke ShellExecute, 0, addr op, ecx, 0, 0, SW_SHOWNORMAL mov eax, [buffer] mov byte ptr [eax], 30h; move '0' into the first byte of buffer! we will save over the file ;so we dont keep running the program every minute invoke SetFilePointer, [fhandle], 0, 0, FILE_BEGIN invoke WriteFile, [fhandle], [buffer], 1, addr byteswritten, 0 exitfunc: invoke VirtualFree, [buffer], 0, MEM_RELEASE invoke CloseHandle, [fhandle] ret CheckFile endp end start heres the ready made folder with the already compiled run.exe http://www.popeax.com/remoteexecute/remotecontrol.zip run.exe is only 2.5KB since I used asm ;) You can play around with my web front if you want but I disabled the saving of the text file and am not currently running run.exe so people wont be able to execute programs on my machine! http://www.popeax.com/remoteexecute/ So there you have it, a way to get around the limitation of php's execute functions whatever the reason may be... Although if your want to run an app that does a certain thing and terminates itself then using php's functions will work fine! but if your trying to get a GUI app to actually show up, this is a better option... :) Quote Link to comment Share on other sites More sharing options...
digip Posted August 29, 2008 Share Posted August 29, 2008 When I run it, the programs show up, but I am not running as a service. I manually start apache, but I don't see how that makes a difference on the GUI side. I thought anything in the system command was called as if it were from the cli. Never thought to use the \\ vs \ Mine show up though with the single slash, just the page doesn't execute any other commands until the gui app is closed. CLI apps and commands seem to work fine though and the script continues through the rest of the page without hanging. It's not pretty, but it works if you need it to do things for you remotely, although a VPN, RDP or VNC connection would probably be better suited for working remotely. It' snice to have something quick and easy though, like a shutdown script in PHP that you can turn your pc off when you want from a remote location or something, or have it attached to some X10 hardware and turn on your lights, etc. edit: I didn't see what your post above did, but just read it. I was going to suggest a post form to execute them right from the webpage, like an open command prompt. Nice job! Quote Link to comment Share on other sites More sharing options...
Steve8x Posted August 30, 2008 Share Posted August 30, 2008 well thanks digital pirate! Anyway today I was thinking about this, and there is something that I didn't like about the previous run.exe! It constantly reads from a text file every minute! Even though the text file is small and there's only 60 reads per hour, it still is extra wear and tear on your hard drive that will add up if running it for hours! Also it kinda sucks to have to wait 1 minute between commands... So I thought of a new idea! This time we will use our beloved sockets! I realized that php CAN use sockets to communicate with other socket apps! I upgraded my MASM32 to version 10 from 9(since a new version was released!) and redid the run.exe It now acts as a server instead of a file reader... You run the server "ExecuteServer.exe" and leave it running. It is now a console app. pressing CTRL + ALT + R will hide/unhide the console window so you dont have to look at it... I also now use WinExec, instead of ShellExecute, Since its more like typing into a command prompt(cmd.exe) than ShellExecute!! I liked your idea about being able to shutdown the computer from the php script! So that contributed to using WinExec as well... You can now execute commands in your system32 folder without providing the full path, WITH PARAMETERS TOO! observe from the image. Files from other paths than system32 can still be executed with params! as I have done so with ghost and it worked... It now also opens and closes your main CD-ROM drive just for fun lol! sending the server "cd -o\r\n" or "cd -c\r\n" opens or closes it... you send the server "exec $command\r\n" to get it to execute a command, its like having a shell to your machine from php :) you add commands and then you can execute them by specifying the id just like previously there is no longer any wait! no more text file, no more 1 minute wait time, its immediate! Since your php script and the server are running on the same machine, the php script connects to localhost! and as long as you don't open any holes in your firewall allowing incoming packets to your server machine on port 22008 it will not be accessible from anything except your password protected php script! ;) (4KB) ExecuteServer.asm: (assembles in MASM32 v10) ;Remote Execute Server 1.0 ;Coded by Steve8x ; ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤ ;standard includes file include \masm32\include\masm32rt.inc ;extra includes used include \masm32\include\wsock32.inc include \masm32\include\winmm.inc includelib \masm32\lib\wsock32.lib includelib \masm32\lib\winmm.lib ; ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤ comment * ----------------------------------------------------- Build this console app with "MAKEIT.BAT" on the PROJECT menu. ----------------------------------------------------- * clearbuffer PROTO windowhide PROTO .data? servsock SOCKET ? clientsock SOCKET ? sockaddr1 sockaddr_in <> sockaddr2 sockaddr_in <> WSockData WSADATA <> outputhandle dd ? tmp dd ? .data wndtitle db 'Remote Execute Server v1.0 - Steve8x',0 mci1 db 'set cdaudio door open',0 mci2 db 'set cdaudio door closed',0 mci3 db 0 buffer db 512 dup(0) .code start: ; ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤ invoke GetStdHandle, STD_OUTPUT_HANDLE mov [outputhandle], eax invoke SetConsoleTextAttribute, [outputhandle], BACKGROUND_RED + FOREGROUND_GREEN + FOREGROUND_INTENSITY cls print "Server Started...",13,10 invoke SetConsoleTitleA, addr wndtitle invoke CreateThread, 0, 0, addr windowhide, 0, 0, 0 call main exit ; ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤ main proc invoke WSAStartup, 0202h, addr WSockData invoke socket, PF_INET, SOCK_STREAM, 0 mov [servsock], eax xor eax, eax mov sockaddr1.sin_family, AF_INET mov sockaddr1.sin_addr, eax invoke htons, 22008 mov sockaddr1.sin_port, ax invoke bind, [servsock], addr sockaddr1, sizeof sockaddr_in .if eax == SOCKET_ERROR invoke OutputDebugString, SADD("SOCKET ERROR: could not bind socket") call WSACleanup xor eax, eax ret .endif invoke listen, [servsock], 1 cls print "Server Active...",13,10,13,10 next_connection: invoke closesocket, [clientsock] mov eax, sizeof sockaddr_in mov [tmp], eax invoke accept, [servsock], addr sockaddr2, addr tmp mov [clientsock], eax ;if it gets here a client is connected next_cmd: mov edi, offset buffer mov eax, sizeof buffer push edi call clearbuffer pop edi recvx: invoke recv, [clientsock], edi, 300, 0 or eax, eax jz next_connection cmp eax, SOCKET_ERROR je next_connection push edi add edi, eax mov al, [edi-1] pop edi cmp al, 10;0x0A/0Ah jne recvx cmp word ptr [edi], "dc";cd je cddrive cmp dword ptr [edi], "cexe";exec je executecmd invalidcommand: ;should never happen if your sending the commands from php correctly print "Client Sent Invalid Command!",13,10 invoke OutputDebugString, SADD("error") jmp next_connection cddrive: invoke SetConsoleTextAttribute, [outputhandle], FOREGROUND_GREEN + FOREGROUND_INTENSITY mov ax, [edi+3]; param in ax either "-o" or "-c" cmp ax, "o-" je opencdrom cmp ax, "c-" jne invalidcommand closecdrom: invoke mciSendString, addr mci2, addr mci3, 0, 0 print "Client Sent:",13,10 print edi,13,10 jmp next_connection opencdrom: invoke mciSendString, addr mci1, addr mci3, 0, 0 print "Client Sent:",13,10 print edi,13,10 jmp next_connection executecmd: invoke SetConsoleTextAttribute, [outputhandle], FOREGROUND_RED + FOREGROUND_INTENSITY invoke lstrlen, addr buffer xor ebx, ebx mov [edi+eax-2], bx;null out the \r\n at the end of the string add edi, 5;get past "exec " invoke WinExec, edi, SW_SHOWNORMAL sub edi, 5 print "Client Sent:",13,10 print edi,13,10,13,10 jmp next_connection shutdownserver: invoke closesocket, [servsock] invoke closesocket, [clientsock] call WSACleanup xor eax, eax ret main endp clearbuffer proc @@: xor edx, edx mov [edi], edx add edi, 4 mov ebx, [edi] test ebx, ebx jnz @b ret clearbuffer endp windowhide proc LOCAL showhide:DWORD LOCAL hWnd:DWORD invoke FindWindow, 0, addr wndtitle mov [hWnd], eax mov [showhide], 1 CheckKeys: invoke Sleep, 10 invoke GetKeyState, VK_CONTROL; CONTROL key and al, 80h cmp al, 0 jz CheckKeys invoke GetKeyState, VK_MENU; ALT key and al, 80h cmp al, 0 jz CheckKeys invoke GetKeyState, 52h; R key and al, 80h cmp al, 0 jz CheckKeys ; If all keys CTRL + ALT + R are simultaneously pressed the execution will reach here xor [showhide], 1 ; 1 = SW_SHOWNORMAL, 0 = SW_HIDE invoke ShowWindow, [hWnd], [showhide]; If showhide == 1 it will show the window, 0 it will hide it;) invoke Sleep, 250; so it wont hide/unhide really quickly, if you don't know what i mean try it without jmp CheckKeys windowhide endp ; ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤ end start new config.php <?php $dbhost = 'localhost:3306'; $dbuser = 'root'; $dbpass = 'mypassword'; $dbname = 'remoteexecute'; $Self = $_SERVER['PHP_SELF']; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); //Create a database to use if it does not exist yet! $query = "CREATE DATABASE IF NOT EXISTS remoteexecute"; $result = mysql_query($query); mysql_select_db($dbname); //Create a table which will hold the name and path to the programs we want to execute $query = "CREATE TABLE IF NOT EXISTS cmds(id INT NOT NULL, name VARCHAR(64) NOT NULL, command VARCHAR(260) NOT NULL, PRIMARY KEY(id))"; mysql_query($query); ?> new index.php (remote control panel) <?php include('config.php'); //Username and password protect this page! //so that only you can access it and run programs remotely on your machine! //change both and don't tell anyone! $username = "username"; $password = "password"; if(isset($_POST['auth'])) // you submitted your login info, so store it in a cookie { $user = $_POST['user']; $pass = $_POST['pword']; $logininfo = "$user-$pass"; setcookie("adminaccess", $logininfo, time()+1200); // 1200 = 20 minutes echo "<meta http-equiv='refresh' content='0;url=$Self'>"; } if(isset($_COOKIE['adminaccess'])) // every time you refresh the page the cookie's expire time will be extended 20 minutes { $logininfo = $_COOKIE['adminaccess']; setcookie("adminaccess", $logininfo, time()+1200); } echo "<html>"; echo "<head>"; echo "<title>Remote Code Execution Through PHP</title>"; echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">"; echo "<center>"; //if no cookie is set, then show the login form if(!isset($_COOKIE['adminaccess'])) { echo "<h1> Admin Login: </h1>"; echo "<p><form method='post' action='$Self'>"; echo "<table border='2' cellspacing='2' cellpadding='0'><tr>"; echo "<td>Username: </td><td> <input name='user' type='text' id='user'> </td> </tr>"; echo "<td>Password: </td><td> <input name='pword' type='password' id='pword'></td></tr> </table>"; echo "<p> <input type='submit' name='auth' id='auth' value='Login'>"; echo "</form>"; die(); } else { //otherwise validate the username and password stored in the cookie! $logininfo = $_COOKIE['adminaccess']; list($usr, $pass) = split('-', $logininfo); //If you enter the wrong username or password you'll have to clear the cookie from your browser //its made that way as an annoyance to deter someone from attempting to guess // HOWEVER they shouldn't know about your page anyway... if($usr != $username) { die("<h1>INVALID CREDENTIALS!!!</h1>"); } if($pass != $password) { die("<h1>INVALID CREDENTIALS!!!</h1>"); } //everything is valid!! continue! if(isset($_POST['add'])) { if(isset($_POST['cmdname']) && isset($_POST['command'])) { //count number of entries + 1 $nextid = 0; $query = "SELECT * FROM cmds"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { $nextid++; } $nextid++; $cmdname = $_POST['cmdname']; $cmd = $_POST['command']; $query = "INSERT INTO cmds (id, name, command) VALUES ('$nextid', '$cmdname', '$cmd')"; mysql_query($query); echo "<b>Successfully added entry to the database!</b><p>"; } else { echo "<b>Insertion Failed! provide name + path!</b><p>"; } } if(isset($_POST['del'])) { if(isset($_POST['id'])) { $deletebyitemid = $_POST['id']; $query = "DELETE FROM cmds WHERE id = $deletebyitemid"; mysql_query($query); if($deletebyitemid > 0) { //since were deleting an item update the id's after it to minus 1 $query = "UPDATE cmds SET id = id - 1 WHERE id > $deletebyitemid"; mysql_query($query); } echo "<b>Sucessfully removed entry!</b><p>"; } else { echo "<b>Failed to remove entry!</b><p>"; } } if(isset($_POST['exec'])) { if(isset($_POST['id'])) { $id = $_POST['id']; $query = "SELECT * FROM cmds WHERE id = $id"; $result = mysql_query($query); $row = mysql_fetch_array($result); $cmd = $row[2]; $writestring = "exec $cmd\r\n"; // sent to the server which does WinExec(like using cmd.exe) //port 22008 was picked by me, if you wanted to change this //you'd also have to change it on the server and re-assemble it! $sock = fsockopen("127.0.0.1", 22008, $error, $error2); if($sock) { fwrite($sock, $writestring); fclose($sock); echo "<b> Command Has Executed Sucessfully!</b><p>"; } else { echo "<b> ERROR #$error: $error2 </b><p>"; } } } if(isset($_POST['opencd'])) { $writestring = "cd -o\r\n"; // -o means open $sock = fsockopen("127.0.0.1", 22008, $error, $error2); if($sock) { fwrite($sock, $writestring); fclose($sock); echo "<b> Success! </b><p>"; } else { echo "<b> ERROR #$error: $error2 </b><p>"; } } if(isset($_POST['closecd'])) { $writestring = "cd -c\r\n"; // -c means close $sock = fsockopen("127.0.0.1", 22008, $error, $error2); if($sock) { fwrite($sock, $writestring); fclose($sock); echo "<b> Success! </b><p>"; } else { echo "<B> ERROR #$error: $error2 </b><p>"; } } echo "<h1> Remote Execution Control Panel 2.0 </h1>"; echo "<form method='POST' action='$Self'>"; echo "<table border='0' cellpadding='0' cellspacing='4'>"; echo "<tr><td>ID</td><td><input type='text' name='id' size='5'></td></tr>"; echo "<tr><td>Name</td><td><input type='text' name='cmdname'></td></tr>"; echo "<tr><td>Command</td><td><input type='text' name='command' size='50'></td></tr>"; echo "</table><br><input type='submit' name='add' value='Add To List'> "; echo "<input type='submit' name='del' value='Delete From List'> "; echo "<input type='submit' name='exec' value='Execute!'><p> "; echo "<input type='submit' name='opencd' value='Open CDROM!'> <input type='submit' name='closecd' value='Close CDROM!'>"; echo "</form><p>"; $query = "SELECT * FROM cmds"; $result = mysql_query($query); echo "<table border='1' cellspacing='1' cellpadding='1'>"; echo "<tr><th>ID</th><th>Name</th><th>Command</th></tr>"; while($row = mysql_fetch_array($result)) { $id = $row[0]; $name = $row[1]; $cmd = $row[2]; echo "<tr><td>"; echo $id; echo "</td><td>"; echo $name; echo "</td><td>"; echo $cmd; echo "</td></tr>"; } } ExecuteServer source code + binary! you can run it from anywhere unlike before, place the folder somewhere in your masm32 directory if wanting to modify and re-assemble it! http://popeax.com/remoteexecute/ExecuteServer.zip remotecontrol2 php files http://popeax.com/remoteexecute/remotecontrol2.zip and thats about it! let me know if you can think of any more improvements that could be done! Quote Link to comment Share on other sites More sharing options...
digip Posted August 30, 2008 Share Posted August 30, 2008 let me know if you can think of any more improvements that could be done! Can you add the kitchen sink? Seriously, this is pretty awesome for a windows machine. Now we just need a *nix equivalent. This should be covered in an episode too. Really handy for controlling your machine or network direclty from the web. Quote Link to comment Share on other sites More sharing options...
iisonly Posted August 30, 2008 Share Posted August 30, 2008 let me know if you can think of any more improvements that could be done! Firstly - cool code Secondly : I don't know how many of you use or have used Jabber (GTalk for example) Next version could also include a bot :) (no need to port forward, simply type your commands into chat program) A little jabber.PHP class is located at code.google.com/p/xmpphp/ Tried messing with it at worked fine on windows and ubuntu (i did a little "group-chat" bot:), commands for listing files in directories, "df -h" for seeing freespace, etc) Quote Link to comment Share on other sites More sharing options...
Gaznox Posted December 15, 2008 Share Posted December 15, 2008 Wow, thank you Steve8x! You wont believe how long I have been looking for the solution to this problem. Quote Link to comment Share on other sites More sharing options...
ubersjaak Posted June 15, 2010 Share Posted June 15, 2010 Hi all, Awesome code! :D I've tried it out for a while now (even before i became a member). I even tried to make the program into a service. Succeeded in most part of it but unfortunately it only opens and closes the tray. If i try to execute anything else it gives me a message saying "A program running on this cumputer it trying to show a message". I'd really like to use CLamp with it but I don't want to have the command window shown on my desktop. I've also tried traying it with trayIt but that makes my cmd prompts tray as well. Any suggestions Grz Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.