Skip to main content

Arquitectura de Seguridad

Capas de Seguridad

Stack de Seguridad Multicapa

SEGURIDAD MULTICAPA
├── HTTPS/TLS 1.3
├── JWT Authentication
├── AES-256 Encryption
├── BCrypt Password Hashing
├── CORS Configuration
├── Input Validation
└── Audit Logging

Flujo de Autenticación

sequenceDiagram
participant C as Cliente
participant F as Frontend
participant B as Backend
participant DB as Database

C->>F: Login credentials
F->>B: POST /auth/login
B->>DB: Validate user
DB-->>B: User data
B->>B: Generate JWT token
B-->>F: JWT + User info
F->>F: Store in Redux + localStorage
F-->>C: Redirect to dashboard

Note over F,B: Subsequent requests
F->>B: API request + JWT header
B->>B: Validate JWT
B-->>F: Protected resource

Encriptación de Datos

AES-256 Implementation

# Encriptación AES-256 para datos sensibles
def encrypt_data(data):
cipher = AES.new(ENCRYPTION_KEY, AES.MODE_CBC)
ct_bytes = cipher.encrypt(pad(data.encode(), AES.block_size))
iv = cipher.iv
encrypted_data = base64.b64encode(iv + ct_bytes).decode()
return encrypted_data

def decrypt_data(encrypted_data):
encrypted_data = base64.b64decode(encrypted_data)
iv = encrypted_data[:AES.block_size]
ct = encrypted_data[AES.block_size:]
cipher = AES.new(ENCRYPTION_KEY, AES.MODE_CBC, iv)
pt = unpad(cipher.decrypt(ct), AES.block_size)
return pt.decode()

Key Management

  • Encryption Key: AES-256 stored as environment variable
  • JWT Secret: Separate key for token signing
  • Key Rotation: Manual process for production updates
  • Storage: Environment variables, never in code

Authentication & Authorization

JWT Token Structure

{
"user_id": 123,
"email": "user@example.com",
"exp": 1672531200,
"iat": 1672494800
}

Role-Based Access Control

  • Admin: Full system access
  • Owner: Property management, contracts
  • Tenant: Limited property access, payments
  • Agent: Property sales, client management

Permission Matrix

Feature          | Admin | Owner | Tenant | Agent
-----------------|-------|-------|--------|-------
User Management | ✓ | ✗ | ✗ | ✗
Property CRUD | ✓ | ✓ | ✗ | ✓
Contract Mgmt | ✓ | ✓ | R | ✓
Payment Access | ✓ | ✓ | ✓ | ✗
Analytics | ✓ | ✓ | ✗ | ✗

Digital Signatures

Contract Signature Security

def generate_signature_hash(contract_id, user_id, signature_data, timestamp):
signature_payload = {
'contract_id': contract_id,
'user_id': user_id,
'signature_data': signature_data,
'timestamp': timestamp
}

json_string = json.dumps(signature_payload, sort_keys=True)
signature_hash = hashlib.sha256(json_string.encode()).hexdigest()

return signature_hash

Signature Verification

  • SHA-256 Hashing: For signature integrity
  • Timestamp Validation: Prevent replay attacks
  • IP Address Logging: Audit trail
  • User Agent Tracking: Device identification

Input Validation

Data Sanitization

def validate_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None

def validate_phone(phone):
pattern = r'^\+57\s?[3][0-9]{9}$|^[3][0-9]{9}$'
return re.match(pattern, phone) is not None

def sanitize_html(content):
allowed_tags = ['p', 'br', 'strong', 'em', 'ul', 'ol', 'li']
return bleach.clean(content, tags=allowed_tags, strip=True)

SQL Injection Prevention

  • Django ORM for all database queries
  • Parameterized queries when raw SQL needed
  • Input validation at serializer level
  • Database user with minimal privileges

CORS & Headers

Security Headers

SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
X_FRAME_OPTIONS = 'DENY'

CORS Configuration

CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOWED_ORIGINS = [
"https://alojaplus.com",
"https://www.alojaplus.com",
"http://localhost:3002" # Development only
]

CORS_ALLOW_METHODS = [
"DELETE",
"GET",
"OPTIONS",
"PATCH",
"POST",
"PUT",
]

Audit Logging

Security Event Logging

class SecurityLogger:
def log_login_attempt(self, email, success, ip_address):
self.logger.info(f"LOGIN_ATTEMPT: {email} - Success: {success} - IP: {ip_address}")

def log_permission_denied(self, user_id, resource, action):
self.logger.warning(f"PERMISSION_DENIED: User {user_id} - {action} on {resource}")

def log_data_access(self, user_id, data_type, record_id):
self.logger.info(f"DATA_ACCESS: User {user_id} - {data_type} - Record {record_id}")

Audit Trail

  • User Actions: Login, logout, profile changes
  • Data Access: Property views, contract access
  • Administrative Actions: User creation, role changes
  • Security Events: Failed logins, permission violations

Vulnerability Protection

Common Attack Vectors

# Rate Limiting
from django_ratelimit.decorators import ratelimit

@ratelimit(key='ip', rate='5/m', method='POST')
def login_view(request):
# Login logic
pass

# CSRF Protection
from django.views.decorators.csrf import csrf_protect

@csrf_protect
def sensitive_action(request):
# Sensitive operation
pass

Security Measures

  • Rate Limiting: Prevent brute force attacks
  • CSRF Protection: Cross-site request forgery prevention
  • XSS Protection: Input sanitization and output encoding
  • Session Security: Secure cookie settings
  • File Upload Validation: Type and size restrictions

Compliance & Standards

Data Protection

  • Data Minimization: Collect only necessary information
  • Purpose Limitation: Use data only for stated purposes
  • Storage Limitation: Automatic data retention policies
  • Encryption at Rest: AES-256 for sensitive data
  • Encryption in Transit: TLS 1.3 for all communications

Security Standards

  • OWASP Top 10: Regular vulnerability assessment
  • ISO 27001: Security management practices
  • SOC 2: Security and availability controls
  • PCI DSS: Payment data protection (via Stripe)

Regular Security Reviews

  • Penetration Testing: Quarterly external assessments
  • Code Reviews: All security-related changes
  • Dependency Updates: Monthly security patch updates
  • Access Reviews: Quarterly permission audits