Jump to content

[SOLVED] php escape backslashes


omonte7

Recommended Posts

I've tried and it isn't catching the backslashes, maybe I'm using it wrong.  I was reluctant to post my code, because it's rather long, but here's what I've got.  Look at the execute function, that's where I'm coding this part.

 

<?php

// function definition

function check_input($serverList, $command)
{
  //parse server list data
  $noEmptyServerList = '';
  $serverList = stripslashes($serverList);
  $serverList = htmlspecialchars($serverList);
  $serverList = trim($serverList);
  $parseServerInput = explode("\n", $serverList);
  foreach ($parseServerInput as $line){if (trim($line) != ''){$noEmptyServerList .= $line . "\n";}}
  $serverList = $noEmptyServerList;

  //parse command data
  $noEmptyCommandList = '';
  $command = stripslashes($command);
  $command = trim($command);
  $parseCommandInput = explode("\n", $command);
  if (strpos($command, "\n") == true){$mcommandError = "Commands must be separated by a ;, &&, or ||";}

  if (strlen($serverList) == 0) { $mlistError = "Please add a server(s) to the list";}
  if (strlen($command) == 0) { $mcommandError = "Please enter a command to execute";}
  if (!$mlistError == "" || !$mcommandError == ""){showForm($serverList, $command, $mlistError, $mcommandError);exit();}
  return compact('serverList', 'command');
}

function execute($serverList, $command)
{
  //put list of servers in a file to be called by command

  //parse command for proper formatting and pass to script for execution
  //escape quotes and back slashes
    //add slashes, isn't working for somereason...
    //$command = addslashes($command);

  $badChars = array('"', '$');
  $escapeBadChars = array('\"', '\$');
  $command = str_replace($badChars, $escapeBadChars, $command);

  //pass the command wrapped in quotes to the script that will run the job
    $command = "/var/www/html/command/test \"$command\"";
  //I can't figure out how to get a return code from a unix command, so I'm using a poorman's way, having my script output it's exit status to a file
  //execute command
    exec($command);
  //get result
    $exitStatus = file_get_contents('/var/www/html/command/.test.result');
    exec("rm -f /var/www/html/command/.test.result");
  displayResults($serverList, $command, $exitStatus);
}
function showForm($serverListData, $command, $listError, $commandError)
{
?>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <link rel="stylesheet" type="text/css" href="command.css" />
  <title>Command Center</title>
  </head>
  <body bgcolor="grey" color="blue">
  <h1 align="center">Command Center</h1>
  <hr>
  <form method="post" action="<?php echo $PHP_SELF;?>">
    <table class="bar" align="center"><tr>
      <th><input type="submit" name="execute" value="execute"/></th>
    </table>
  <hr>
  <table align="left">
    <tr>
      <?if (!$listError == "") { echo "<td colspan=\"1\" align=\"left\" style=\"color:red\">$listError</td><tr>";}?>
      <td colspan="1">Server(s) to run command on:</td>
    </tr>
    <tr>
      <td colspan="1">
        <textarea name="serverList" cols="18" rows="10"><?if (!$serverListData == "") { print $serverListData;}?></textarea>
      </td>
    </tr>
  </table>
  <table align="center">
    <tr>
      <?if (!$commandError == "") { echo "<td colspan=\"1\" align=\"center\" style=\"color:red\">$commandError</td><tr>";}?>
      <td colspan="1">Command to run:</td>
    </tr>
    <tr>
      <td colspan="1">
        <textarea name="command" cols="18" rows="10"><?if (!$command == "") { print $command;}?></textarea>
      </td>
    </tr>
  </table>
  </form>
  </body>
  </html>
<?
}

function verifyInput($serverList, $command)
{
  extract(check_input($serverList, $command));
  execute($serverList, $command);
}

function displayResults($serverList, $command, $exitStatus)
{
?>
  <html>
  <head>
  <link rel="stylesheet" type="text/css" href="command.css" />
  <title>Command Center</title>
  </head>
  <body bgcolor="grey" color="blue">
  <h1 align="center">Command Center</h1>
  <hr>
  <form method="post" action="<?php echo $PHP_SELF;?>">
    <table align="center"><tr>
    <th><input type="submit" name="return" value="Return"/></th>
    </table>
  <hr>
  <?echo "<h4 align=\"center\">Command:  $command</h4>";?>
  <tr><?echo "<h4 align=\"center\">Exit Status:  $exitStatus</h4>";?>
  <? echo "<td align=\"center\"><input type=\"submit\" name=\"viewLog\" value=\"View Log\"/></td><tr>";?>
  <table border="1" align="center">
    <tr><th>Servers</th>
    <th>Status</th></tr>
    <?
      $server = explode("\n", trim($serverList));
      foreach ($server as $host) {
        echo "<tr><td align=\"center\">" . trim($host) . "</td>";
        if ("$exitStatus" == 0) {
          echo "<td align=\"center\"><font color=\"green\">OK</font></td></tr>";
        } else {
          echo "<td align=\"center\"><font color=\"red\">Fail</font></td>";
          echo "<td align=\"center\"><input type=\"submit\" name=\"viewLog\" value=\"View Log\"/></td><tr>";
       }
      }
    ?>
  </table>
  </form>
  </body>
  </html>
<?
}

