This document outlines the security measures implemented across all AgriTech Flask applications to prevent common web vulnerabilities including SQL injection, XSS attacks, file upload vulnerabilities, and input validation bypasses.
Before Fix:
@app.route('/predict', methods=['POST'])
def predict():
data = [
float(request.form['N']), # No validation - crashes if missing
float(request.form['P']), # No validation
# ... more fields
]After Fix:
@app.route('/predict', methods=['POST'])
@validate_required_fields(['N', 'P', 'K', 'temperature', 'humidity', 'ph', 'rainfall'])
def predict():
try:
data = [
sanitize_numeric_input(request.form['N'], 0, 200, "Nitrogen (N)"),
sanitize_numeric_input(request.form['P'], 0, 200, "Phosphorus (P)"),
# ... more validated fields
]
except ValueError as e:
return jsonify({'error': str(e)}), 400Before Fix:
query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
cursor.execute(query) # DANGEROUSAfter Fix:
query = "SELECT id, username, password_hash FROM users WHERE username = ?"
cursor.execute(query, (username,)) # SAFE - Parameterized queryBefore Fix:
filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(filepath) # DANGEROUS - No validationAfter Fix:
# Validate file extension
if not allowed_file(file.filename):
return jsonify({'error': 'Invalid file type'}), 400
# Validate file size
if not validate_file_size(file):
return jsonify({'error': 'File too large'}), 400
# Sanitize filename
filename = sanitize_filename(file.filename)
unique_filename = f"{uuid.uuid4().hex}_{filename}"
filepath = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)Before Fix:
return render_template('result.html', user_input=user_input) # DANGEROUSAfter Fix:
sanitized_input = sanitize_input(user_input, 255)
return render_template('result.html', user_input=sanitized_input) # SAFEDecorator that ensures all required form fields are present and non-empty.
Removes dangerous characters and limits input length to prevent XSS and injection attacks.
Validates and sanitizes numeric inputs with range checking.
Validates file extensions against a whitelist.
Ensures uploaded files don't exceed size limits.
Removes dangerous characters from filenames to prevent path traversal attacks.
All applications now include proper error handling that:
- Returns appropriate HTTP status codes
- Logs errors without exposing sensitive information
- Provides user-friendly error messages
- Prevents information disclosure
Applications include security headers:
X-Content-Type-Options: nosniffX-Frame-Options: DENYX-XSS-Protection: 1; mode=blockStrict-Transport-Security: max-age=31536000; includeSubDomains
- ✅ Input validation for all form fields
- ✅ Numeric range validation
- ✅ Error handling for missing/invalid data
- ✅ PDF generation security
- ✅ Form field validation
- ✅ Encoder validation
- ✅ Numeric input sanitization
- ✅ Comprehensive error handling
- ✅ Input sanitization
- ✅ API error handling
- ✅ Timeout protection
- ✅ Data validation
- ✅ JSON validation
- ✅ Content length limits
- ✅ XSS prevention
- ✅ Input sanitization
- ✅ File upload validation
- ✅ File type restrictions
- ✅ File size limits
- ✅ Path traversal prevention
- ✅ Filename sanitization
- ✅ JSON input validation
- ✅ AI prompt sanitization
- ✅ Error handling
- ✅ Input length limits
- ✅ API timeout protection
- ✅ Retry logic with exponential backoff
- ✅ Response caching
- ✅ Error handling
python security_test.pyThe security test script validates:
- Missing field handling
- SQL injection prevention
- XSS prevention
- File upload security
- Numeric input validation
- JSON validation
- Error handling
- API endpoint availability
SQL_INJECTION_PAYLOADS = [
"admin'; DROP TABLE users; --",
"' OR '1'='1",
"admin' UNION SELECT * FROM users --",
# ... more payloads
]XSS_PAYLOADS = [
"<script>alert('XSS')</script>",
"<img src=x onerror=alert('XSS')>",
"javascript:alert('XSS')",
# ... more payloads
]- Use the provided validation decorators
- Sanitize all user inputs
- Validate data types and ranges
- Never use string formatting for SQL queries
- Always use parameterized queries or ORM
- Don't expose sensitive information in error messages
- Log errors for debugging
- Return appropriate HTTP status codes
- Validate file types and sizes
- Sanitize filenames
- Store files outside web root when possible
- Enable HTTPS for all communications
- Use secure cookies
- Implement HSTS headers
# Security dependencies
bcrypt==4.0.1
email-validator==2.0.0
flask-limiter==3.5.0
werkzeug==2.3.7
requests==2.31.0- Run security tests monthly
- Review access logs
- Monitor for suspicious activity
- Keep all dependencies updated
- Monitor for security advisories
- Use
pip-auditto check for vulnerabilities
- Monitor application logs for errors
- Set up alerts for security events
- Review failed authentication attempts
- Immediately isolate affected systems
- Preserve evidence
- Assess the scope of the breach
- Notify relevant stakeholders
- Implement fixes
- Document lessons learned
- Report vulnerabilities to the development team
- Provide detailed reproduction steps
- Allow reasonable time for fixes
- Coordinate public disclosure
For security issues, please contact the development team or create a security issue in the project repository.
Last Updated: December 2024 Version: 1.0