Files
MSPE/BACKEND_SECURITY_FIXES.md
T

8.6 KiB

Backend Security Fixes Applied

Date: February 24, 2026

Summary

Comprehensive backend security review and fixes applied to the MSPE website PHP API. All critical and high-priority security issues have been addressed.


Issues Fixed

1. Missing CSRF Protection on Auth Endpoints

File: api/auth.php Issue: Login and password reset endpoints didn't validate same-origin requests. Fix: Added requireSameOriginRequest() call to auth POST endpoints. Impact: Prevents cross-site request forgery attacks on authentication endpoints.

2. Inconsistent Response Function Implementation

File: api/config.php Issue: jsonResponse() used exit() instead of die(), and didn't clean output buffer. Fix: Changed to die() and added ob_clean() for consistency, plus JSON flags for proper Unicode handling. Impact: Ensures clean API responses, better error handling.

3. Email Validation Issues

Files: api/auth.php, api/config.php, api/contact.php Issue: Missing email format validation in several endpoints. Fixes:

  • Added email validation in password reset request
  • Added comprehensive email parameter validation in sendEmail() function
  • Added email validation in contact form submission
  • Added email validation to subscribe endpoint (already present) Impact: Prevents malformed email data and reduces SMTP errors.

4. Email Function Error Handling

File: api/config.php Issue: sendEmail() lacked parameter validation and error handling. Fixes:

  • Validates all email addresses with filter_var()
  • Validates subject and body are not empty
  • Validates reply-to email if provided
  • Returns structured error responses Impact: Better error reporting for email failures.

5. recordFailedLogin Code Smell

File: api/auth.php Issue: Function called getRequestBody() internally, causing double-parsing. Fix: Changed to accept username parameter instead of re-parsing body. Impact: Better code efficiency and clarity.

6. File Upload Error Handling

File: api/config.php Issue: mkdir() and file operations lacked error checking. Fixes:

  • Added return value checks for mkdir()
  • Added write-permission verification
  • Added path traversal protection in media deletion
  • Added socket validity checks in file operations Impact: Prevents file system errors and directory traversal attacks.

7. SMTP Socket Connection Hardening

File: api/config.php Issues:

  • Timeout was too short (20 seconds)
  • Missing socket validity checks
  • Missing timeout detection
  • Missing parameter validation for port Fixes:
  • Increased timeout to 30 seconds
  • Added socket resource checks before operations
  • Added timeout detection in expect function
  • Added port range validation (1-65535)
  • Added proper error logging Impact: More robust SMTP email delivery with better error handling.

8. Date/Time Validation in Bookings

File: api/bookings.php Issues:

  • No validation of date format (YYYY-MM-DD)
  • No validation of time format (HH:MM)
  • No validation of time values (hours 0-23, minutes 0-59)
  • No capacity range validation Fixes:
  • Added regex validation for date format
  • Added regex validation for time format
  • Added range checks for hours and minutes
  • Added capacity range validation (1-100)
  • Applied to createAvailabilitySlot() and blockTime() functions Impact: Prevents invalid data entry and database corruption.

9. Phone Number Validation

File: api/contact.php Issue: Phone numbers weren't validated. Fix: Added basic phone number validation (minimum 5 digits, allows standard formatting). Impact: Better contact form data quality.

10. SQL Injection Prevention Enhancement

File: api/config.php Issue: Table name validation could theoretically be improved. Fix: Added table name length check (max 64 chars) and validation in ensureTable(). Impact: Additional layer of SQL injection prevention.

11. Media Path Traversal Protection

File: api/media.php Issue: Media deletion didn't verify files were in upload directory. Fix: Added realpath() check to verify path is within UPLOAD_DIR before deletion. Impact: Prevents directory traversal attacks in file deletion.

12. JSON Response Security

File: api/config.php Issue: JSON responses didn't specify encoding flags. Fix: Added JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE flags for proper encoding. Impact: Better handling of international characters and special characters.


Security Best Practices Already in Place

Password Hashing: Using password_hash() with PASSWORD_DEFAULT Rate Limiting: Per-IP and per-username rate limiting on login attempts CSRF Protection: requireSameOriginRequest() on public POST endpoints Input Sanitization: Using sanitize() and sanitizeRichText() functions JWT Authentication: Secure token-based authentication with expiration HTTPS/TLS: HSTS headers and SSL/TLS enforcement Security Headers: XSS, clickjacking, and content security policy headers Audit Logging: All security events logged with IP, user, and timestamp File Upload Validation: MIME type verification and extension whitelist SQL Injection Prevention: Prepared statements and parameterized queries Email Validation: Using PHP's FILTER_VALIDATE_EMAIL Error Handling: Proper error codes and messages without exposing internals


Recommendations for Further Hardening

High Priority

  1. Environment Configuration Review

    • Ensure .env file is not in webroot
    • Verify JWT_SECRET is properly set in production
    • Set APP_ENV to 'production' in production servers
  2. Database Monitoring

    • Implement connection logging for debugging
    • Monitor for unusual query patterns
    • Set up alerts for failed authentication attempts
  3. Rate Limiting Enhancement

    • Consider implementing Redis-based rate limiting for better performance
    • Add rate limiting to API endpoints (currently only on auth/contact)

Medium Priority

  1. API Documentation

    • Document all endpoints with required authentication
    • Add rate limit information to API docs
    • Document error codes and messages
  2. Monitoring & Alerts

    • Implement email notifications for failed login attempts (after threshold)
    • Monitor email delivery failures
    • Track usage patterns for anomaly detection
  3. Testing

    • Add automated security tests for input validation
    • Test rate limiting thresholds
    • Validate CORS configuration

Low Priority

  1. Performance Optimization

    • Cache frequently accessed data
    • Consider pagination defaults
    • Optimize database queries
  2. Code Quality

    • Add type hints to functions
    • Increase test coverage
    • Add PHPDoc comments to all functions

Files Modified

  • api/auth.php - CSRF protection, email validation, recordFailedLogin fix
  • api/config.php - Email validation, file handling, SMTP hardening, JSON response, SQL injection prevention
  • api/contact.php - Email validation, phone validation
  • api/bookings.php - Date/time validation, capacity validation
  • api/media.php - Path traversal protection

Testing Recommendations

1. Authentication Testing

# Test CSRF protection
curl -X POST https://example.com/api/auth.php \
  -H "Origin: https://malicious.com" \
  -d '{"action":"login","username":"admin","password":"test"}'
# Should return 403

2. Email Validation Testing

# Test invalid email
curl -X POST https://example.com/api/contact.php \
  -d '{"email":"invalid-email"}'
# Should return 400

3. Date/Time Validation Testing

# Test invalid date format
curl -X POST https://example.com/api/bookings.php?action=create-slot \
  -H "Authorization: Bearer TOKEN" \
  -d '{"date":"2026-02-invalid","time":"14:30"}'
# Should return 400

Deployment Checklist

  • Update .env file with strong JWT_SECRET
  • Set APP_ENV=production
  • Enable HTTPS/TLS
  • Configure SMTP credentials
  • Set up backup and restore procedures
  • Configure log rotation
  • Test all email functionality
  • Test all booking functionality
  • Run security header verification
  • Update API documentation
  • Train support team on new error messages
  • Monitor for any issues in first 24 hours

Version History

Date Version Changes
2026-02-24 1.0 Initial security audit and fixes

Contact

For security concerns or issues, contact: info@mspe.pro