0

I am having some trouble with a PHP script. I am trying to do two things:

  1. Create an XML file in /usr/local/ezreplay/data/XML/ directory and add contents to it using inputs passed to it from a HTML form;

  2. Upload a PCAP file which is included in the submitted HTML form.

Here is my PHP (apologies it is a little long but I believe all of it is relevant here):

<?php

// Check if the 'expirydate' input is set
if (isset($_POST['expirydate'])) {

  // Convert the input string to a timestamp using 'strtotime'
  $timestamp = strtotime($_POST['expirydate']);

  // Format the timestamp as a 'mm/dd/yyyy' string using 'date'
  $expirydate = date('m/d/Y', $timestamp);
}

// Check if all required POST variables are set
if ( isset($_POST['destinationip']) && isset($_POST['destinationport']) && isset($expirydate) && isset($_POST['multiplier']) && isset($_POST['pcap']) ) {

    // Set the path for the XML file
    $path = '/usr/local/ezreplay/data/XML/' . trim($_POST['destinationip']) . ':' . trim($_POST['destinationport']) . ':' . $expirydate . ':' . trim($_POST['multiplier']) . ':' . trim($_POST['pcap']) . '.xml';

    // Initialize the contents of the XML file
    $contents = "";

    // Open the XML file in append mode
    if ( $fh = fopen($path,"a+") ) {

        // Add the opening 'config' tag to the XML file
        $contents .= '<config>';

        // If the 'destinationip' and 'destinationport' POST variables are not empty, add a 'destination' tag to the XML file
        if ( trim( $_POST['destinationip'] ) != "" && trim( $_POST['destinationport'] ) != "" ) {
            $contents .= "\n" . '<destination>' . $_POST['destinationip'] . ':' . $_POST['destinationport'] . '</destination>';
        }

        // If the 'multiplier' POST variable is not empty, add a 'multiplier' tag to the XML file
        if ( trim( $_POST['multiplier'] ) != "" ) {
            $contents .= "\n" . '<multiplier>' . $_POST['multiplier'] . '</multiplier>';
        }

        // If the 'pcap' POST variable is not empty, add a 'pcap' tag to the XML file
        if ( trim( $_POST['pcap'] ) != "" ) {
            $contents .= "\n" . '<pcap>/usr/local/ezreplay/data/PCAP/' . $_POST['pcap'] . '</pcap>';

            // Add default tags to XML config file to ensure the pcap does not fail and loops continuously until expiration date hits
            $contents .= "\n" . '<loop>0</loop>';
            $contents .= "\n" . '<nofail>true</nofail>';
        }

        // Add the closing 'config' tag to the XML file
        $contents .= "\n" . '</config>';

        // Write the contents to the file
        if ( fwrite( $fh, $contents ) ) {
            // Success
        } else {
            echo "The XML config could not be created";
        }

        // Close the file
        fclose($fh);
    }
}

// Set the target directory and file name
$target_dir = "/usr/local/ezreplay/data/PCAP/";
$basename = basename($_FILES["pcap"]["name"]);
$target_file = $target_dir . $basename;

// Check if the file has a pcap extension
$allowedExtensions = array('pcap');
$basenameWithoutExt = null;
foreach ($allowedExtensions as $allowedExtension) {
    if (preg_match('#\\.' . $allowedExtension . '$#',$basename)) {
        $basenameWithoutExt = substr($basename,0,-1 - strlen($allowedExtension));
        break;
    }
}

// Accept only .pcap files
if (is_null($basenameWithoutExt)) {
    echo "Sorry, only .pcap files are allowed. Please try creating your Packet Replay again using a .pcap file.";
    exit;
}

// Check if the file already exists
if (file_exists($target_file)) {
    echo "The Packet Replay could not be started, the PCAP is already running.";
    exit;
}

// Try to upload the file
if (move_uploaded_file($_FILES["pcap"]["tmp_name"], $target_file)) {
    // Success
} else {
    echo "Sorry, there was an error uploading your file.";
    exit;
}

// Start the Packet Replay
$command = '/usr/local/ezreplay/bin/startreplay.sh ' . $path;
system($command);

echo "The Packet Replay has been started.";

?>

Now the file upload is working and I can see the final echo message being returned in my browser however the XML file is never created. I have changed the directory ownership to the apache user and even chmod 777 to eliminate any permissions issues but it still doesn't create the file.

Any ideas why this is not working? The PHP and apache error logs don't show any issues and as I mentioned the script seems to be working to a degree as the file upload takes place perfectly.

Thanks!

Rolando Isidoro
  • 4,983
  • 2
  • 31
  • 43
