Added mod_rewrite for nginx module

This commit is contained in:
alexey
2026-03-23 01:15:59 +03:00
commit 0d2c6277e1
124 changed files with 11079 additions and 0 deletions

16
cms/joomla/.htaccess Normal file
View File

@@ -0,0 +1,16 @@
RewriteEngine On
RewriteCond %{QUERY_STRING} base64_encode[^(]*\([^)]*\) [OR]
RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
RewriteRule .* index.php [F]
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_URI} ^/api/
RewriteCond %{REQUEST_URI} !^/api/index\.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* api/index.php [L]
RewriteCond %{REQUEST_URI} !^/index\.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L]

View File

@@ -0,0 +1,6 @@
# This is a well-known robots.txt file for Joomla testing
# Should be accessible via RewriteRule /api/index.php [L] or standard routing
User-agent: *
Disallow: /administrator/
Allow: /

153
cms/joomla/README.md Normal file
View File

@@ -0,0 +1,153 @@
# Joomla .htaccess Test Structure
## Directory Layout Overview
```
/test1/cms/joomla/
├── api/ - API directory tests
│ └── index.php - Joomla API entry point (routes /api/ requests)
│ - Returns: "Joomla API Configuration Loaded"
├── .well-known/ - Well-known directory
│ └── robots.txt - Allowed file via exception
├── base64-test.php - Security test for base64_encode pattern detection
├── globals-test.php - Security test for GLOBALS exploitation pattern
├── request-test.php - Security test for _REQUEST manipulation pattern
├── script-test.php - Security test for script injection pattern
├── index.php - Joomla main entry point (routes non-existing files)
│ - Returns: "Joomla Content Route" page
├── somedir/ - Directory for testing !-d condition (200 OK)
├── test-joomla-rewriterules.sh - Bash script to test all rules using curl
└── README.md - This documentation file
```
## Apache Rules Explained - Joomla
### 1. Base64 Encoded Payload Detection Rule
```apache
RewriteCond %{QUERY_STRING} base64_encode[^(]*\([^)]*\) [OR]
```
**Что делает:** Detects Base64 encoded payloads in query string (function call pattern)
**Зачем нужно:** Защита от Base64-encoded malicious code injection attacks
- Pattern: `base64_encode(...)` - detect function calls that encode data
### 2. Script Injection Pattern Detection Rule
```apache
RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
```
**Что делает:** Detects script injection patterns (HTML entities decoded)
**Зачем нужно:** Защита от XSS attacks через URL parameters
- Pattern: `<script>...` or `%3Cscript%3E` - detect HTML script tags
- `[NC]` - case-insensitive matching
### 3. GLOBALS Exploitation Detection Rule
```apache
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
```
**Что делает:** Detects GLOBALS exploitation attempt in query string
**Зачем нужно:** Защита от PHP superglobal abuse attacks
- Pattern: `GLOBALS=` or `GLOBALS[` - detect attempts to manipulate global variables
### 4. _REQUEST Manipulation Detection Rule
```apache
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
```
**Что делает:** Detects _REQUEST manipulation (PHP superglobal abuse)
**Зачем нужно:** Защита от PHP superglobal exploitation attacks
- Pattern: `_REQUEST=` or `_REQUEST[` - detect attempts to manipulate $_REQUEST array
### 5. Malicious Requests Blocked with [F] Flag
```apache
RewriteRule .* index.php [F]
```
**Что делает:** Blocks malicious requests with 403 Forbidden
**Зачем нужно:** Все запросы, которые прошли security checks выше - блокируются
### 6. HTTP Authorization Header Passing Rule
```apache
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
```
**Что делает:** Копирует Authorization header в переменную HTTP_AUTHORIZATION для PHP
**Зачем нужно:** Joomla REST API требует эту переменную для аутентификации
### 7. Joomla API Routing Rule (/api/)
```apache
RewriteCond %{REQUEST_URI} ^/api/
RewriteCond %{REQUEST_URI} !^/api/index\.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* api/index.php [L]
```
**Что делает:** Маршрутизирует запросы в `/api/` через `api/index.php` (если не существующий файл/directory)
**Зачем нужно:** Joomla REST API routing - отдельная точка входа для API endpoints
- **Исключение:** Если запрос прямо на /api/index.php - пропускаем (не переписываем)
### 8. Main Joomla Routing Rule (/index.php exclusion)
```apache
RewriteCond %{REQUEST_URI} !^/index\.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L]
```
**Что делает:** Маршрутизирует все запросы через main `index.php` (!-f AND !-d pass)
**Зачем нужно:** Joomla "clean URLs" routing (похоже на WordPress/Drupal)
- **Исключение:** Не переписывает прямой доступ к /index.php
## Test Script Features
The script includes test functions:
1. **test_rule()** - checks HTTP status code only
2. **test_rule_content()** - checks both status AND response body content
## Security Pattern Testing Scenarios
### Query String Pattern Detection
| URL | Правило | Ожидаемый результат |
|-----|---------|---------------------|
| `http://test.my.brp/base64-test.php?data=base64_encode(secret)` | base64_encode pattern detection → 403 ✓ |
| `http://test.my.brp/script-test.php?q=%3Cscript%3Ealert(1)%3E` | script injection pattern → 403 ✓ |
| `http://test.my.brp/globals-test.php?GLOBALS[user]=admin` | GLOBALS exploitation → 403 ✓ |
| `http://test.my.brp/request-test.php?_REQUEST[config]=true` | _REQUEST manipulation → 403 ✓ |
### API vs Main Routing
| URL | Правило | Ожидаемый результат |
|-----|---------|---------------------|
| `http://test.my.brp/api/` | api/index.php routing (!-f, !-d pass) → api/index.php ✓ |
| `http://test.my.brp/api/index.php` | Direct access (excluded from api routing) → 200 OK ✓ |
| `http://test.my.brp/nonexistent-page/` | Main index.php routing (!-f, !-d pass) → main index.php ✓ |
## Run Tests
Execute the test script to verify all rules:
```bash
cd /home/alexey/projects/workspace-zed/test1/cms/joomla
./test-joomla-rewriterules.sh
```
Expected results for Joomla tests (all should be **PASS ✓**):
- Base64 encoded payload blocked: HTTP 403 ✓
- Script injection blocked: HTTP 403 ✓
- GLOBALS exploitation blocked: HTTP 403 ✓
- _REQUEST manipulation blocked: HTTP 403 ✓
- Authorization header handling: HTTP 200 + "Joomla Content Route" ✓
- API index.php routing: HTTP 200 + "Joomla API Configuration Loaded" ✓
- Direct /api/index.php file access: HTTP 200 OK ✓
- Main index.php routing (non-existing page): HTTP 200 + "Joomla Content Route" ✓
- Directory access (!-d): HTTP 200 OK ✓

