-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path15-in-memory-pattern-backend.php
More file actions
266 lines (211 loc) · 9.19 KB
/
Copy path15-in-memory-pattern-backend.php
File metadata and controls
266 lines (211 loc) · 9.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
<?php
/**
* Example 15: In-Memory Pattern Backend
*
* This example demonstrates how to use the InMemoryPatternBackend for
* configuration-based blocklists without file I/O.
*
* Use cases:
* - Hardcoded CIDR ranges (e.g., block internal networks from public API)
* - Configuration-driven blocklists
* - Testing and development
*
* Run: php examples/15-in-memory-pattern-backend.php
*/
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
use Flowd\Phirewall\Config;
use Flowd\Phirewall\Http\Firewall;
use Flowd\Phirewall\Pattern\InMemoryPatternBackend;
use Flowd\Phirewall\Pattern\PatternEntry;
use Flowd\Phirewall\Pattern\PatternKind;
use Flowd\Phirewall\Store\InMemoryCache;
use Nyholm\Psr7\ServerRequest;
echo "=== In-Memory Pattern Backend Example ===\n\n";
// =============================================================================
// SETUP
// =============================================================================
$config = new Config(new InMemoryCache());
// =============================================================================
// EXAMPLE 1: CIDR-BASED IP BLOCKING
// =============================================================================
echo "--- Example 1: CIDR-Based IP Blocking (Simple One-Step) ---\n\n";
// Simple approach: Create backend and register as blocklist in one step
// Use patternBlocklist() for the most common case
$ipBackend = $config->blocklists->patternBlocklist('private-networks', [
new PatternEntry(PatternKind::CIDR, '10.0.0.0/8'),
new PatternEntry(PatternKind::CIDR, '172.16.0.0/12'),
new PatternEntry(PatternKind::CIDR, '192.168.0.0/16'),
new PatternEntry(PatternKind::IP, '127.0.0.1'),
]);
echo "Blocked ranges:\n";
echo " - 10.0.0.0/8 (Class A private)\n";
echo " - 172.16.0.0/12 (Class B private)\n";
echo " - 192.168.0.0/16 (Class C private)\n";
echo " - 127.0.0.1 (localhost)\n\n";
// =============================================================================
// EXAMPLE 2: PATH-BASED BLOCKING
// =============================================================================
echo "--- Example 2: Path-Based Blocking (Two-Step for Reusability) ---\n\n";
// Two-step approach: Useful when sharing a backend between multiple rules
// or when you need more control over backend configuration
$pathBackend = $config->blocklists->inMemoryPatternBackend('blocked-paths', [
// Exact path matches
new PatternEntry(PatternKind::PATH_EXACT, '/admin'),
new PatternEntry(PatternKind::PATH_EXACT, '/.env'),
// Prefix matches
new PatternEntry(PatternKind::PATH_PREFIX, '/.aws'),
new PatternEntry(PatternKind::PATH_PREFIX, '/phpmyadmin'),
// Regex matches
new PatternEntry(PatternKind::PATH_REGEX, '/\.(git|svn|hg)/'),
]);
$config->blocklists->fromBackend('block-sensitive-paths', 'blocked-paths');
echo "Blocked paths:\n";
echo " - /admin (exact)\n";
echo " - /.env (exact)\n";
echo " - /.aws* (prefix)\n";
echo " - /phpmyadmin* (prefix)\n";
echo " - /.git/, /.svn/, /.hg/ (regex)\n\n";
// =============================================================================
// EXAMPLE 3: HEADER-BASED BLOCKING
// =============================================================================
echo "--- Example 3: Header-Based Blocking ---\n\n";
$headerBackend = $config->blocklists->inMemoryPatternBackend('blocked-headers', [
// Block specific User-Agents
new PatternEntry(
kind: PatternKind::HEADER_REGEX,
value: '/sqlmap|nikto|nmap|masscan/i',
target: 'User-Agent'
),
// Block empty User-Agent
new PatternEntry(
kind: PatternKind::HEADER_EXACT,
value: '',
target: 'User-Agent'
),
// Block specific referers
new PatternEntry(
kind: PatternKind::HEADER_REGEX,
value: '/spam-site\.com|malware\.net/i',
target: 'Referer'
),
]);
$config->blocklists->fromBackend('block-bad-headers', 'blocked-headers');
echo "Blocked headers:\n";
echo " - User-Agent matching: sqlmap, nikto, nmap, masscan\n";
echo " - Empty User-Agent\n";
echo " - Referer from spam-site.com or malware.net\n\n";
// =============================================================================
// EXAMPLE 4: DYNAMIC ENTRIES WITH EXPIRATION
// =============================================================================
echo "--- Example 4: Dynamic Entries with Expiration ---\n\n";
$dynamicBackend = $config->blocklists->inMemoryPatternBackend('dynamic-blocks');
// Add entries that expire
$dynamicBackend->append(new PatternEntry(
kind: PatternKind::IP,
value: '203.0.113.100',
expiresAt: time() + 3600, // Expires in 1 hour
metadata: ['reason' => 'Suspicious activity'],
));
$dynamicBackend->append(new PatternEntry(
kind: PatternKind::CIDR,
value: '198.51.100.0/24',
expiresAt: time() + 86400, // Expires in 24 hours
metadata: ['reason' => 'DDoS source'],
));
// Permanent block (no expiration)
$dynamicBackend->append(new PatternEntry(
kind: PatternKind::IP,
value: '203.0.113.200',
metadata: ['reason' => 'Known bad actor'],
));
$config->blocklists->fromBackend('dynamic-blocklist', 'dynamic-blocks');
echo "Dynamic entries added:\n";
echo " - 203.0.113.100 (expires in 1 hour)\n";
echo " - 198.51.100.0/24 (expires in 24 hours)\n";
echo " - 203.0.113.200 (permanent)\n\n";
// =============================================================================
// TESTING
// =============================================================================
echo "=== Testing Blocklists ===\n\n";
$firewall = new Firewall($config);
$testCases = [
// IP tests
['IP: Private (10.x)', 'GET', '/', [], '10.0.0.1', 'BLOCK'],
['IP: Private (172.x)', 'GET', '/', [], '172.16.0.1', 'BLOCK'],
['IP: Private (192.x)', 'GET', '/', [], '192.168.1.1', 'BLOCK'],
['IP: Localhost', 'GET', '/', [], '127.0.0.1', 'BLOCK'],
['IP: Public (allowed)', 'GET', '/', [], '8.8.8.8', 'ALLOW'],
// Path tests
['Path: /admin', 'GET', '/admin', [], '8.8.8.8', 'BLOCK'],
['Path: /.env', 'GET', '/.env', [], '8.8.8.8', 'BLOCK'],
['Path: /.aws', 'GET', '/.aws/credentials', [], '8.8.8.8', 'BLOCK'],
['Path: /.git/config', 'GET', '/.git/config', [], '8.8.8.8', 'BLOCK'],
['Path: /api/users', 'GET', '/api/users', [], '8.8.8.8', 'ALLOW'],
// Header tests
['Header: sqlmap UA', 'GET', '/', ['User-Agent' => 'sqlmap/1.0'], '8.8.8.8', 'BLOCK'],
['Header: Empty UA', 'GET', '/', ['User-Agent' => ''], '8.8.8.8', 'BLOCK'],
['Header: Normal UA', 'GET', '/', ['User-Agent' => 'Mozilla/5.0'], '8.8.8.8', 'ALLOW'],
['Header: Bad Referer', 'GET', '/', ['Referer' => 'https://spam-site.com/'], '8.8.8.8', 'BLOCK'],
// Dynamic blocks
['Dynamic: Temp IP', 'GET', '/', [], '203.0.113.100', 'BLOCK'],
['Dynamic: Temp CIDR', 'GET', '/', [], '198.51.100.50', 'BLOCK'],
['Dynamic: Perm IP', 'GET', '/', [], '203.0.113.200', 'BLOCK'],
];
$passed = 0;
$failed = 0;
foreach ($testCases as [$desc, $method, $path, $headers, $ip, $expected]) {
$request = new ServerRequest($method, $path, $headers, null, '1.1', ['REMOTE_ADDR' => $ip]);
$result = $firewall->decide($request);
$actual = $result->isBlocked() ? 'BLOCK' : 'ALLOW';
$status = $actual === $expected ? 'PASS' : 'FAIL';
if ($status === 'PASS') {
++$passed;
} else {
++$failed;
}
echo sprintf("[%s] %-25s => %s\n", $status, $desc, $actual);
}
echo "\n";
echo sprintf('Passed: %d%s', $passed, PHP_EOL);
echo sprintf('Failed: %d%s', $failed, PHP_EOL);
// =============================================================================
// BACKEND STATS
// =============================================================================
echo "\n=== Backend Statistics ===\n\n";
echo "private-networks: " . $ipBackend->count() . " entries\n";
echo "blocked-paths: " . $pathBackend->count() . " entries\n";
echo "blocked-headers: " . $headerBackend->count() . " entries\n";
echo "dynamic-blocks: " . $dynamicBackend->count() . " entries\n";
// =============================================================================
// USAGE PATTERNS
// =============================================================================
echo "\n=== Common Usage Patterns ===\n\n";
echo "1. Block cloud provider ranges from sensitive endpoints:\n";
echo <<<'CODE'
$backend = $config->blocklists->inMemoryPatternBackend('cloud-ips', [
new PatternEntry(PatternKind::CIDR, '13.32.0.0/15'), // AWS CloudFront
new PatternEntry(PatternKind::CIDR, '34.0.0.0/9'), // Google Cloud
new PatternEntry(PatternKind::CIDR, '40.74.0.0/15'), // Azure
]);
CODE;
echo "\n\n";
echo "2. Allow only specific countries (by known IP ranges):\n";
echo <<<'CODE'
$allowedBackend = $config->blocklists->inMemoryPatternBackend('allowed-ips', [
new PatternEntry(PatternKind::CIDR, '...'), // Your country's ranges
]);
// Use as safelist instead of blocklist
CODE;
echo "\n\n";
echo "3. Block Tor exit nodes (loaded from external source):\n";
echo <<<'CODE'
$torExits = file('https://check.torproject.org/exit-addresses');
$entries = array_map(
fn($ip) => new PatternEntry(PatternKind::IP, trim($ip)),
$torExits
);
$backend = $config->blocklists->inMemoryPatternBackend('tor-exits', $entries);
CODE;
echo "\n\n";
echo "=== Example Complete ===\n";