divad
  • 7
  • 4
  • 2
    Try to create a simple file using `file_put_contents($file, $data);` – executable Dec 22 '22 at 15:13
  • @executable Looks like that worked okay: `/usr/bin/php-cgi test.php X-Powered-By: PHP/7.2.24 Content-type: text/html; charset=UTF-8 XML file successfully created!` I guess the issue must be with the inputs passed from the HTML form perhaps? – divad Dec 22 '22 at 15:19
  • How it this related to HTML ? – executable Dec 22 '22 at 15:20
  • The PHP script creates an XML file based on inputs from a HTML form. When the form is submitted it passes the inputs to this script. – divad Dec 22 '22 at 15:22
  • Maybe try throwing an `else` on `if ( $fh = fopen($path,"a+") ) {` to see if that's failing – Chris Haas Dec 22 '22 at 15:26
  • @ChrisHaas I added an else at the bottom of the `fopen` and tested again but I still have the same issue and only get the success echo message in the browser: `// Close the file fclose($fh); } else { // If the file could not be opened, print an error message echo "Error: Could not open file for writing."; } }` – divad Dec 22 '22 at 15:58
  • Try an else statement on that main 'Check if all required POST variables are set' IF statement. If you can't use a debugger to step thru the code execution, consider temporarily adding lines to write a log file or perhaps `echo` messages so you can find out what is going on. – S. Imp Dec 22 '22 at 17:18
  • I have tried running the code in sections and it seems to have an issue creating the XML file and naming it using the variables – divad Dec 22 '22 at 18:24
  • @divad Do not write XML files by hand, this can result in invalid XML files when not done correctly. Use existing libraries like simplexml or DOM to create the XML file you want. – Progman Dec 23 '22 at 17:18

2 Answers2

0

I think the file is not being created due to "/" in the filename. As mentioned at Allowed characters in filename

Atif
  • 75
  • 5
-1

I managed to fix this with the following edits.

<?php

// Set the target directory and file name
$target_dir = "/usr/local/ezreplay/data/PCAP/";
$basename = basename($_FILES["pcap"]["name"]);
$target_file = $target_dir . $basename;

// Check if the file has a pcap extension
$allowedExtensions = array('pcap');
$basenameWithoutExt = null;
foreach ($allowedExtensions as $allowedExtension) {
    if (preg_match('#\\.' . $allowedExtension . '$#',$basename)) {
        $basenameWithoutExt = substr($basename,0,-1 - strlen($allowedExtension));
        break;
    }
}

// Accept only .pcap files
if (is_null($basenameWithoutExt)) {
    echo "Sorry, only .pcap files are allowed. Please try creating your Packet Replay again using a .pcap file.";
    exit;
}

// Check if the file already exists
if (file_exists($target_file)) {
    echo "The Packet Replay could not be started, the PCAP is already running.";
    exit;
}

// Try to upload the file
if (move_uploaded_file($_FILES["pcap"]["tmp_name"], $target_file)) {
    //Success
} else {
    echo "Sorry, there was an error uploading your file.";
    exit;
}

// Check if the 'expirydate' input is set
if (isset($_POST['expirydate'])) {
  // Convert the input string to a timestamp using 'strtotime'
  $timestamp = strtotime($_POST['expirydate']);
  // Format the timestamp as a 'mm-dd-yyyy' string using 'date'
  $expirydate = date('m-d-Y', $timestamp);
}

// Check if 'destinationip', 'destinationport', 'multiplier' and 'pcap' required POST variables are set
if (isset($_POST['destinationip']) && isset($_POST['destinationport']) && isset($_POST['multiplier'])) {

  // Set the filename and path for the XML file
  $file = '/usr/local/ezreplay/data/XML/' . trim($_POST['destinationip']) . ':' . trim($_POST['destinationport']) . ':' . trim($_POST['multiplier'])  . ':' . $expirydate . ':' . $_FILES["pcap"]["name"] . '.xml';

  // Initialize the contents of the XML file
  $contents = "";

  // Add the opening 'config' tag to the XML file
  $contents .= '<config>';

  // If the 'destinationip' and 'destinationport' POST variables are not empty, add a 'destination' tag to the XML file
  if (trim($_POST['destinationip']) != "" && trim($_POST['destinationport']) != "") {
    $contents .= "\n" . '<destination>' . $_POST['destinationip'] . ':' . $_POST['destinationport'] . '</destination>';
  }

  // If the 'multiplier' POST variable is not empty, add a 'multiplier' tag to the XML file
  if (trim($_POST['multiplier']) != "") {
    $contents .= "\n" . '<multiplier>' . $_POST['multiplier'] . '</multiplier>';
  }

  // If the 'pcap' POST variable is not empty, add a 'pcap' tag to the XML file
  if (trim($_FILES["pcap"]["name"]) != "") {
    $contents .= "\n" . '<pcap>/usr/local/ezreplay/data/PCAP/' . $_FILES["pcap"]["name"] . '</pcap>';
  }

  // Add default tags to XML config file to ensure the pcap does not fail and loops continuously until expiration date hits
  $contents .= "\n" . '<loop>0</loop>';
  $contents .= "\n" . '<nofail>true</nofail>';

  // Add the closing 'config' tag to the XML file
  $contents .= "\n" . '</config>';

  // Write the contents to the file
  if (file_put_contents($file, $contents)) {
    // Success
  } else {
    echo "The XML config could not be created";
  }
}

// Start the Packet Replay
$command = '/usr/local/ezreplay/bin/startreplay.sh ' . $path;
system($command);

echo "The Packet Replay has been started.";

?>
divad
  • 7
  • 4
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 25 '22 at 09:56