285 lines
No EOL
6.5 KiB
Markdown
285 lines
No EOL
6.5 KiB
Markdown
# Keys for All - Security Model
|
|
|
|
## Overview
|
|
|
|
The Keys for All system implements defense-in-depth security with multiple layers of protection for key generation, validation, and distribution.
|
|
|
|
## Key Security
|
|
|
|
### Key Generation
|
|
|
|
1. **Cryptographically Secure Random Number Generator (CSPRNG)**
|
|
```javascript
|
|
const crypto = require('crypto');
|
|
|
|
function generateSecureKey() {
|
|
const bytes = crypto.randomBytes(12); // 96 bits of entropy
|
|
const key = base32Encode(bytes); // Base32 for readability
|
|
return formatKey(key); // XXXX-XXXX-XXXX-XXXX
|
|
}
|
|
```
|
|
|
|
2. **Key Format**
|
|
- 16 characters in 4 groups
|
|
- Base32 alphabet (no ambiguous characters)
|
|
- 96 bits of entropy (2^96 possible keys)
|
|
- Built-in checksum validation
|
|
|
|
3. **Collision Prevention**
|
|
- Database unique constraint
|
|
- Retry on collision (extremely rare)
|
|
- Monitoring for collision attempts
|
|
|
|
### Key Validation
|
|
|
|
1. **Format Validation**
|
|
- Regex pattern matching
|
|
- Checksum verification
|
|
- Character set validation
|
|
|
|
2. **Business Logic Validation**
|
|
- Key exists in database
|
|
- Key not expired
|
|
- Key not revoked
|
|
- App ID matches
|
|
|
|
## API Security
|
|
|
|
### Authentication
|
|
|
|
1. **API Key Requirements**
|
|
- 256-bit randomly generated keys
|
|
- Stored as hashed values (bcrypt)
|
|
- Rotatable on demand
|
|
- Per-app isolation
|
|
|
|
2. **Request Signing** (Optional High Security)
|
|
```
|
|
X-Signature: HMAC-SHA256(request_body + timestamp, api_secret)
|
|
X-Timestamp: 1674567890
|
|
```
|
|
|
|
### Rate Limiting
|
|
|
|
1. **Tiered Limits**
|
|
```javascript
|
|
const rateLimits = {
|
|
'/keys/validate': { window: '1m', max: 100 },
|
|
'/keys/generate': { window: '1m', max: 10 },
|
|
'/community/request': { window: '1h', max: 1 },
|
|
'default': { window: '1h', max: 1000 }
|
|
};
|
|
```
|
|
|
|
2. **Implementation**
|
|
- Redis-based sliding window
|
|
- Per API key and per IP
|
|
- Exponential backoff for violations
|
|
|
|
### Input Validation
|
|
|
|
1. **Request Validation**
|
|
- JSON schema validation (AJV)
|
|
- SQL injection prevention (parameterized queries)
|
|
- XSS prevention (output encoding)
|
|
|
|
2. **Data Sanitization**
|
|
```javascript
|
|
const sanitize = require('mongo-sanitize');
|
|
const validator = require('validator');
|
|
|
|
// Clean all user input
|
|
const cleanInput = (data) => {
|
|
return sanitize(data);
|
|
};
|
|
```
|
|
|
|
## Data Security
|
|
|
|
### Encryption at Rest
|
|
|
|
1. **Database Encryption**
|
|
- PostgreSQL Transparent Data Encryption (TDE)
|
|
- Encrypted backups
|
|
- Encrypted file systems
|
|
|
|
2. **Sensitive Data**
|
|
- Purchase receipts encrypted with AES-256
|
|
- Email addresses hashed for lookups
|
|
- No credit card data stored
|
|
|
|
### Encryption in Transit
|
|
|
|
1. **TLS Requirements**
|
|
- TLS 1.2 minimum
|
|
- Strong cipher suites only
|
|
- HSTS enabled
|
|
- Certificate pinning for mobile apps
|
|
|
|
2. **API Communication**
|
|
```nginx
|
|
ssl_protocols TLSv1.2 TLSv1.3;
|
|
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384';
|
|
ssl_prefer_server_ciphers on;
|
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
|
```
|
|
|
|
## Access Control
|
|
|
|
### Role-Based Access Control (RBAC)
|
|
|
|
```javascript
|
|
const roles = {
|
|
'app': ['read:own_keys', 'create:keys', 'validate:keys'],
|
|
'admin': ['read:all_keys', 'create:keys', 'revoke:keys', 'read:analytics'],
|
|
'support': ['read:keys', 'read:users', 'create:community_keys']
|
|
};
|
|
```
|
|
|
|
### Principle of Least Privilege
|
|
|
|
1. **Database Access**
|
|
- Apps can only access their own keys
|
|
- Read-only replicas for analytics
|
|
- Separate credentials per service
|
|
|
|
2. **API Scopes**
|
|
- Granular permissions per endpoint
|
|
- OAuth 2.0 style scopes
|
|
- Audit trail for all actions
|
|
|
|
## Audit and Monitoring
|
|
|
|
### Logging
|
|
|
|
1. **Security Events**
|
|
```javascript
|
|
const securityEvents = [
|
|
'key.generated',
|
|
'key.validated',
|
|
'key.activation_failed',
|
|
'api.authentication_failed',
|
|
'rate_limit.exceeded',
|
|
'suspicious.pattern_detected'
|
|
];
|
|
```
|
|
|
|
2. **Log Storage**
|
|
- Centralized logging (ELK stack)
|
|
- Immutable audit trail
|
|
- 90-day retention minimum
|
|
- Real-time alerting
|
|
|
|
### Anomaly Detection
|
|
|
|
1. **Patterns to Detect**
|
|
- Unusual validation patterns
|
|
- Key farming attempts
|
|
- Brute force attacks
|
|
- Geographic anomalies
|
|
|
|
2. **Response Actions**
|
|
- Automatic rate limit increases
|
|
- API key suspension
|
|
- Admin notifications
|
|
- Incident response triggers
|
|
|
|
## Privacy Protection
|
|
|
|
### Data Minimization
|
|
|
|
1. **No Personal Data Required**
|
|
- Keys are anonymous
|
|
- No user accounts needed
|
|
- Optional email for community requests
|
|
|
|
2. **Data Retention**
|
|
- Analytics aggregated after 30 days
|
|
- Logs pruned after 90 days
|
|
- Inactive keys archived
|
|
|
|
### GDPR Compliance
|
|
|
|
1. **User Rights**
|
|
- Right to erasure (key revocation)
|
|
- Data portability (key export)
|
|
- Transparency (clear policies)
|
|
|
|
2. **Data Processing**
|
|
```javascript
|
|
// Anonymize IP addresses
|
|
const anonymizeIP = (ip) => {
|
|
const parts = ip.split('.');
|
|
if (parts.length === 4) {
|
|
parts[3] = '0'; // IPv4
|
|
}
|
|
return parts.join('.');
|
|
};
|
|
```
|
|
|
|
## Incident Response
|
|
|
|
### Security Incident Procedure
|
|
|
|
1. **Detection**
|
|
- Automated alerts
|
|
- Manual reports
|
|
- Regular audits
|
|
|
|
2. **Response Plan**
|
|
```
|
|
1. Isolate affected systems
|
|
2. Assess impact and scope
|
|
3. Contain the incident
|
|
4. Eradicate the threat
|
|
5. Recover normal operations
|
|
6. Post-incident review
|
|
```
|
|
|
|
3. **Communication**
|
|
- Notify affected apps within 24 hours
|
|
- Public disclosure if widespread
|
|
- Transparent incident reports
|
|
|
|
## Best Practices for App Developers
|
|
|
|
### Secure Integration
|
|
|
|
1. **Store API Keys Securely**
|
|
```swift
|
|
// iOS Keychain
|
|
let keychain = Keychain(service: "com.app.keysforall")
|
|
keychain["api_key"] = apiKey
|
|
```
|
|
|
|
2. **Validate Keys Locally First**
|
|
```swift
|
|
func isValidKeyFormat(_ key: String) -> Bool {
|
|
let pattern = "^[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$"
|
|
return key.range(of: pattern, options: .regularExpression) != nil
|
|
}
|
|
```
|
|
|
|
3. **Handle Errors Gracefully**
|
|
- Don't expose error details to users
|
|
- Log errors for debugging
|
|
- Implement retry logic
|
|
|
|
### Security Checklist
|
|
|
|
- [ ] API keys stored in secure storage
|
|
- [ ] HTTPS certificate pinning implemented
|
|
- [ ] Input validation before API calls
|
|
- [ ] Rate limiting handled gracefully
|
|
- [ ] Error messages don't leak information
|
|
- [ ] Regular security updates applied
|
|
- [ ] Audit logs for key operations
|
|
|
|
## Security Contact
|
|
|
|
Report security vulnerabilities to: security@keysforall.com
|
|
|
|
We follow responsible disclosure with:
|
|
- 90-day disclosure timeline
|
|
- Bug bounty program available
|
|
- CVE assignment for valid issues |