Skip to content

Instantly share code, notes, and snippets.

@SuriyaRuk
Created June 26, 2025 01:25
Show Gist options
  • Save SuriyaRuk/a93d612120e1b1d217cc6c3665222336 to your computer and use it in GitHub Desktop.
Save SuriyaRuk/a93d612120e1b1d217cc6c3665222336 to your computer and use it in GitHub Desktop.
hack .htaccess
# .htaccess Security Protection Guide
[![Security Status](https://img.shields.io/badge/Security-Critical-red.svg)](https://github.com/yourusername/htaccess-security-guide)
[![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Thai Language](https://img.shields.io/badge/Language-Thai-green.svg)](README_TH.md)
## πŸ“‹ Table of Contents
- [Overview](#overview)
- [Common Attack Vectors](#common-attack-vectors)
- [Protection Methods](#protection-methods)
- [Quick Fix](#quick-fix)
- [Advanced Protection](#advanced-protection)
- [Monitoring & Detection](#monitoring--detection)
- [Emergency Response](#emergency-response)
- [Best Practices](#best-practices)
- [Contributing](#contributing)
## πŸ›‘οΈ Overview
This guide provides comprehensive protection methods for `.htaccess` files against malicious modifications. The `.htaccess` file is a critical configuration file that can be exploited by attackers to redirect traffic, display malicious content, or compromise your website.
## ⚠️ Common Attack Vectors
### 1. PHP File Upload Vulnerability
```php
// Dangerous code - allows uploading any file type
if(isset($_FILES['file'])) {
move_uploaded_file($_FILES['file']['tmp_name'], '.htaccess');
}
```
### 2. File Write Functions in PHP
```php
// From SQL Injection or RCE vulnerabilities
file_put_contents('.htaccess', $malicious_content);
fwrite(fopen('.htaccess', 'w'), $malicious_content);
```
### 3. Directory Traversal Attack
```php
// If code like this exists
$filename = $_GET['file'];
file_put_contents($filename, $content); // Can inject '../.htaccess'
```
### 4. Compromised FTP/SSH Access
- Weak FTP/SSH passwords
- Compromised key authentication
## πŸ”’ Protection Methods
### 1. File Permission Protection
```bash
# Set .htaccess as read-only
chmod 444 .htaccess
# Or allow only owner read-write
chmod 644 .htaccess
# Prevent modification by web server
chattr +i .htaccess # Make file immutable (Linux)
```
### 2. Directory Permission
```bash
# Set directory permissions
chmod 755 /path/to/website/
chown -R webuser:webgroup /path/to/website/
# Prevent web server from writing files in root folder
chmod 555 /path/to/website/ # Read and execute only
```
### 3. .htaccess Self-Protection Rules
```apache
# Add to .htaccess to protect itself
<Files ".htaccess">
Order Allow,Deny
Deny from all
</Files>
# Protect other configuration files
<FilesMatch "^(\.htaccess|\.htpasswd|config\.php|wp-config\.php)$">
Order Allow,Deny
Deny from all
</FilesMatch>
```
## πŸš€ Quick Fix
If your `.htaccess` has been compromised, follow these immediate steps:
### Step 1: Backup and Replace
```bash
# Backup the infected file
cp .htaccess .htaccess.infected.backup
# Create clean .htaccess
cat > .htaccess << 'EOF'
Options -Indexes
<FilesMatch "\.(htaccess|htpasswd|ini|log|sh|inc|bak)$">
Order Allow,Deny
Deny from all
</FilesMatch>
<FilesMatch "\.php$">
Order Allow,Deny
Deny from all
</FilesMatch>
<FilesMatch '^(index\.php|login\.php|logout\.php|connect\.php|home\.php)$'>
Order Allow,Deny
Allow from all
</FilesMatch>
ErrorDocument 403 /error403.html
ErrorDocument 404 /error404.html
EOF
# Protect from modification
chmod 444 .htaccess
```
### Step 2: Investigation
```bash
# Find recently modified files
find . -type f -mtime -7 -ls
# Search for malicious strings
grep -r "rebrand.ly" .
grep -r "tenor.com" .
grep -r "base64_decode\|eval\|exec" . --include="*.php"
```
## πŸ”§ Advanced Protection
### Web Server Configuration
#### Apache Virtual Host
```apache
<VirtualHost *:80>
DocumentRoot /var/www/html/stat
# Prevent file writing in root directory
<Directory "/var/www/html/stat">
AllowOverride None # Disable .htaccess
# or
AllowOverride Limit Options FileInfo # Limit to necessary directives
</Directory>
# Allow only specific directories
<Directory "/var/www/html/stat/uploads">
AllowOverride None
Options -ExecCGI -Includes
RemoveHandler .php .phtml .php3 .php4 .php5
</Directory>
</VirtualHost>
```
### PHP Security Configuration
```php
// In php.ini
disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source,file_put_contents,fwrite,fputs
// Check file write operations
function secure_file_write($filename, $content) {
// Prevent writing .htaccess
if (basename($filename) === '.htaccess') {
die('Access denied');
}
// Check directory traversal
$real_path = realpath(dirname($filename));
$allowed_path = realpath('/var/www/html/stat/uploads/');
if (strpos($real_path, $allowed_path) !== 0) {
die('Path not allowed');
}
return file_put_contents($filename, $content);
}
```
### Secure File Upload
```php
function secure_upload($file) {
$allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'pdf'];
$forbidden_names = ['.htaccess', '.htpasswd', 'config.php', 'wp-config.php'];
$filename = strtolower($file['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
// Check extension
if (!in_array($extension, $allowed_extensions)) {
die('File type not allowed');
}
// Check filename
if (in_array($filename, $forbidden_names)) {
die('Filename not allowed');
}
// Generate new filename
$new_filename = uniqid() . '.' . $extension;
$upload_path = '/var/www/html/stat/uploads/' . $new_filename;
// Check MIME type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $file['tmp_name']);
$allowed_mimes = [
'image/jpeg', 'image/png', 'image/gif',
'application/pdf'
];
if (!in_array($mime_type, $allowed_mimes)) {
die('Invalid file type');
}
return move_uploaded_file($file['tmp_name'], $upload_path);
}
```
## πŸ“Š Monitoring & Detection
### File Integrity Monitoring
```bash
#!/bin/bash
# htaccess_monitor.sh
HTACCESS_FILE="/var/www/html/stat/.htaccess"
BACKUP_HASH="/var/www/html/stat/.htaccess.md5"
LOG_FILE="/var/log/htaccess_monitor.log"
# Create hash of correct file (first time)
if [ ! -f "$BACKUP_HASH" ]; then
md5sum "$HTACCESS_FILE" > "$BACKUP_HASH"
echo "$(date): Initial hash created" >> "$LOG_FILE"
fi
# Check for changes
CURRENT_HASH=$(md5sum "$HTACCESS_FILE" | cut -d' ' -f1)
EXPECTED_HASH=$(cat "$BACKUP_HASH" | cut -d' ' -f1)
if [ "$CURRENT_HASH" != "$EXPECTED_HASH" ]; then
echo "$(date): WARNING - .htaccess file has been modified!" >> "$LOG_FILE"
# Send email alert
echo ".htaccess file has been modified at $(date)" | \
mail -s "SECURITY ALERT: .htaccess Modified" [email protected]
# Backup compromised file
cp "$HTACCESS_FILE" "/var/log/htaccess_compromised_$(date +%Y%m%d_%H%M%S).txt"
fi
```
### Automated Monitoring Setup
```bash
# Add to crontab for monitoring every 5 minutes
*/5 * * * * /usr/local/bin/htaccess_monitor.sh
# Setup cron job
crontab -e
```
## 🚨 Emergency Response
### Automated Recovery Script
```bash
#!/bin/bash
# emergency_restore.sh
CLEAN_HTACCESS="/var/www/html/stat/.htaccess.clean"
CURRENT_HTACCESS="/var/www/html/stat/.htaccess"
LOG_FILE="/var/log/emergency_restore.log"
# Check if clean backup exists
if [ ! -f "$CLEAN_HTACCESS" ]; then
echo "$(date): ERROR - Clean .htaccess backup not found!" >> "$LOG_FILE"
exit 1
fi
# Backup compromised file
cp "$CURRENT_HTACCESS" "/var/log/compromised_htaccess_$(date +%Y%m%d_%H%M%S).txt"
# Restore clean file
cp "$CLEAN_HTACCESS" "$CURRENT_HTACCESS"
# Set permissions
chmod 444 "$CURRENT_HTACCESS"
echo "$(date): .htaccess restored from clean backup" >> "$LOG_FILE"
# Reload web server
systemctl reload apache2
echo "$(date): Web server reloaded" >> "$LOG_FILE"
```
## πŸ“‹ Security Audit Script
```bash
#!/bin/bash
# security_audit.sh
echo "=== Security Audit Started ==="
echo "Date: $(date)"
echo ""
# 1. Check for malicious files
echo "1. Checking for suspicious files..."
find . -name "*.php" -type f -exec grep -l "base64_decode\|eval\|exec\|system\|shell_exec" {} \;
# 2. Check file permissions
echo "2. Checking file permissions..."
find . -type f -perm 777 -ls
# 3. Check for recently modified files
echo "3. Recently modified files (last 7 days)..."
find . -type f -mtime -7 -ls
# 4. Check for unusual file sizes
echo "4. Checking for unusually large PHP files..."
find . -name "*.php" -type f -size +100k -ls
# 5. Check for hidden files
echo "5. Checking for hidden files..."
find . -name ".*" -type f -ls
echo "=== Security Audit Completed ==="
```
## βœ… Best Practices
### 1. **Defense in Depth**
- Use multiple protection layers
- Regular security audits
- Keep software updated
### 2. **Regular Monitoring**
- Set up automated monitoring
- Review logs regularly
- Implement alerting systems
### 3. **Access Control**
- Use strong passwords
- Implement 2FA
- Limit file permissions
### 4. **Backup Strategy**
- Regular automated backups
- Test restore procedures
- Keep multiple backup versions
### 5. **Incident Response**
- Have a response plan
- Document procedures
- Practice recovery scenarios
## πŸ”§ Installation
1. Clone this repository:
```bash
git clone https://github.com/yourusername/htaccess-security-guide.git
cd htaccess-security-guide
```
2. Make scripts executable:
```bash
chmod +x scripts/*.sh
```
3. Setup monitoring:
```bash
./setup_monitoring.sh
```
## πŸ“ Usage
### Quick Security Check
```bash
./scripts/security_audit.sh
```
### Setup Protection
```bash
./scripts/setup_protection.sh
```
### Emergency Recovery
```bash
./scripts/emergency_restore.sh
```
## 🀝 Contributing
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
## πŸ“„ License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## ⚠️ Disclaimer
This guide is provided for educational and defensive purposes only. Always test security measures in a development environment before applying to production systems.
## πŸ“ž Support
- πŸ“§ Email: [email protected]
- πŸ› Issues: [GitHub Issues](https://github.com/yourusername/htaccess-security-guide/issues)
- πŸ“– Documentation: [Wiki](https://github.com/yourusername/htaccess-security-guide/wiki)
## πŸ™ Acknowledgments
- Apache HTTP Server Documentation
- OWASP Security Guidelines
- PHP Security Best Practices
- Thai Government IT Security Standards
---
⭐ **Star this repository if it helped you secure your website!**
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment