setup.php now deletes itself when finished. Some code cleanup

This commit is contained in:
Andrew S. Rightenburg 2023-04-24 13:12:41 -04:00
parent c83f5786a4
commit 4a8d1d1f3a
Signed by: rail5
GPG key ID: A0CB570AB6629159
8 changed files with 206 additions and 196 deletions

View file

@ -26,23 +26,23 @@ Simple, Self-Hosted, PHP File Sharing
It's recommended that you alter your server configuration to block direct access to the sqlite database file (created by **setup.php** as **filedb.sqlite**), and to block direct access to the *files directory*, as such for example:
```
location = /SimpleFS/Installation/Folder/filedb.sqlite {
deny all;
return 404;
}
location = /SimpleFS/Installation/Folder/files/ {
deny all;
return 404;
}
location = /SimpleFS/Installation/Folder/filedb.sqlite {
deny all;
return 404;
}
location = /SimpleFS/Installation/Folder/files/ {
deny all;
return 404;
}
```
- For Apache Users
This repo includes .htaccess files preventing direct access to the sqlite database file and to the files directory. Please ensure that your Apache installation is configured to allow .htaccess overrides, as in for instance, in your **apache2.conf**:
```
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
```

View file

@ -4,46 +4,43 @@ require('config.global.php');
require('functions.global.php');
require('layout.php');
$notRealFile = 0;
if (!isset($_GET['id'])) {
header('location: index.php'); // user loaded without requesting file by id
header('location: index.php'); // user loaded without requesting file by id
die();
}
if (!is_numeric($_GET['id'])) {
header('location: index.php'); // user requested non-numeric (invalid) file id, damned fuzzers
header('location: index.php'); // user requested non-numeric (invalid) file id, damned fuzzers
die();
}
$reqFile = $_GET['id'];
$fetched = contactDB("SELECT * FROM files WHERE fileid='$reqFile';", 1);
if (count($fetched) == 0) {
$notRealFile = 1; // user requested invalid (unmatched) file id, possibly a deleted file
}
$realFile = (count($fetched) != 0); // Set realFile to true if we found the file id, false if we didn't find it
if ($notRealFile == 1) {
echo deliverTop("SimpleFS - Download");
if (!$realFile) {
echo deliverTop("SimpleFS - Download");
echo deliverMiddle("File Not Found", "The file you requested doesn't exist on this server", "");
echo deliverBottom();
echo deliverMiddle("File Not Found", "The file you requested doesn't exist on this server", "");
echo deliverBottom();
} else {
$fileName = str_replace("files/", "", $fetched[0]);
if ($_GET['dl'] == "true") {
$fileName = str_replace("files/", "", $fetched[0]);
if ($_GET['dl'] == "true") {
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" .$fileName. "\"");
readfile($fetched[0]);
} else {
echo deliverTop("SimpleFS - Download");
echo deliverMiddle("Download", $fileName, '<a href="download.php?id='.$_GET['id'].'&dl=true"><i class="fa fa-download fa-5x"></i></a>');
echo deliverBottom();
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" .$fileName. "\"");
readfile($fetched[0]);
} else {
echo deliverTop("SimpleFS - Download");
echo deliverMiddle("Download", $fileName, '<a href="download.php?id='.$_GET['id'].'&dl=true"><i class="fa fa-download fa-5x"></i></a>');
echo deliverBottom();
}
}
}

View file