/*
  main
*/
  //variable declarations
  $serverListData == "";
  $command == "";
  $listError == "";
  $commandError == "";
  $command == "";
  $listError == "";
  $commandError == "";
  if(!isset($_POST["execute"])){showForm($serverListData, $command, $listError, $commandError);}
  if(isset($_POST["execute"])){verifyInput($_POST["serverList"], $_POST["command"]);}
  if(isset($_POST["return"])){header("location:index.php");}
  if(isset($_POST["viewLog"])){header("location:viewLog.php");}

?>

 

And here's the viewlog code

<html>
<head>
<link rel="stylesheet" type="text/css" href="command.css" />
<title>Command Center</title>
</head>
<body bgcolor="grey" color="blue">
<h1 align="center">Command Center Log</h1>
<hr>
  <form method="post" action="<?php echo $PHP_SELF;?>">
    <table class="bar" align="center"><tr>
    <th><input type="submit" name="return" value="Return"/></th>
    </table>
  <hr>
<?php
$log = "/var/www/html/command/log";
$fhLog = fopen("$log", "rb");
while (!feof($fhLog))
{
  $line = fgets($fhLog);
  echo "$line" . "<BR>";
}
fclose($fhLog);
?>
</body>
</html>
<? if ($_POST["return"]) { header("location:index.php"); } ?>

 

command.css contains this:

<style type="text/css">

 

body {color:blue;background-color:grey;}

 

h1 {

        color:blue;

        border-width: 0px 0px 0px 0px;

        border-spacing: 0px 0px 0px 0px;

}

 

input:hover {background-color:grey;color:blue;}

 

input.link {background-color:white;color:black;}

 

input.link:hover {background-color:grey;color:blue;}

 

table.bar {

        border-width: 0px 0px 0px 0px;

        border-spacing: px 0px 0px 0px;

        border-style: none none none none;

        border-color: black black black;

        border-collapse: separate;

        background-color: grey;

        color: blue;

}

table.bar th {

        border-width: 0px 0px 0px 0px;

        padding: 0px 0px 0px 0px;

        border-style: none none none none;

        border-color: black black black;

        background-color: grey;

        color: blue;

        -moz-border-radius: 0px 0px 0px 0px;

}

table.bar td {

        border-width: 0px 0px 0px 0px;

        padding: 0px 0px 0px 0px;

        border-style: none none none none;

        border-color: black black black;

        background-color: grey;

        color: blue;

        -moz-border-radius: 0px 0px 0px 0px;

}

</style>

 

 

AND the "test" script I run contains this:

#/bin/bash

! [ $# = 1 ] && exit 1

eval $1 &> /var/www/html/command/log

if [ $? = 0 ]; then

  printf 0 > /var/www/html/command/.test.result

  exit 0

else

  printf 1 > /var/www/html/command/.test.result

  exit 1

fi

 

 

Any help would be awesome!  Thanks.

 

Link to comment
Share on other sites

The script doesn't actually connect to a host to run it's command, I have no coded that part yet, so it will be run on the local host.  To test I was using this (in the "command to run" box):

 

ls somefile &>/dev/null && printf "result\nsuccessful" || printf "result\nfailed"

 

 

Link to comment
Share on other sites

lonewolf217 :

try $escapeBadChars = array('\\"', '\$');

 

I can escape the double quotes (") just fine.  It's the backslash (\) that I need to escape.  Something like:

 

//the below is a syntax error
  $badChars = array('"', '$', '\');  
  $escapeBadChars = array('\"', '\$', '\\');
/*or this, which isn't a syntax error, but doesn't escape the back slash, also if left alone it will esacpe the '\"' from above and result in '\\"', so I'm stuck and not sure where to go.*/
  $badChars = array('"', '$', "\\");  
  $escapeBadChars = array('\"', '\$', "\\\\");

$command = str_replace($badChars, $escapeBadChars, $command);

 

Link to comment
Share on other sites

I Fixed it.  The problem was not escaping the backslash in my $command, but rather "stripslashes" in my verifyInput function.  I only read the description of the stripslashes manual which states "Un-quotes a quoted string" and in wanting full control over user input I used this to remove any leading/trailing quotes (").  Well while debugging (echoing my $command in various places) I noticed that "stripslashes" actually does what it's name says and strips the slashes (imagine that!  Yes, I'm an idiot).  So, by the time my $command got down to the execute function (where I was trying to escape certain characters) the backslashes were not there for it to escape.  doh!  Thanks everyone for your help, I appreciate it.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.