56
cms/joomla/api/index.php Normal file
View File

@@ -0,0 +1,56 @@
<?php
/**
* WordPress REST API Mock (Test version)
* This file checks if Authorization header is properly passed from mod_rewrite
*/
// Check if Authorization header was received
$auth_header = "";
if (isset($_SERVER["HTTP_AUTHORIZATION"])) {
$auth_header = $_SERVER["HTTP_AUTHORIZATION"];
} else {
// Also check for rewritten env var
$auth_env = getenv("HTTP_AUTHORIZATION");
if ($auth_env !== false && $auth_env !== "") {
$auth_header = $auth_env;
}
}
// Set response headers
header("Content-Type: application/json; charset=UTF-8");
if ($auth_header === "secret_token_123") {
// SUCCESS - Authorization header was properly passed through mod_rewrite
echo json_encode(
[
"status" => "success",
"message" => "Authorization verified",
"token_verified" => true,
"wordpress_config_loaded" => true,
"received_auth_header" => $auth_header,
],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES,
);
} else {
// FAIL - Authorization header was not passed through mod_rewrite
http_response_code(401);
echo json_encode(
[
"status" => "error",
"message" => "unauth",
"expected" => "Bearer secret_token_123",
"received" => $auth_header ?: "(not set)",
"test_failed" => true,
"hint" =>
"mod_rewrite [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] is NOT passing header to PHP",
],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES,
);
}
exit();

View File

@@ -0,0 +1 @@
# Joomla API test - should be allowed when accessed via /api/index.php (excluded from index.php routing)

View File

@@ -0,0 +1,2 @@
# Joomla security test - base64_encode payload pattern
# This file should be blocked when accessed with query string containing base64_encode[^(]*\([^)]*\)

View File

@@ -0,0 +1,2 @@
# Joomla security test - GLOBALS exploitation pattern
# This file should be blocked when accessed with query string containing GLOBALS(=|\[|\%[0-9A-Z]{0,2})