@ -3,26 +3,27 @@
/* General Global Include Functions Here */
function contactDB($query, $column) {
// $query: the SQLite query to the database
// $column: the column you're asking the DB to report back on
// 1: fileid
// 2: filepath
// 3: fileowner
// ie, $result = contactDB("SELECT * FROM files WHERE fileowner='admin';", 2);
// populates the $result[] array with the file paths to every file owned by the admin user
$dbresult = array();
$datab = 'sqlite:./filedb.sqlite';
$dbpdo = new PDO($datab) or die ("Fatal Error: Can't open the database");
foreach ($dbpdo->query($query) as $row) {
array_push($dbresult, $row[$column]);
// $query: the SQLite query to the database
// $column: the column you're asking the DB to report back on
// 1: fileid
// 2: filepath
// 3: fileowner
// 4: filedate
// ie, $result = contactDB("SELECT * FROM files WHERE fileowner='admin';", 2);
// populates the $result[] array with the file paths to every file owned by the admin user
$dbresult = array();
$datab = 'sqlite:./filedb.sqlite';
$dbpdo = new PDO($datab) or die ("Fatal Error: Can't open the database");
foreach ($dbpdo->query($query) as $row) {
array_push($dbresult, $row[$column]);
}
$dbpdo = NULL; // Closing connection
return $dbresult;
$dbpdo = NULL; // Closing connection
return $dbresult;
}
?>

View file

@ -8,7 +8,7 @@ session_start();
function deliverTop($pagetitle) {
$top = '<!DOCTYPE HTML>
$top = '<!DOCTYPE HTML>
<!--
Identity by HTML5 UP
html5up.net | @ajlkn
@ -26,12 +26,12 @@ function deliverTop($pagetitle) {
';
return $top;
return $top;
}
function deliverMiddle($toptext, $bottomtext, $buttons) {
$middle = '<!-- Wrapper -->
$middle = '<!-- Wrapper -->
<div id="wrapper">
<!-- Main -->
@ -55,8 +55,8 @@ function deliverMiddle($toptext, $bottomtext, $buttons) {
}
function deliverBottom() {
$bottom = '<!-- Footer -->
$bottom = '<!-- Footer -->
<footer id="footer">
</footer>
@ -73,7 +73,7 @@ function deliverBottom() {
</body>
</html>';
return $bottom;
return $bottom;
}
?>

View file

@ -4,34 +4,34 @@ require('config.global.php');
require('layout.php');
if ($_POST['submitted'] == true) {
if ($_POST['username'] == $adminuser) {
if (password_verify($_POST['password'], $adminpass)) {
$_SESSION['simplefsvalid'] = true;
$_SESSION['simplefsuser'] = "admin";
// signed in, redirect
header('location: manage.php');
} else {
$_SESSION['simplefsvalid'] = false;
$_SESSION['simplefsuser'] = NULL;
die('Invalid username or password');
if ($_POST['username'] == $adminuser) {
if (password_verify($_POST['password'], $adminpass)) {
$_SESSION['simplefsvalid'] = true;
$_SESSION['simplefsuser'] = "admin";
// signed in, redirect
header('location: manage.php');
} else {
$_SESSION['simplefsvalid'] = false;
$_SESSION['simplefsuser'] = NULL;
die('Invalid username or password');
}
} else if ($_POST['username'] == $secuser) {
if (password_verify($_POST['password'], $secpass)) {
$_SESSION['simplefsvalid'] = true;
$_SESSION['simplefsuser'] = "guest";
// signed in, redirect
header('location: manage.php');
} else {
$_SESSION['simplefsvalid'] = false;
$_SESSION['simplefsuser'] = NULL;
die('Invalid username or password');
}
} else {
$_SESSION['simplefsvalid'] = false;
$_SESSION['simplefsuser'] = NULL;
die('Invalid username or password');
}
}
} else if ($_POST['username'] == $secuser) {
if (password_verify($_POST['password'], $secpass)) {
$_SESSION['simplefsvalid'] = true;
$_SESSION['simplefsuser'] = "guest";
// signed in, redirect
header('location: manage.php');
} else {
$_SESSION['simplefsvalid'] = false;
$_SESSION['simplefsuser'] = NULL;
die('Invalid username or password');
}
} else {
$_SESSION['simplefsvalid'] = false;
$_SESSION['simplefsuser'] = NULL;
die('Invalid username or password');
}
}
echo deliverTop("SimpleFS - Sign in");

View file

@ -5,8 +5,8 @@ require('layout.php');
require('functions.global.php');
if ($_SESSION['simplefsvalid'] != true) {
header('location: login.php');
die();
header('location: login.php');
die();
}
$currentUser = $_SESSION['simplefsuser'];
@ -23,17 +23,17 @@ $i = 0;
$outputContents = "";
if ($_POST['msubmitted'] == true) {
while ($i < $nFiles) {
if ($_POST["file$myFilesId[$i]"] == "marked") {
unlink($myFilesName[$i]); // Delete selected file
$dbChange = contactDB("DELETE FROM files WHERE fileid='$myFilesId[$i]';", 0); // Update database
}
$i = $i + 1;
}
$i = 0; // Reset iteration for next use
$noticeText = "<div align='center'><h1>Files successfully deleted</h1></div><br>".PHP_EOL;
while ($i < $nFiles) {
if ($_POST["file$myFilesId[$i]"] == "marked") {
unlink($myFilesName[$i]); // Delete selected file
$dbChange = contactDB("DELETE FROM files WHERE fileid='$myFilesId[$i]';", 0); // Update database
}
$i = $i + 1;
}
$i = 0; // Reset iteration for next use
$noticeText = "<div align='center'><h1>Files successfully deleted</h1></div><br>".PHP_EOL;
}
unset($myFilesId);
@ -45,19 +45,19 @@ $myFilesName = contactDB("SELECT * FROM files where fileowner='$currentUser';",
$nFiles = count($myFilesId);
if ($nFiles == 0) {
$outputContents = "You haven't uploaded any files yet";
$outputContents = "You haven't uploaded any files yet";
} else {
while ($i < $nFiles) {
$fileName = str_replace("files/", "", $myFilesName[$i]);
$outputContents = $outputContents.'<div class="field"> <input type="checkbox" name="file'.$myFilesId[$i].'" id="file'.$myFilesId[$i].'" value="marked"><label for="file'.$myFilesId[$i].'"><a href="download.php?id='.$myFilesId[$i].'">'.$fileName.'</a></label></div>'.PHP_EOL;
$i = $i + 1;
}
while ($i < $nFiles) {
$fileName = str_replace("files/", "", $myFilesName[$i]);
$outputContents = $outputContents.'<div class="field"> <input type="checkbox" name="file'.$myFilesId[$i].'" id="file'.$myFilesId[$i].'" value="marked"><label for="file'.$myFilesId[$i].'"><a href="download.php?id='.$myFilesId[$i].'">'.$fileName.'</a></label></div>'.PHP_EOL;
$i = $i + 1;
}
}
echo deliverTop("SimpleFS - Manage");
if (isset($noticeText)) {
echo $noticeText;
echo $noticeText;
}
echo deliverMiddle("Manage", '<form action="manage.php" method="post">'.PHP_EOL.'<input type="hidden" name="msubmitted" id="msubmitted" value="true">'.PHP_EOL.$outputContents, '<button><i class="fa">Delete Selected Files</i></button></form><br><br><form action="index.php"><button><i class="fa">Return Home</i></button></form>');

142
setup.php
View file

@ -6,107 +6,119 @@
</head>
<body>
<?php
// Check that file uploads are enabled on the server
if (ini_get('file_uploads') != 1) {
echo '<div align="center"><h1><font color="FF0000">Warning: Your PHP configuration has disabled file uploads</font><h1><h3>Please check your <b><u>php.ini</u></b> for the line:</h3><i>file_uploads = On</i></div><br><br>';
}
// Check for SQLite and PDO
if (!extension_loaded("pdo_sqlite")) {
echo '<div align="center"><h1><font color="FF0000">Warning: You do not have the PHP SQLite extension installed.</font></h1><h3>Please install the PHP sqlite3 extension before moving forward</h3></div><br><br>';
echo '<div align="center"><h1><font color="FF0000">Warning: You do not have the PHP SQLite extension installed.</font></h1><h3>Please install the PHP sqlite3 extension before moving forward</h3></div><br><br>';
}
echo '<div align="center"><b><u>php.ini</u></b> specifies your server\'s <i>maximum upload filesize</i> as:<b> '.ini_get('upload_max_filesize').'</b></div><br>';
?>
<div align="center">
<h1>IMPORTANT:</h1>
<h2>Delete this file <i>immediately</i> after completing set-up</h2><br />
<form action="setup.php" method="post">
<input type="hidden" name="formsubmitted" id="formsubmitted" value="true">
<div align="center">
<h1>IMPORTANT:</h1>
<h2>Delete this file <i>immediately</i> after completing set-up</h2><br />
<form action="setup.php" method="post">
<input type="hidden" name="formsubmitted" id="formsubmitted" value="true">
Create admin <i>(uploader)</i> account
<br>
<br>
<input type="text" name="username" id="username" placeholder="Admin username" autofocus>
<br>
<br>
<input type="password" name="password" id="password" placeholder="Admin password">
<br>
<br>
<input type="checkbox" name="makeuser" id="makeuser" onchange="seconduser(this)"> Create a second user who can also upload stuff?
<div id="seconduser">
<input type="text" name="user2" id="user2" placeholder="Second username">
<br>
<input type="password" name="pass2" id="pass2" placeholder="Second password">
</div>
<div id="seconduser">
<input type="text" name="user2" id="user2" placeholder="Second username">
<br>
<input type="password" name="pass2" id="pass2" placeholder="Second password">
</div>
<script type="text/javascript">
var secform = document.getElementById("seconduser");
secform.style.display = "none";
function seconduser(checkE) {
if (checkE.checked) {
secform.style.display = "block";
} else {
secform.style.display = "none";
}
if (checkE.checked) {
secform.style.display = "block";
} else {
secform.style.display = "none";
}
}
</script>
<br>
<input type="submit">
</form>
</form>
<?php
require('functions.global.php');
if ($_POST['formsubmitted'] == "true") {
if (strlen($_POST['username']) < 3 || strlen($_POST['password']) < 3) {
die('Error: Use a username/password of at least 3 characters');
exit();
}
if ($_POST['makeuser'] == true) {
if (strlen($_POST['user2']) < 3 || strlen($_POST['pass2']) < 3) {
die('Error: Use a username/password of at least 3 characters');
exit();
}
if ($_POST['username'] == $_POST['user2']) {
die('Error: Usernames cannot be identical to each other');
exit();
}
}
if (strlen($_POST['username']) < 3 || strlen($_POST['password']) < 3) {
die('Error: Use a username/password of at least 3 characters');
exit();
}
if ($_POST['makeuser'] == true) {
if (strlen($_POST['user2']) < 3 || strlen($_POST['pass2']) < 3) {
die('Error: Use a username/password of at least 3 characters');
exit();
}
if ($_POST['username'] == $_POST['user2']) {
die('Error: Usernames cannot be identical to each other');
exit();
}
}
$myfile = fopen("config.global.php", "w") or die("Fatal error: can't open file. Does your webserver have write permissions here?");
$admhash = password_hash($_POST['password'], PASSWORD_DEFAULT);
if ($_POST['makeuser'] == true) {
$usrhash = password_hash($_POST['pass2'], PASSWORD_DEFAULT);
}
fwrite($myfile, "<?php".PHP_EOL);
fwrite($myfile, '$adminuser = \''.$_POST['username'].'\';'.PHP_EOL);
fwrite($myfile, '$adminpass = \''.$admhash.'\';'.PHP_EOL);
// TODO: config.global.php should really just be a second SQL table
$myfile = fopen("config.global.php", "w") or die("Fatal error: can't open file. Does your webserver have write permissions here?");
$admhash = password_hash($_POST['password'], PASSWORD_DEFAULT);
if ($_POST['makeuser'] == true) {
$usrhash = password_hash($_POST['pass2'], PASSWORD_DEFAULT);
}
fwrite($myfile, "<?php".PHP_EOL);
fwrite($myfile, '$adminuser = \''.$_POST['username'].'\';'.PHP_EOL);
fwrite($myfile, '$adminpass = \''.$admhash.'\';'.PHP_EOL);
if ($_POST['makeuser'] == true) {
fwrite($myfile, '$secuser = \''.$_POST['user2'].'\';'.PHP_EOL);
fwrite($myfile, '$secpass = \''.$usrhash.'\';'.PHP_EOL);
}
fwrite($myfile, "?>".PHP_EOL);
echo '<br>User(s) created. I mean, check config.global.php to make sure, but then delete this file ASAP.';
if (file_exists("./filedb.sqlite")) {
unlink("./filedb.sqlite");
}
if ($_POST['makeuser'] == true) {
fwrite($myfile, '$secuser = \''.$_POST['user2'].'\';'.PHP_EOL);
fwrite($myfile, '$secpass = \''.$usrhash.'\';'.PHP_EOL);
}
fwrite($myfile, '$deleteafter = -1'.PHP_EOL);
if (!fwrite($myfile, "?>".PHP_EOL)) {
echo '<br><font color="FF0000">Error creating <b>config.global.php</b></font><br>Does the web server have write permissions here?';
die();
}
echo '<br>User(s) created.';
if (file_exists("./filedb.sqlite")) {
unlink("./filedb.sqlite");
}
touch("./filedb.sqlite");
$initializeDB = contactDB("CREATE TABLE files (
fileid int NOT NULL PRIMARY KEY,
filepath varchar(255) NOT NULL,
fileowner varchar(255) NOT NULL
);", 0);
echo '<br>Initialized file database';
touch("./filedb.sqlite");
$initializeDB = contactDB("CREATE TABLE files (
fileid int NOT NULL PRIMARY KEY,
filepath varchar(255) NOT NULL,
fileowner varchar(255) NOT NULL
);", 0);
echo '<br>Initialized file database';
// Delete setup.php
unlink("./setup.php");
}
?>
</div>
</div>
</body>
</html>

View file

@ -6,8 +6,8 @@ require('functions.global.php');
require('layout.php');
if ($_SESSION['simplefsvalid'] != true) {
header('location: login.php');
die();
header('location: login.php');
die();
}
$currentUser = $_SESSION['simplefsuser'];
@ -15,7 +15,7 @@ $currentUser = $_SESSION['simplefsuser'];
echo deliverTop("SimpleFS - Upload");
if ($_POST['fsubmitted'] == "true") {
$target_dir = "files/";
$target_file = $target_dir . basename($_FILES["upfile"]["name"]);
$uploadOk = 1;
@ -45,13 +45,13 @@ if($fileType == "php" || $fileType == "htm" || $fileType == "html" || $fileType
/* This following part shouldn't be deleted though, my apologies but without sanitizing these filenames, could break the whole thing */
/* **** */
if (strpos($target_file, "'") !== false) {
echo "<div align='center'><h1>Error: Cannot upload files with apostrophes or quote-marks</h1></div>";
$uploadOk = 0;
echo "<div align='center'><h1>Error: Cannot upload files with apostrophes or quote-marks</h1></div>";
$uploadOk = 0;
}
if (strpos($target_file, '"') !== false) {
echo "<div align='center'><h1>Error: Cannot upload files with apostrophes or quote-marks</h1></div>";
$uploadOk = 0;
echo "<div align='center'><h1>Error: Cannot upload files with apostrophes or quote-marks</h1></div>";
$uploadOk = 0;
}
/* Getting a list of all file IDs */
@ -62,26 +62,26 @@ if ($uploadOk == 0) {
echo "<div align='center'><h1>Error: file was not uploaded</h1></div>";
} else {
if (move_uploaded_file($_FILES["upfile"]["tmp_name"], $target_file)) {
$newFileId = rand(10000, 99999);
while (in_array($newFileId, $fileListId)) {
$newFileId = rand(10000, 99999);
}
$newFileId = rand(10000, 99999);
while (in_array($newFileId, $fileListId)) {
$newFileId = rand(10000, 99999);
}
/* Write entry to DB */
$publish = contactDB("INSERT INTO files (fileid, filepath, fileowner)
VALUES ($newFileId, '$target_file', '$currentUser');", 0);
/* Tell the user all is well */
echo "<div align='center'><h1>The file ". htmlspecialchars( basename( $_FILES["upfile"]["name"])). " has been uploaded.</h1></div>";
/* Write entry to DB */
$publish = contactDB("INSERT INTO files (fileid, filepath, fileowner)
VALUES ($newFileId, '$target_file', '$currentUser');", 0);
/* Tell the user all is well */
echo "<div align='center'><h1>The file ". htmlspecialchars( basename( $_FILES["upfile"]["name"])). " has been uploaded.</h1></div>";
} else {
echo "<div align='center'><h1>Error uploading file</h1></div>";
echo "<div align='center'><h1>Error uploading file</h1></div>";
}
}