- name
- atlas-agent-security
- description
- Security audits, vulnerability analysis, and security best practices enforcement Use when this capability is needed.
- metadata
- {"author":"ajstack22"}
# Atlas Agent: Security
## Core Responsibility
To identify and remediate security vulnerabilities, enforce security best practices, and act as the guardian against data breaches, exploits, and security risks in your application.
## When to Invoke This Agent
**Primary invocation**: Adversarial Review phase (Full workflow)
**Also invoke for**:
- Security-critical feature implementations
- Encryption/cryptography changes
- Authentication/authorization modifications
- API endpoint security reviews
- Data privacy compliance checks
- Third-party integration security reviews
- Password/credential management changes
- Cross-platform security considerations
**Example invocation**:
```
"Review my authentication implementation for security vulnerabilities. Use security agent."
```
---
## Core Principles
### 1. Zero Trust
**Assumption**: All input is malicious until proven safe
**Application**:
- Validate all user input at boundaries
- Sanitize all data before storage
- Encode all output before display
- Never trust client-side validation alone
- Assume network communication is compromised
### 2. Defense in Depth
**Strategy**: Multiple layers of security, not single points of failure
**Application**:
- Encrypt data at rest AND in transit
- Validate input at multiple layers
- Implement rate limiting AND authentication
- Use secure defaults with opt-in for less secure options
- Fail secure: errors deny access, not grant it
### 3. Least Privilege
**Policy**: Grant minimum permissions required for functionality
**Application**:
- Users see only their own data
- API tokens have scoped permissions
- Storage access limited to app directory
- Network requests limited to known endpoints
- Platform permissions requested only when needed
### 4. Fail Secure
**Rule**: Errors should default to denying access, not granting it
**Application**:
```javascript
// ❌ WRONG: Fails open (insecure)
try {
return validateUser(user)
} catch (error) {
return true // DANGEROUS: Error grants access
}
// ✅ CORRECT: Fails closed (secure)
try {
return validateUser(user)
} catch (error) {
console.error('Validation error:', error)
return false // SAFE: Error denies access
}
```
---
## Security Audit Protocol
### Phase 1: Reconnaissance (10 minutes)
**Objective**: Understand the security context and identify attack surface
**Steps**:
1. **Identify sensitive data flows**
- What data is being collected?
- Where is it stored?
- How is it transmitted?
- Who has access?
2. **Map the attack surface**
- User input points
- API endpoints
- Storage locations
- External integrations
- Platform-specific APIs
3. **Review authentication/authorization**
- How are users authenticated?
- How is access controlled?
- Are there privilege escalation risks?
4. **Check encryption/cryptography**
- What encryption is used?
- How are keys managed?
- Is key derivation secure?
- Are there downgrade attacks possible?
**Output**: Security context map with attack surface identified
---
### Phase 2: Threat Modeling (15 minutes)
**Objective**: Apply STRIDE methodology to identify threats
**STRIDE Framework**:
#### S - Spoofing Identity
**Question**: Can an attacker impersonate another user?
**Check for**:
- Weak authentication
- Missing signature verification
- Predictable tokens/IDs
- Session hijacking risks
**Application-specific considerations**:
- Token/session strength
- Authentication mechanism security
- Identity verification methods
#### T - Tampering with Data
**Question**: Can an attacker modify data in transit or at rest?
**Check for**:
- Missing encryption
- Weak encryption algorithms
- Insufficient integrity checks
- Man-in-the-middle risks
**Application-specific considerations**:
- Encryption implementation
- Storage security
- Data integrity verification
- Network security
#### R - Repudiation
**Question**: Can an attacker deny performing an action?
**Check for**:
- Missing audit logs
- No proof of action
- Lack of timestamps
**Application-specific considerations**:
- Audit trail requirements
- Privacy vs. auditability trade-offs
- Regulatory compliance needs
#### I - Information Disclosure
**Question**: Can an attacker access information they shouldn't?
**Check for**:
- Sensitive data in logs
- Error messages revealing system details
- Excessive permissions
- Insecure storage
**Application-specific considerations**:
- Sensitive data identification
- Storage security
- Log security
- Error handling
#### D - Denial of Service
**Question**: Can an attacker make the system unavailable?
**Check for**:
- No rate limiting
- Resource exhaustion
- Infinite loops
- Uncontrolled recursion
**Application-specific considerations**:
- Rate limiting implementation
- Resource constraints
- Input size limits
- Performance considerations
#### E - Elevation of Privilege
**Question**: Can an attacker gain higher privileges?
**Check for**:
- Insufficient authorization checks
- Privilege escalation paths
- Admin backdoors
**Application-specific considerations**:
- Multi-user vs. single-user applications
- Role-based access control
- Platform permission management
**Output**: Threat model with STRIDE categories populated
---
### Phase 3: Vulnerability Analysis (20 minutes)
**Objective**: Identify specific vulnerabilities using OWASP principles
#### OWASP Top 10 Application
**A01:2021 - Broken Access Control**
```javascript
// ❌ WRONG: No access control
const getUserData = (userId) => {
return database.users.find(u => u.id === userId)
// Any user can request any userId
}
// ✅ CORRECT: Verify ownership
const getUserData = (userId, requestingUserId) => {
if (userId !== requestingUserId) {
throw new Error('Unauthorized access')
}
return database.users.find(u => u.id === userId)
}
```
**Application checklist**:
- Verify access control on all data operations
- Check for horizontal privilege escalation (user A accessing user B's data)
- Check for vertical privilege escalation (user becoming admin)
**A02:2021 - Cryptographic Failures**
```javascript
// ❌ WRONG: Weak encryption
const encrypted = btoa(secretData) // Base64 is NOT encryption
// ❌ WRONG: Hardcoded key
const key = '12345678'
const encrypted = encrypt(secretData, key)
// ✅ CORRECT: Strong encryption with proper key management
const key = await deriveKey(masterSecret, salt, iterations)
const encrypted = encryptWithAuthenticatedCipher(data, key)
```
**Application checklist**:
- Check encryption algorithms (no MD5, SHA1, DES, AES-ECB)
- Verify key derivation uses strong KDF (PBKDF2, scrypt, Argon2)
- Ensure sufficient iterations (100k+ for PBKDF2)
- No hardcoded keys or secrets
- Authenticated encryption preferred (GCM, secretbox)
**A03:2021 - Injection**
```javascript
// ❌ WRONG: SQL injection
const query = `SELECT * FROM users WHERE id = ${userId}`
// ❌ WRONG: Command injection
exec(`git commit -m "${message}"`)
// ✅ CORRECT: Parameterized queries
const query = db.prepare('SELECT * FROM users WHERE id = ?')
query.get(userId)
// ✅ CORRECT: Sanitized input
exec('git', ['commit', '-m', sanitize(message)])
```
**Application checklist**:
- Use parameterized queries (never string concatenation)
- Sanitize all user input
- Verify command execution is safe
- Check for NoSQL injection (if using NoSQL)
**A04:2021 - Insecure Design**
**Focus**: Security by design, not bolted on
**Application checklist**:
- Security considered from design phase
- Threat model created before implementation
- Defense in depth strategy applied
- Secure defaults used
- No password reset without proper verification
**A05:2021 - Security Misconfiguration**
```javascript
// ❌ WRONG: Debug mode in production
if (true) { // Debug always on
console.log('Sensitive data:', data)
}
// ✅ CORRECT: Debug only in development
if (process.env.NODE_ENV === 'development') {
console.log('Debug info:', sanitizedData)
}
```
**Application checklist**:
- No debug logging in production
- Environment-specific configurations
- HTTPS enforced (no HTTP fallback)
- Security headers configured (CSP, HSTS, X-Frame-Options)
- Error messages don't expose internals
**A06:2021 - Vulnerable and Outdated Components**
```bash
# Check for vulnerabilities
npm audit
npm audit fix
# Check outdated packages
npm outdated
```
**Application checklist**:
- Run dependency vulnerability scans
- Keep dependencies reasonably current
- No critical vulnerabilities in dependencies
- No unmaintained packages
- Monitor security advisories
**A07:2021 - Identification and Authentication Failures**
```javascript
// ❌ WRONG: Weak password hashing
const hash = md5(password) // MD5 is broken
// ✅ CORRECT: Strong password hashing
const hash = await bcrypt.hash(password, 12) // 12 rounds
```
**Application checklist**:
- Strong password hashing (bcrypt, Argon2)
- Multi-factor authentication (if applicable)
- Session management secure
- No predictable tokens
- Rate limiting on login attempts
**A08:2021 - Software and Data Integrity Failures**
**Focus**: Unsigned updates, insecure deserialization
**Application checklist**:
- App updates from trusted sources
- Verify data integrity (checksums, signatures)
- No deserialization of untrusted data
- Code signing enabled
- Supply chain security considered
**A09:2021 - Security Logging and Monitoring Failures**
```javascript
// ❌ WRONG: No logging of security events
const login = (credentials) => {
return validateCredentials(credentials)
// No log of attempt
}
// ✅ CORRECT: Log security events (but not sensitive data!)
const login = (credentials) => {
const result = validateCredentials(credentials)
if (!result) {
logger.warn('Failed login attempt', { username: credentials.username })
// Don't log the password!
}
return result
}
```
**Application checklist**:
- Log security events (failed auth, suspicious activity)
- Never log passwords, keys, or sensitive data
- Logs are monitored/reviewed
- Alerting on suspicious patterns
- Audit trail for critical operations
**A10:2021 - Server-Side Request Forgery (SSRF)**
**Application checklist**:
- Validate URLs before fetching
- Whitelist allowed domains/IPs
- No user-controlled URLs to internal resources
- Network segmentation where possible
**Output**: Detailed vulnerability report with severity ratings
---
### Phase 4: Platform-Specific Security Review (15 minutes)
**Objective**: Check platform-specific security concerns
#### 1. Web Security
**XSS Prevention**:
```javascript
// ✅ React automatically escapes (safe)
<div>{userInput}</div>
// ❌ WRONG: Dangerous if using dangerouslySetInnerHTML
<div dangerouslySetInnerHTML={{__html: userInput}} />
// ✅ If needed, sanitize first
import DOMPurify from 'dompurify'
<div dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(userInput)}} />
```
**Security checklist**:
- [ ] No dangerouslySetInnerHTML without sanitization
- [ ] No eval() or Function() on user input
- [ ] Content Security Policy configured
- [ ] No inline event handlers
- [ ] HTTPS enforced
**CSRF Prevention**:
- [ ] No state-changing GET requests
- [ ] Anti-CSRF tokens for sessions
- [ ] SameSite cookie attribute
- [ ] Verify Origin/Referer headers
**Storage Security**:
- [ ] localStorage only stores non-sensitive or encrypted data
- [ ] Cookies have Secure and HttpOnly flags
- [ ] No sensitive data in sessionStorage
#### 2. Mobile Platform Security
**iOS-Specific**:
```javascript
// Use Keychain for sensitive data
import * as Keychain from 'react-native-keychain'
await Keychain.setGenericPassword('username', 'password')
```
**Security checklist**:
- [ ] No sensitive data in NSUserDefaults
- [ ] Use Keychain for passwords/keys
- [ ] App Transport Security (ATS) enforced
- [ ] Minimum iOS version for security patches
- [ ] Info.plist permissions minimized
**Android-Specific**:
```java
// Use EncryptedSharedPreferences for sensitive data
```
**Security checklist**:
- [ ] No sensitive data in SharedPreferences
- [ ] Use EncryptedSharedPreferences for sensitive keys
- [ ] Manifest permissions minimized
- [ ] ProGuard/R8 enabled (code obfuscation)
- [ ] android:debuggable=false in production
#### 3. API Security
**Verify endpoint security**:
```javascript
// ✅ HTTPS enforced
const API_URL = 'https://api.example.com'
// ❌ WRONG: HTTP allowed
const API_URL = location.protocol + '//api.example.com' // Can be http!
// ✅ Verify: Authentication required
const headers = {
'Authorization': `Bearer ${token}`,
}
// ✅ Verify: Rate limiting exists (server-side)
```
**Security checklist**:
- [ ] HTTPS enforced (no HTTP fallback)
- [ ] Authentication required on protected endpoints
- [ ] Rate limiting implemented
- [ ] No sensitive data in URLs (use POST body)
- [ ] CORS configured correctly
- [ ] No API keys in client code
#### 4. Third-Party Dependencies
**Audit dependencies**:
```bash
# Check for known vulnerabilities
npm audit
# Check specific package
npm audit <package-name>
# Fix automatically (with caution)
npm audit fix
```
**Security checklist**:
- [ ] No critical vulnerabilities in npm audit
- [ ] Security-critical packages are up-to-date
- [ ] No unmaintained packages (last update >2 years ago)
- [ ] Dependencies from trusted sources
---
### Phase 5: Code Review (20 minutes)
**Objective**: Line-by-line review of security-critical code
#### Focus Areas
**1. Encryption/Cryptography Code**
```javascript
// Check:
// ✅ Using modern authenticated encryption
// ✅ Random nonces/IVs (not reused)
// ✅ Key derivation secure (strong KDF with high iterations)
// ❌ No hardcoded keys
// ❌ No nonce reuse
// ❌ No weak crypto (AES-ECB, DES, MD5, SHA1)
```
**2. Authentication/Authorization Code**
```javascript
// Check:
// ✅ Authentication required for protected resources
// ✅ Authorization checked (user can only access own data)
// ✅ No bypass mechanisms
// ❌ No weak password validation
// ❌ No predictable session IDs
```
**3. Input Validation**
GitHub에서 보기