Creating Secure File Upload/Download sites using UBUNTU Server

Use the following guide to create a secure file transfer site.

1. Install Ubuntu Server with SSH and LAMP enabled. Be sure to encrypt the whole hard drive.

2. (Optional) Install SFTP so users can use SFTP to transfer files.

3. Configure a Apache2 web server with SSH.

4. Edit php.ini file (/etc/php5/apache2) to increase the file upload maximum.

    1. upload_max_filesize – The maximum size of an uploaded file.
    2. post_max_size – Sets max size of post data allowed. This setting also affects file upload. To upload large files, this value must be larger than upload_max_filesize. If memory limit is enabled by your configure script, memory_limit also affects file uploading. Generally speaking, memory_limit should be larger than post_max_size.

5. Install phpmyadmin by typing sudo apt-get phpmyadmin.

6. Under /var/www folder create a folder called “files”. Give user permission to be able to write to the folder (chmod 777 files). Create index.html in the files folder. Index.html does not need to have anything particular. Just have some text in it.

7. Modify /etc/crontab file. Add the following line at the end of the crontab file. It will delete any file older than 7 days in the /var/www/files folder, but will not delete the index.html in the folder.

1 20 * * * root touch /var/www/files/index.html
1 21 * * * root find /var/www/files/ -mtime +7 -exec rm {} \;

8. Create a database using mysql.  Use the following SQL command to create a database. Grant user access to the database.

-- phpMyAdmin SQL Dump
-- version 4.0.10deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Dec 08, 2015 at 03:26 PM
-- Server version: 5.5.46-0ubuntu0.14.04.2
-- PHP Version: 5.5.9-1ubuntu4.14

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `FileUploader`
--

-- --------------------------------------------------------

--
-- Table structure for table `DownloadHistory`
--