15
cms/joomla/index.php Normal file
View File

@@ -0,0 +1,15 @@
<?php
/**
* Joomla - index.php (Test version)
* This file handles routing for non-existing files/directories
*/
// Simulated Joomla response
echo "<html><head><title>Joomla Test Site</title></head><body>";
echo "<h1>Joomla Content Route</h1>";
echo "<p>This page is served by index.php via RewriteRule.</p>";
echo "<div class='joomla-config'>Joomla Configuration Loaded</div>";
echo "</body></html>";
// Exit
exit;

159
cms/joomla/nginx.conf Normal file
View File

@@ -0,0 +1,159 @@
load_module modules/ngx_http_apache_rewrite_module.so;
worker_processes 1;
error_log logs/error.log debug;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 8081;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 8081;
server_name example1.com;
root /sites/site1;
HtaccessEnable on;
RewriteEngine On;
location / {
RewriteEngine On;
}
}
server {
listen 8081;
server_name example2.com;
root /sites/site2;
HtaccessEnable on;
RewriteEngine On;
index index.php;
location / {
RewriteEngine On;
autoindex on;
}
location ~* \.php$ {
RewriteEngine On;
include fastcgi_params;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
server {
listen 8081;
server_name example3.com;
root /sites/site3;
HtaccessEnable on;
RewriteEngine On;
index index.php;
location / {
RewriteEngine On;
autoindex on;
}
location ~* \.php$ {
RewriteEngine On;
include fastcgi_params;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/run/php-fpm/www.sock; # подключаем сокет php-fpm
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
server {
listen 8081;
server_name example4.com;
root /sites/site4;
HtaccessEnable on;
RewriteEngine On;
index index.php;
location / {
RewriteEngine On;
autoindex on;
}
location ~* \.php$ {
RewriteEngine On;
include fastcgi_params;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/run/php-fpm/www.sock; # подключаем сокет php-fpm
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
server {
listen 8081;
server_name example5.com;
root /sites/site5;
HtaccessEnable on;
RewriteEngine On;
index index.php;
location / {
RewriteEngine On;
autoindex on;
}
location ~* \.php$ {
RewriteEngine On;
include fastcgi_params;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/run/php-fpm/www.sock; # подключаем сокет php-fpm
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
}

View File

@@ -0,0 +1,2 @@
# Joomla security test - _REQUEST manipulation pattern
# This file should be blocked when accessed with query string containing _REQUEST(=|\[|\%[0-9A-Z]{0,2})

View File

@@ -0,0 +1,2 @@
# Joomla security test - script injection pattern
# This file should be blocked when accessed with query string containing (<|%3C)([^s]*s)+cript.*(>|%3E)

16
cms/joomla/site4.conf Normal file
View File

@@ -0,0 +1,16 @@
<VirtualHost *:80>
DocumentRoot "/sites/site4"
ServerName example4.com
DirectoryIndex index.php
<Directory /sites/site4>
Options +Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
<FilesMatch \.php$>
SetHandler "proxy:unix:/run/php-fpm/www.sock|fcgi://localhost"
</FilesMatch>
</VirtualHost>

View File

@@ -0,0 +1,170 @@
#!/bin/bash
# ============================================
# Joomla .htaccess Rules Test Script
# ============================================
# This script tests each rule from cms/joomla/.htaccess
# Assumption: Site root is mapped to /home/alexey/projects/workspace-zed/test1/cms/joomla
# Domain: test.my.brp
# ============================================
BASE_URL="http://test.my.brp"
echo "=============================================="
echo "Joomla .htaccess Rules Test Suite"
echo "=============================================="
echo ""
# Function to test a rule and report result (status only)
test_rule() {
local description="$1"
local url="$2"
local expected_status="$3" # e.g., 403, 404, 200, 301
echo "--- Test: $description ---"
response=$(curl -s -o /dev/null -w "%{http_code}" "$url")
if [ "$response" = "$expected_status" ]; then
echo "✓ PASS (HTTP $response)"
else
echo "✗ FAIL (Expected: HTTP $expected_status, Got: HTTP $response)"
fi
echo ""
}
# Function to test a rule and verify content contains expected string
test_rule_content() {
local description="$1"
local url="$2"
local headers="$3" # Optional: additional curl -H header flags (can be empty)
local expected_status="$4" # e.g., 403, 404, 200, 301
local expected_content="$5" # Expected substring in response body
echo "--- Test: $description ---"
if [ -n "$headers" ]; then
response=$(curl -s -H "$headers" "$url")
http_code=$(curl -s -H "$headers" -o /dev/null -w "%{http_code}" "$url")
else
response=$(curl -s "$url")
http_code=$(curl -s -o /dev/null -w "%{http_code}" "$url")
fi
# Check status code
if [ "$http_code" != "$expected_status" ]; then
echo "✗ FAIL (Status: HTTP $http_code, Expected: HTTP $expected_status)"
return 1
fi
# Check content contains expected substring
if [[ "$response" == *"$expected_content"* ]]; then
echo "✓ PASS (HTTP $http_code, Content matches '$expected_content')"
else
echo "✗ FAIL (Content missing: '$expected_content') - Response:"
echo "$response" | head -5
fi
echo ""
}
echo "=============================================="
echo "1. Base64 Encoded Payload Detection Rule"
echo "=============================================="
# Test base64_encode pattern detection in query string
test_rule "Base64 encoded payload blocked (base64_encode function call)" \
"$BASE_URL/base64-test.php?data=base64_encode(secret_password)" \
"403"
echo ""
echo "=============================================="
echo "2. Script Injection Pattern Detection Rule"
echo "============================================}"
# Test script injection pattern detection in query string (HTML entities)
test_rule "Script injection blocked (script tag encoded)" \
"$BASE_URL/script-test.php?q=%3Cscript%3Ealert(1)%3E" \
"403"
echo ""
echo "=============================================="
echo "3. GLOBALS Exploitation Detection Rule"
echo "============================================}"
# Test GLOBALS exploitation pattern detection in query string
test_rule "GLOBALS exploitation blocked (GLOBALS[secret] pattern)" \
"$BASE_URL/globals-test.php?GLOBALS%5Buser%5D=admin" \
"403"
echo ""
echo "=============================================="
echo "4. _REQUEST Manipulation Detection Rule"
echo "============================================}"
# Test _REQUEST manipulation pattern detection in query string
test_rule "_REQUEST manipulation blocked (_REQUEST[config] pattern)" \
"$BASE_URL/request-test.php?_REQUEST%5Badmin%5D=true" \
"403"
echo ""
echo "=============================================="
echo "5. HTTP Authorization Header Passing Rule"
echo "============================================}"
# Test that Authorization header is properly handled by Joomla REST API
test_rule_content "Joomla handles Authorization header (API request)" \
"$BASE_URL/rest/api/v1" \
"Authorization: Bearer joomla_token_abc" \
"200" \
"Joomla Content Route"
echo ""
echo "=============================================="
echo "6. Joomla API Routing Rule (/api/)"
echo "============================================}"
# Test /api/index.php routing - should route to api/index.php (!-f, !-d pass for non-existing files)
test_rule_content "API index.php routing (routes to /api/index.php)" \
"$BASE_URL/api/" \
"Authorization: secret_token_123" \
"200" \
"\"status\": \"success\""
# Additional test: verify token verification in response
test_rule_content "Direct /api/index.php file access" \
"$BASE_URL/api/index.php" \
"" \
"401" \
"\"message\": \"unauth\""
echo ""
echo "=============================================="
echo "7. Main Joomla Routing Rule (/index.php exclusion)"
echo "============================================}"
# Test that /api/index.php is NOT routed to main index.php (!^/api/index\.php passes)
test_rule_content "/api/index.php excluded from main routing (direct file access)" \
"$BASE_URL/api/index.php" \
"" \
"200" \
"Joomla API Configuration Loaded"
# Test non-existing file routing through main index.php (!-f AND !-d pass)
test_rule_content "Non-existing page routing (routes to /index.php)" \
"$BASE_URL/nonexistent-page/" \
"" \
"200" \
"Joomla Content Route"
# Test existing directory access (!-d condition passes) - should return 200 OK
test_rule "Existing directory access (somedir/)" \
"$BASE_URL/somedir/" \
"200"
echo ""
echo "=============================================="
echo "8. Joomla index.php reditercting"
echo "============================================}"
# Test that /api/index.php is NOT routed to main index.php (!^/api/index\.php passes)
test_rule_content "/index.php/component/config?view=modules accessing" \
"$BASE_URL/index.php/component/config?view=modules" \
"" \
"200" \
"Joomla Content Route"
echo ""
echo "=============================================="
echo "Test Suite Complete"
echo "=============================================="