Enhance file deletion process in FileManager: Implement detailed logging for file and directory deletion, including security checks and error handling. Improve handling of immutable flags and ensure proper permissions for suspension pages in website management. Add fallback mechanisms for system file deletions and enhance user feedback on operations.

This commit is contained in:
Master3395
2025-09-20 20:39:35 +02:00
parent 6ef98c57e7
commit af434bcb89
3 changed files with 197 additions and 69 deletions

View File

@@ -384,16 +384,25 @@ class FileManager:
website = Websites.objects.get(domain=domainName) website = Websites.objects.get(domain=domainName)
self.homePath = '/home/%s' % (domainName) self.homePath = '/home/%s' % (domainName)
logging.CyberCPLogFileWriter.writeToFile(f"Attempting to delete files/folders for domain: {domainName}")
RemoveOK = 1 RemoveOK = 1
# Test if directory is writable
command = 'touch %s/public_html/hello.txt' % (self.homePath) command = 'touch %s/public_html/hello.txt' % (self.homePath)
result = ProcessUtilities.outputExecutioner(command) result = ProcessUtilities.outputExecutioner(command)
if result.find('cannot touch') > -1: if result.find('cannot touch') > -1:
RemoveOK = 0 RemoveOK = 0
logging.CyberCPLogFileWriter.writeToFile(f"Directory {self.homePath} is not writable, removing chattr flags")
# Remove immutable flag from entire directory
command = 'chattr -R -i %s' % (self.homePath) command = 'chattr -R -i %s' % (self.homePath)
ProcessUtilities.executioner(command) result = ProcessUtilities.executioner(command)
if result.find('cannot') > -1:
logging.CyberCPLogFileWriter.writeToFile(f"Warning: Failed to remove chattr -i from {self.homePath}: {result}")
else:
logging.CyberCPLogFileWriter.writeToFile(f"Successfully removed chattr -i from {self.homePath}")
else: else:
command = 'rm -f %s/public_html/hello.txt' % (self.homePath) command = 'rm -f %s/public_html/hello.txt' % (self.homePath)
@@ -401,111 +410,155 @@ class FileManager:
for item in self.data['fileAndFolders']: for item in self.data['fileAndFolders']:
itemPath = self.data['path'] + '/' + item
if (self.data['path'] + '/' + item).find('..') > -1 or (self.data['path'] + '/' + item).find( # Security check - prevent path traversal
self.homePath) == -1: if itemPath.find('..') > -1 or itemPath.find(self.homePath) == -1:
return self.ajaxPre(0, 'Not allowed to move in this path, please choose location inside home!') logging.CyberCPLogFileWriter.writeToFile(f"Security violation: Attempted to delete outside home directory: {itemPath}")
return self.ajaxPre(0, 'Not allowed to delete files outside home directory!')
logging.CyberCPLogFileWriter.writeToFile(f"Deleting: {itemPath}")
if skipTrash: if skipTrash:
command = 'rm -rf ' + self.returnPathEnclosed(self.data['path'] + '/' + item) # Permanent deletion
ProcessUtilities.executioner(command, website.externalApp) command = 'rm -rf ' + self.returnPathEnclosed(itemPath)
result = ProcessUtilities.executioner(command, website.externalApp)
if result.find('cannot') > -1 or result.find('Permission denied') > -1:
logging.CyberCPLogFileWriter.writeToFile(f"Failed to delete {itemPath}: {result}")
# Try with sudo if available
command = 'sudo rm -rf ' + self.returnPathEnclosed(itemPath)
result = ProcessUtilities.executioner(command, website.externalApp)
if result.find('cannot') > -1 or result.find('Permission denied') > -1:
return self.ajaxPre(0, f'Failed to delete {item}: {result}')
logging.CyberCPLogFileWriter.writeToFile(f"Successfully deleted: {itemPath}")
else: else:
# Move to trash
trashPath = '%s/.trash' % (self.homePath) trashPath = '%s/.trash' % (self.homePath)
command = 'mkdir %s' % (trashPath) # Ensure trash directory exists
ProcessUtilities.executioner(command, website.externalApp) command = 'mkdir -p %s' % (trashPath)
result = ProcessUtilities.executioner(command, website.externalApp)
if result.find('cannot') > -1:
logging.CyberCPLogFileWriter.writeToFile(f"Failed to create trash directory: {result}")
return self.ajaxPre(0, f'Failed to create trash directory: {result}')
# Save to trash database
try:
Trash(website=website, originalPath=self.returnPathEnclosed(self.data['path']), Trash(website=website, originalPath=self.returnPathEnclosed(self.data['path']),
fileName=self.returnPathEnclosed(item)).save() fileName=self.returnPathEnclosed(item)).save()
except Exception as e:
logging.CyberCPLogFileWriter.writeToFile(f"Failed to save trash record: {str(e)}")
command = 'mv %s %s' % (self.returnPathEnclosed(self.data['path'] + '/' + item), trashPath) # Move to trash
ProcessUtilities.executioner(command, website.externalApp) command = 'mv %s %s' % (self.returnPathEnclosed(itemPath), trashPath)
result = ProcessUtilities.executioner(command, website.externalApp)
if result.find('cannot') > -1 or result.find('Permission denied') > -1:
logging.CyberCPLogFileWriter.writeToFile(f"Failed to move to trash {itemPath}: {result}")
# Try with sudo if available
command = 'sudo mv %s %s' % (self.returnPathEnclosed(itemPath), trashPath)
result = ProcessUtilities.executioner(command, website.externalApp)
if result.find('cannot') > -1 or result.find('Permission denied') > -1:
return self.ajaxPre(0, f'Failed to move {item} to trash: {result}')
logging.CyberCPLogFileWriter.writeToFile(f"Successfully moved to trash: {itemPath}")
if RemoveOK == 0: if RemoveOK == 0:
logging.CyberCPLogFileWriter.writeToFile(f"Restoring chattr +i flags for {self.homePath}")
# Restore immutable flag to entire directory
command = 'chattr -R +i %s' % (self.homePath) command = 'chattr -R +i %s' % (self.homePath)
ProcessUtilities.executioner(command) result = ProcessUtilities.executioner(command)
if result.find('cannot') > -1:
logging.CyberCPLogFileWriter.writeToFile(f"Warning: Failed to restore chattr +i to {self.homePath}: {result}")
else:
logging.CyberCPLogFileWriter.writeToFile(f"Successfully restored chattr +i to {self.homePath}")
# Allow specific directories to remain mutable # Allow specific directories to remain mutable
command = 'chattr -R -i %s' % (self.homePath) + '/logs/' mutable_dirs = ['/logs/', '/.trash/', '/backup/', '/incbackup/', '/lscache/', '/.cagefs/']
ProcessUtilities.executioner(command) for dir_name in mutable_dirs:
dir_path = self.homePath + dir_name
command = 'chattr -R -i %s' % (self.homePath) + '/.trash/' command = 'chattr -R -i %s' % (dir_path)
ProcessUtilities.executioner(command) result = ProcessUtilities.executioner(command)
if result.find('cannot') > -1:
command = 'chattr -R -i %s' % (self.homePath) + '/backup/' logging.CyberCPLogFileWriter.writeToFile(f"Warning: Failed to remove chattr +i from {dir_path}: {result}")
ProcessUtilities.executioner(command) else:
logging.CyberCPLogFileWriter.writeToFile(f"Successfully removed chattr +i from {dir_path}")
command = 'chattr -R -i %s' % (self.homePath) + '/incbackup/' except Exception as e:
ProcessUtilities.executioner(command) logging.CyberCPLogFileWriter.writeToFile(f"Error in deleteFolderOrFile for {domainName}: {str(e)}")
command = 'chattr -R -i %s' % (self.homePath) + '/lscache/'
ProcessUtilities.executioner(command)
command = 'chattr -R -i %s' % (self.homePath) + '/.cagefs/'
ProcessUtilities.executioner(command)
except:
try: try:
skipTrash = self.data['skipTrash'] skipTrash = self.data['skipTrash']
except: except:
skipTrash = False skipTrash = False
# Fallback to root path for system files
self.homePath = '/' self.homePath = '/'
logging.CyberCPLogFileWriter.writeToFile(f"Using fallback deletion for system files in {self.data['path']}")
RemoveOK = 1 RemoveOK = 1
# Test if directory is writable
command = 'touch %s/public_html/hello.txt' % (self.homePath) command = 'touch %s/public_html/hello.txt' % (self.homePath)
result = ProcessUtilities.outputExecutioner(command) result = ProcessUtilities.outputExecutioner(command)
if result.find('cannot touch') > -1: if result.find('cannot touch') > -1:
RemoveOK = 0 RemoveOK = 0
logging.CyberCPLogFileWriter.writeToFile(f"Directory {self.homePath} is not writable, removing chattr flags")
command = 'chattr -R -i %s' % (self.homePath) command = 'chattr -R -i %s' % (self.homePath)
ProcessUtilities.executioner(command) result = ProcessUtilities.executioner(command)
if result.find('cannot') > -1:
logging.CyberCPLogFileWriter.writeToFile(f"Warning: Failed to remove chattr -i from {self.homePath}: {result}")
else: else:
command = 'rm -f %s/public_html/hello.txt' % (self.homePath) command = 'rm -f %s/public_html/hello.txt' % (self.homePath)
ProcessUtilities.executioner(command) ProcessUtilities.executioner(command)
for item in self.data['fileAndFolders']: for item in self.data['fileAndFolders']:
itemPath = self.data['path'] + '/' + item
if (self.data['path'] + '/' + item).find('..') > -1 or (self.data['path'] + '/' + item).find( # Security check for system files
self.homePath) == -1: if itemPath.find('..') > -1 or itemPath.find(self.homePath) == -1:
return self.ajaxPre(0, 'Not allowed to move in this path, please choose location inside home!') logging.CyberCPLogFileWriter.writeToFile(f"Security violation: Attempted to delete outside allowed path: {itemPath}")
return self.ajaxPre(0, 'Not allowed to delete files outside allowed path!')
logging.CyberCPLogFileWriter.writeToFile(f"Deleting system file: {itemPath}")
if skipTrash: if skipTrash:
command = 'rm -rf ' + self.returnPathEnclosed(self.data['path'] + '/' + item) command = 'rm -rf ' + self.returnPathEnclosed(itemPath)
ProcessUtilities.executioner(command) result = ProcessUtilities.executioner(command)
if result.find('cannot') > -1 or result.find('Permission denied') > -1:
logging.CyberCPLogFileWriter.writeToFile(f"Failed to delete system file {itemPath}: {result}")
return self.ajaxPre(0, f'Failed to delete {item}: {result}')
logging.CyberCPLogFileWriter.writeToFile(f"Successfully deleted system file: {itemPath}")
if RemoveOK == 0: if RemoveOK == 0:
logging.CyberCPLogFileWriter.writeToFile(f"Restoring chattr +i flags for system path: {self.homePath}")
command = 'chattr -R +i %s' % (self.homePath) command = 'chattr -R +i %s' % (self.homePath)
ProcessUtilities.executioner(command) result = ProcessUtilities.executioner(command)
if result.find('cannot') > -1:
logging.CyberCPLogFileWriter.writeToFile(f"Warning: Failed to restore chattr +i to system path {self.homePath}: {result}")
else:
logging.CyberCPLogFileWriter.writeToFile(f"Successfully restored chattr +i to system path {self.homePath}")
# Allow specific directories to remain mutable # Allow specific directories to remain mutable for system files
command = 'chattr -R -i %s' % (self.homePath) + '/logs/' mutable_dirs = ['/logs/', '/.trash/', '/backup/', '/incbackup/', '/lscache/', '/.cagefs/']
ProcessUtilities.executioner(command) for dir_name in mutable_dirs:
dir_path = self.homePath + dir_name
command = 'chattr -R -i %s' % (self.homePath) + '/.trash/' command = 'chattr -R -i %s' % (dir_path)
ProcessUtilities.executioner(command) result = ProcessUtilities.executioner(command)
if result.find('cannot') > -1:
command = 'chattr -R -i %s' % (self.homePath) + '/backup/' logging.CyberCPLogFileWriter.writeToFile(f"Warning: Failed to remove chattr +i from system {dir_path}: {result}")
ProcessUtilities.executioner(command) else:
logging.CyberCPLogFileWriter.writeToFile(f"Successfully removed chattr +i from system {dir_path}")
command = 'chattr -R -i %s' % (self.homePath) + '/incbackup/'
ProcessUtilities.executioner(command)
command = 'chattr -R -i %s' % (self.homePath) + '/lscache/'
ProcessUtilities.executioner(command)
command = 'chattr -R -i %s' % (self.homePath) + '/.cagefs/'
ProcessUtilities.executioner(command)
logging.CyberCPLogFileWriter.writeToFile(f"File deletion completed successfully for domain: {domainName}")
json_data = json.dumps(finalData) json_data = json.dumps(finalData)
return HttpResponse(json_data) return HttpResponse(json_data)
except BaseException as msg: except BaseException as msg:
return self.ajaxPre(0, str(msg)) logging.CyberCPLogFileWriter.writeToFile(f"Critical error in deleteFolderOrFile: {str(msg)}")
return self.ajaxPre(0, f"File deletion failed: {str(msg)}")
def restore(self): def restore(self):
try: try:

View File

@@ -1152,6 +1152,12 @@ Automatic backup failed for %s on %s.
# #
# command = 'chattr -R -i /home/%s/incbackup/' % (website.domain) # command = 'chattr -R -i /home/%s/incbackup/' % (website.domain)
# ProcessUtilities.executioner(command) # ProcessUtilities.executioner(command)
#
# command = 'chattr -R -i /home/%s/lscache/' % (website.domain)
# ProcessUtilities.executioner(command)
#
# command = 'chattr -R -i /home/%s/.cagefs/' % (website.domain)
# ProcessUtilities.executioner(command)
# else: # else:
# command = 'chattr -R -i /home/%s/' % (website.domain) # command = 'chattr -R -i /home/%s/' % (website.domain)
# ProcessUtilities.executioner(command) # ProcessUtilities.executioner(command)

View File

@@ -2890,6 +2890,17 @@ Require valid-user
# Ensure suspension page exists and has proper permissions # Ensure suspension page exists and has proper permissions
suspensionPagePath = "/usr/local/CyberCP/websiteFunctions/suspension.html" suspensionPagePath = "/usr/local/CyberCP/websiteFunctions/suspension.html"
suspensionDir = "/usr/local/CyberCP/websiteFunctions"
# Ensure directory exists
if not os.path.exists(suspensionDir):
try:
command = f"mkdir -p {suspensionDir}"
ProcessUtilities.executioner(command)
logging.CyberCPLogFileWriter.writeToFile(f"Created suspension directory: {suspensionDir}")
except Exception as e:
logging.CyberCPLogFileWriter.writeToFile(f"Failed to create suspension directory: {str(e)}")
if not os.path.exists(suspensionPagePath): if not os.path.exists(suspensionPagePath):
# Create default suspension page if it doesn't exist # Create default suspension page if it doesn't exist
defaultSuspensionHTML = """<!DOCTYPE html> defaultSuspensionHTML = """<!DOCTYPE html>
@@ -2958,17 +2969,34 @@ Require valid-user
# Use ProcessUtilities to move the file to the final location # Use ProcessUtilities to move the file to the final location
command = f"mv {tempFile} {suspensionPagePath}" command = f"mv {tempFile} {suspensionPagePath}"
ProcessUtilities.executioner(command) ProcessUtilities.executioner(command)
except: logging.CyberCPLogFileWriter.writeToFile(f"Created suspension page: {suspensionPagePath}")
pass except Exception as e:
logging.CyberCPLogFileWriter.writeToFile(f"Failed to create suspension page: {str(e)}")
# Try alternative method using echo command
try:
command = f'echo "{defaultSuspensionHTML.replace('"', '\\"')}" > {suspensionPagePath}'
ProcessUtilities.executioner(command)
logging.CyberCPLogFileWriter.writeToFile(f"Created suspension page using echo: {suspensionPagePath}")
except Exception as e2:
logging.CyberCPLogFileWriter.writeToFile(f"Failed to create suspension page with echo: {str(e2)}")
return self.ajaxPre(0, f"Failed to create suspension page: {str(e2)}")
# Set proper permissions for suspension page # Set proper permissions for suspension page
try: try:
command = f"chown lsadm:lsadm {suspensionPagePath}" command = f"chown lsadm:lsadm {suspensionPagePath}"
ProcessUtilities.executioner(command) result = ProcessUtilities.executioner(command)
if result.find('cannot') > -1:
logging.CyberCPLogFileWriter.writeToFile(f"Warning: Failed to set ownership for suspension page: {result}")
command = f"chmod 644 {suspensionPagePath}" command = f"chmod 644 {suspensionPagePath}"
ProcessUtilities.executioner(command) result = ProcessUtilities.executioner(command)
except: if result.find('cannot') > -1:
pass logging.CyberCPLogFileWriter.writeToFile(f"Warning: Failed to set permissions for suspension page: {result}")
logging.CyberCPLogFileWriter.writeToFile(f"Set permissions for suspension page: {suspensionPagePath}")
except Exception as e:
logging.CyberCPLogFileWriter.writeToFile(f"Error setting suspension page permissions: {str(e)}")
# Don't fail the entire operation for permission issues
# Create suspension configuration with end marker # Create suspension configuration with end marker
suspensionConf = """# Website Suspension Configuration suspensionConf = """# Website Suspension Configuration
@@ -2999,10 +3027,18 @@ context /cyberpanel_suspension_page.html {
""" """
try: try:
# Check if vhost file exists
if not os.path.exists(vhostConfPath):
logging.CyberCPLogFileWriter.writeToFile(f"Error: Vhost configuration file not found: {vhostConfPath}")
return self.ajaxPre(0, f"Vhost configuration file not found for {websiteName}")
# Read current vhost configuration # Read current vhost configuration
with open(vhostConfPath, 'r') as f: with open(vhostConfPath, 'r') as f:
vhostContent = f.read() vhostContent = f.read()
if not vhostContent.strip():
logging.CyberCPLogFileWriter.writeToFile(f"Warning: Empty vhost configuration file: {vhostConfPath}")
if "# Website Suspension Configuration" not in vhostContent: if "# Website Suspension Configuration" not in vhostContent:
# Check if there's an existing rewrite block at the root level # Check if there's an existing rewrite block at the root level
# If so, we need to comment it out to avoid conflicts # If so, we need to comment it out to avoid conflicts
@@ -3026,7 +3062,11 @@ context /cyberpanel_suspension_page.html {
# Set proper ownership # Set proper ownership
command = f"chown lsadm:lsadm {vhostConfPath}" command = f"chown lsadm:lsadm {vhostConfPath}"
ProcessUtilities.executioner(command) result = ProcessUtilities.executioner(command)
if result.find('cannot') > -1:
logging.CyberCPLogFileWriter.writeToFile(f"Warning: Failed to set vhost ownership: {result}")
logging.CyberCPLogFileWriter.writeToFile(f"Successfully suspended website: {websiteName}")
except IOError as e: except IOError as e:
# If direct file access fails, fall back to command-based approach # If direct file access fails, fall back to command-based approach
command = f"cat {vhostConfPath}" command = f"cat {vhostConfPath}"
@@ -3115,17 +3155,34 @@ context /cyberpanel_suspension_page.html {
except Exception as e: except Exception as e:
CyberCPLogFileWriter.writeToFile(f"Error suspending child domain {items.domain}: {str(e)}") CyberCPLogFileWriter.writeToFile(f"Error suspending child domain {items.domain}: {str(e)}")
# Restart LiteSpeed to apply changes
try:
installUtilities.reStartLiteSpeedSocket() installUtilities.reStartLiteSpeedSocket()
website.state = 0 logging.CyberCPLogFileWriter.writeToFile(f"Restarted LiteSpeed after suspending {websiteName}")
except Exception as e:
logging.CyberCPLogFileWriter.writeToFile(f"Warning: Failed to restart LiteSpeed: {str(e)}")
website.state = 1
else: else:
# Unsuspend logic
confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName
vhostConfPath = confPath + "/vhost.conf" vhostConfPath = confPath + "/vhost.conf"
logging.CyberCPLogFileWriter.writeToFile(f"Attempting to unsuspend website: {websiteName}")
try: try:
# Check if vhost file exists
if not os.path.exists(vhostConfPath):
logging.CyberCPLogFileWriter.writeToFile(f"Error: Vhost configuration file not found: {vhostConfPath}")
return self.ajaxPre(0, f"Vhost configuration file not found for {websiteName}")
# Try direct file access first # Try direct file access first
with open(vhostConfPath, 'r') as f: with open(vhostConfPath, 'r') as f:
vhostContent = f.read() vhostContent = f.read()
if not vhostContent.strip():
logging.CyberCPLogFileWriter.writeToFile(f"Warning: Empty vhost configuration file: {vhostConfPath}")
if "# Website Suspension Configuration" in vhostContent: if "# Website Suspension Configuration" in vhostContent:
# Use regex to remove the suspension configuration block # Use regex to remove the suspension configuration block
pattern = r'# Website Suspension Configuration.*?# End Website Suspension Configuration\n' pattern = r'# Website Suspension Configuration.*?# End Website Suspension Configuration\n'
@@ -3150,7 +3207,13 @@ context /cyberpanel_suspension_page.html {
f.write(modifiedContent) f.write(modifiedContent)
command = f"chown lsadm:lsadm {vhostConfPath}" command = f"chown lsadm:lsadm {vhostConfPath}"
ProcessUtilities.executioner(command) result = ProcessUtilities.executioner(command)
if result.find('cannot') > -1:
logging.CyberCPLogFileWriter.writeToFile(f"Warning: Failed to set vhost ownership: {result}")
logging.CyberCPLogFileWriter.writeToFile(f"Successfully unsuspended website: {websiteName}")
else:
logging.CyberCPLogFileWriter.writeToFile(f"Website {websiteName} is not currently suspended")
except IOError: except IOError:
# Fall back to command-based approach # Fall back to command-based approach
command = f"cat {vhostConfPath}" command = f"cat {vhostConfPath}"
@@ -3240,8 +3303,14 @@ context /cyberpanel_suspension_page.html {
except Exception as e: except Exception as e:
CyberCPLogFileWriter.writeToFile(f"Error unsuspending child domain {items.domain}: {str(e)}") CyberCPLogFileWriter.writeToFile(f"Error unsuspending child domain {items.domain}: {str(e)}")
# Restart LiteSpeed to apply changes
try:
installUtilities.reStartLiteSpeedSocket() installUtilities.reStartLiteSpeedSocket()
website.state = 1 logging.CyberCPLogFileWriter.writeToFile(f"Restarted LiteSpeed after unsuspending {websiteName}")
except Exception as e:
logging.CyberCPLogFileWriter.writeToFile(f"Warning: Failed to restart LiteSpeed: {str(e)}")
website.state = 0
website.save() website.save()