CREATE TABLE IF NOT EXISTS `DownloadHistory` (
 `ID` int(11) NOT NULL AUTO_INCREMENT,
 `Date` text NOT NULL,
 `IPAddress` text NOT NULL,
 `FileName` text NOT NULL,
 PRIMARY KEY (`ID`),
 UNIQUE KEY `ID` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `FileLists`
--

CREATE TABLE IF NOT EXISTS `FileLists` (
 `ID` int(11) NOT NULL AUTO_INCREMENT,
 `FileCode` text NOT NULL,
 `FileName` text NOT NULL,
 `Expiration` text NOT NULL,
 `FileDate` text NOT NULL,
 `CryptFileName` text NOT NULL,
 PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

9. Place the following files in the /var/www folder.

custom.php   (for $c_userid and$c_password variable, use the echo crypt(“string value”,’xx’) to generate the value)

 
<?php
$c_userid = "xxGeneratedValue"; # Upload UserID
$c_password = "xxGeneratedValue"; # Upload Password
$forbidden_file_extension = array("php","html","htm");
$dbase_name = "FileUploader"; # mysql Database Name
$dbase_user = "FileUpload"; # mysql UserID
$dbase_pass = "password"; # mysql Password
?>

download.php

<?php

function Display_Upload()
 {
$HTMLDOCS = <<<HTML1
<html>
<body>
<form action="download.php" method="post"
enctype="multipart/form-data">
<h1><center>Secure File Download</center></h1>
<table align="center">
<tr><td>File Code: </td>
<td><input type="text" name="FileCode"> </td></tr>
<tr><td colspan="2"><input type="submit" name="submit" value="Download File"
/></td></tr>
</table>
</form>
</body>
</html>
HTML1;
print $HTMLDOCS;
}

function Check_Files($FileCode)
 {
 $FileCode = substr($FileCode,0,9);
if (preg_match ('/[0-9]+[0-9]+[0-9]+[0-9]+[0-9]+[0-9]+[0-9]+[0-9]+[0-9]/',$FileCode)==false)
 {
 echo "Wrong Code Entered. File Code is 9 digit number.";
exit;
 }
 include("custom.php");
 $con = mysql_connect("localhost",$dbase_user,$dbase_pass);
 if (!$con)
 {
 die ('Could not Connect: '. mysql_error());
 }
 mysql_select_db ($dbase_name,$con);
 $sql = "select * from FileLists where FileCode = ".$FileCode;
 $result = mysql_query($sql);
 $row=mysql_fetch_array($result);
 if (mysql_num_rows($result)==0)
 {
 echo "Wrong Code Entered. Please go back and enter the correct File Code.";
 exit;
 }
 if (!file_exists("files/".$row['CryptFileName']))
 {
 echo "The requested file has expired. The file you requested is not available for download anymore.";
 exit;
 }
 }

function Write_Log($FileCode)
 {
 include ("custom.php");
 $con = mysql_connect("localhost",$dbase_user,$dbase_pass);
 if (!$con)
 {
 die ('Could not Connect: '. mysql_error());
 }
 mysql_select_db ($dbase_name,$con);
 $sql = "select * from FileLists where FileCode = ".$FileCode;
 $result = mysql_query($sql);
 $row=mysql_fetch_array($result);
 $FileDate = date ("Y-m-d H:i:s");
 $FileName =$row['FileName'];
 $IPAddress = $_SERVER['REMOTE_ADDR'];
 $sql = "INSERT INTO DownloadHistory (Date,IPAddress,FileName) VALUES('";
 $sql = $sql . $FileDate."','".$IPAddress."','".$FileName."')";
 $result = mysql_query($sql);
 }

function Download_File($FileCode)
 {
 include ("custom.php");
 $con = mysql_connect("localhost",$dbase_user,$dbase_pass);
 if (!$con)
 {
 die ('Could not Connect: '. mysql_error());
 }
 mysql_select_db ($dbase_name,$con);
 $sql = "select * from FileLists where FileCode = ".$FileCode;
 $result = mysql_query($sql);
 while ($row=mysql_fetch_array($result))
 {
// Headers to send your file
 header("Content-Type: application/jpeg");
 header("Content-Disposition: attachment; filename = ". $row['FileName']);
 readfile("files/".$row['CryptFileName']);
 exit;
 }
 }

// Main Program
include ("custom.php");
$success =0;
if (!isset($_POST["FileCode"]))
 {
 Display_Upload();
 } else
 {
 Check_Files($_POST["FileCode"]);
 Write_Log($_POST["FileCode"]);
 Download_File($_POST["FileCode"]);
}

?>


upload.php

<?php

function Display_Upload()
 {

$HTMLDOCS = <<<HTML1

<html>
<body>

<form action= "upload.php" method="post" enctype="multipart/form-data">
<h1><center>IHS Secure File Upload</center></h1>
<table align="center">
<tr><td>Userid: </td>
<td><input type="text" name="userid"> </td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password"></td></tr>

<tr><td>Filename:</td><td>
<input type="file" name="file" id="file" /> </td></tr>

<tr><td colspan="2"><input type="submit" name="submit" value="Upload File"/></td></tr>
</table>
</form>

</body>
</html>
HTML1;

print $HTMLDOCS;
}



// Check to see if the files are ok to be uploaded.
function CheckFile()
 {
 include ("custom.php");
 $ReturnValue = 0;
 if (file_exists("files/" . $_FILES["file"]["name"]))
 {
 $ReturnValue = 1;
 }
 // File Extension Check.
 $pieces = explode (".",$_FILES["file"]["name"]);
 $extension = $pieces[count($pieces)-1];
 // echo "<h1>".$extension."</h1>";
 for ($i=0;$i<count($forbidden_file_extension);$i++)
 {
 if ($extension == $forbidden_file_extension[$i])
 {
 $ReturnValue = 2;
 }
 }
 Return $ReturnValue;
 }

function Upload_File()
 {
 global $success;
 $UploadOK = 0;
 if ($_FILES["file"]["error"] > 0)
 {
 echo "Return Code: " . $_FILES["file"]["error"] . "<br/>";
 }
 else
 {
// echo "Upload: " . $_FILES["file"]["name"] . "<br />";
// echo "Type: " . $_FILES["file"]["type"] . "<br />";
// echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br/>";
// echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br/>";
 $UploadOK = CheckFile();
 if ($UploadOK!= 0)
 {
 if ($UploadOK ==1)
 {
 echo "<h2>". $_FILES["file"]["name"] . " already exists.</h2> ";
 echo "<h2>Go back to <a href=\"index.php\">Main Screen</a>.</h2>";
 exit;
 }
 if ($UploadOK ==2)
 {
 $pieces = explode (".",$_FILES["file"]["name"]);
 $extension = $pieces[count($pieces)-1];
 echo "<h2>File Extension ".$extension." is forbidden.</h2>";
 echo "<h2>Go back to <a href=\"index.php\">Main Screen</a>.</h2>";
 exit;
 }
 }else
 {
 $new_FileName = crypt($_FILES["file"]["name"],'xx');
 $new_FileName = str_replace ("/",".",$new_FileName);
 move_uploaded_file($_FILES["file"]["tmp_name"], "files/" . $new_FileName);
 echo "Stored in: " . "files/" . $new_FileName."</br>";
 $success = 1;
 }
 }
 }

function Write_Description($success)
 {
 include ("custom.php");
 if ($success==1)
 {
 $con = mysql_connect("localhost",$dbase_user,$dbase_pass);
 if (!$con)
 {
 die ('Could not Connect: '. mysql_error());
 }
 mysql_select_db ($dbase_name,$con);
 $FileCode = strval(rand (100000000,999999999));
 $FileName = $_FILES["file"]["name"];
 $FileDate = date("Y-m-d");
 $ServerURL = "https:/"."/".$_SERVER['SERVER_NAME'];
 $new_FileName = crypt($_FILES["file"]["name"],'xx');
 $new_FileName = str_replace("/",".",$new_FileName);


 $sql = "INSERT INTO FileLists (FileCode,FileName,Expiration,FileDate,CryptFileName) VALUES('";
 $sql = $sql .$FileCode."','". $FileName."','1 Days','".$FileDate."','".$new_FileName."')";
// echo $sql;
 $result = mysql_query($sql);
 if ($result)
 {
 echo "<h1>File was uploaded successfully</h1>";
 echo "<h3>File Download instruction:</h3>";
 echo "<h4>Point your browser to <a href='".$ServerURL.":4040/download.php'>".$ServerURL.":4040/download.php</a></h4>";
 echo "<h4>Enter ".$FileCode." in the File Code area.</h4>";
 echo "<h4>The file will be available for download until ". date("Y-m-d",strtotime("+7 days")). " and will be deleted from the system.";
 } else
 {
 echo "Fail";
 }
 } else
 {
 echo "File Could not be uploaded... Please try again.";
 }

 }
// Main Program

include ("custom.php");

$success =0;
if (!isset($_POST["userid"]))
 {
 Display_Upload();
 } else
 {
 if ((crypt($_POST["userid"],'xx')==$c_userid) && (crypt($_POST["password"],'xx')==$c_password))
 {
 Upload_File();
 Write_Description ($success);
 } else
 {
 echo "Authentication Failed";
 }
 }

?>





Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s