forked from UTSAVS26/PyVerse
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
105 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
## **Web Application Firewall** | ||
|
||
### 🎯 **Goal** | ||
|
||
The goal of this code is to create a Flask-based web application designed to process user input securely by preventing common web security threats. | ||
|
||
### 🧵 **Dataset** | ||
|
||
N/A | ||
|
||
### 🧾 **Description** | ||
|
||
This Python code is a Flask-based web application designed to process user input securely by preventing common web security threats like SQL Injection and Cross-Site Scripting (XSS). It uses pattern matching with regular expressions to detect these threats in the input. Additionally, it has a rate-limiting feature, limiting the number of requests from a single user to prevent abuse (DoS attacks). | ||
|
||
### 🧮 **What I had done!** | ||
|
||
1. Threat Detection: Implemented pattern matching using regular expressions to detect potential SQL injection and XSS attacks in user input. | ||
2. Input Sanitization: By using the html.escape() function, ensured that any harmful HTML characters are escaped, preventing malicious scripts from being executed in the browser. | ||
3. Rate Limiting: Integrated Flask-Limiter to impose rate limits (e.g., 10 requests per minute) on incoming requests, protecting the app from abuse such as denial of service (DoS) attacks. | ||
4. Logging: You set up logging to record any detected security events, such as SQL injection attempts or XSS attacks. This helps with monitoring and auditing the security of the application. | ||
|
||
### 🚀 **Models Implemented** | ||
|
||
N/A | ||
|
||
### 📚 **Libraries Needed** | ||
|
||
1. `Flask` : It is a lightweight web framework used to handle HTTP requests and responses, providing routes like /submit for user interaction. | ||
2. `Flask-Limiter` : Provides rate-limiting to protect the application from abuse, such as a Denial of Service (DoS) attack by limiting the number of requests a user can make. | ||
|
||
### 📊 **Exploratory Data Analysis Results** | ||
|
||
N/A. | ||
|
||
### 📈 **Performance of the Models based on the Accuracy Scores** | ||
|
||
N/A. | ||
|
||
### 📢 **Conclusion** | ||
|
||
This Flask-based web application effectively implements basic cybersecurity protections by detecting and preventing common threats like SQL Injection and Cross-Site Scripting (XSS) through pattern matching and input sanitization. The addition of rate-limiting safeguards the application from excessive requests, helping to mitigate DoS attacks. The app also incorporates robust logging to track security events, making it a simple yet effective solution for securing user input and enhancing web application security. | ||
|
||
**Deanne Vaz** | ||
[GitHub](https://github.com/djv554) | | [LinkedIn](https://www.linkedin.com/in/deanne-vaz/) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import re | ||
import logging | ||
from flask import Flask, request, jsonify | ||
from html import escape | ||
from flask_limiter import Limiter | ||
from flask_limiter.util import get_remote_address | ||
|
||
app = Flask(__name__) | ||
|
||
# Rate limiting configuration | ||
limiter = Limiter(app, key_func=get_remote_address) | ||
|
||
# Set up logging for security events | ||
logging.basicConfig(filename='security.log', level=logging.INFO) | ||
|
||
# Expanded SQL Injection and XSS patterns | ||
SQL_INJECTION_PATTERN = re.compile( | ||
r"(?:--|;|'|\"|OR|AND|SELECT|INSERT|DELETE|UPDATE|DROP|UNION|#|/\*|\*/|CHAR|HEX)", re.IGNORECASE) | ||
XSS_PATTERN = re.compile(r"(<script.*?>|<.*?on[a-zA-Z]+\s*=|javascript:|data:text/html)", re.IGNORECASE) | ||
|
||
def is_safe(input_string): | ||
"""Check if the input string is safe from SQL injection and XSS.""" | ||
if SQL_INJECTION_PATTERN.search(input_string): | ||
logging.warning(f"SQL Injection detected: {input_string}") | ||
return False, "Potential SQL Injection detected." | ||
if XSS_PATTERN.search(input_string): | ||
logging.warning(f"XSS attack detected: {input_string}") | ||
return False, "Potential XSS detected." | ||
return True, "" | ||
|
||
@app.route('/submit', methods=['POST']) | ||
@limiter.limit("10 per minute") # Rate limiting: max 10 requests per minute | ||
def submit(): | ||
try: | ||
data = request.json | ||
if not data or "user_input" not in data: | ||
return jsonify({"error": "Invalid input. Please provide valid JSON."}), 400 | ||
|
||
user_input = data.get("user_input", "") | ||
# Input length validation | ||
if len(user_input) > 1000: | ||
return jsonify({"error": "Input too long."}), 413 | ||
|
||
# Sanitize the input to escape harmful HTML characters | ||
safe_input = escape(user_input) | ||
|
||
# Check if the input is safe | ||
is_safe_input, reason = is_safe(safe_input) | ||
if not is_safe_input: | ||
return jsonify({"error": reason}), 400 | ||
|
||
# Log and process the safe input | ||
logging.info(f"Safe input processed: {safe_input}") | ||
return jsonify({"message": "Input processed successfully!"}), 200 | ||
|
||
except Exception as e: | ||
logging.error(f"Error processing request: {e}") | ||
return jsonify({"error": "An error occurred processing the request."}), 500 | ||
|
||
if __name__ == '__main__': | ||
app.run(debug=True) |