From_ Telstra Security Operations (2)
From_ Telstra Security Operations (2)
Here’s how you can approach creating a firewall rule in Python to filter incoming
traffic based on malicious URL patterns and IP whitelisting. Since you’ll be simulating
this using an HTTP server, the script will inspect incoming requests and drop/block
any that don't match the whitelisted IPs or contain malicious patterns.
### Steps:
3. **Write Python Code**: Use Python’s built-in HTTP server and modify the `do_GET`
or `do_POST` methods to implement these checks.
### `firewall_server.py`
```python
#!/usr/bin/env python3
class FirewallHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
client_ip = self.client_address[0]
# Check if the IP is whitelisted
self.send_response(403) # Forbidden
self.end_headers()
return
parsed_url = urlparse(self.path)
query_params = parse_qs(parsed_url.query)
if param in BLOCKED_PATTERNS:
self.end_headers()
return
self.send_response(200) # OK
self.end_headers()
def do_POST(self):
# Set up and run the HTTP server with the firewall logic
def run(server_class=HTTPServer, handler_class=FirewallHTTPRequestHandler,
port=8080):
httpd.serve_forever()
if __name__ == '__main__':
run()
```
1. **Whitelisting IPs**:
- We parse the URL and query parameters using `urlparse` and `parse_qs`.
- We iterate over the query parameters, and if any match the blocked patterns
(`cmd`, `pwd`, `exec`), we return a `400 Bad Request` response.
3. **Handling Requests**:
- If the IP is trusted and no malicious patterns are detected, the request is allowed
(`200 OK`).
Testing:
- Use the `test_requests.py` script provided to send test requests to this HTTP server.
```bash
python3 firewall_server.py
```
Next Steps:
- Test the server against various inputs using the `test_requests.py` script to ensure it
correctly blocks malicious requests and allows legitimate ones.
Kind regards,
Amine Dhaouadi
Cybersecurity Analyst
[email protected]