sf-agent-framework
Version:
AI Agent Orchestration Framework for Salesforce Development - Two-phase architecture with 70% context reduction
629 lines (473 loc) • 15.2 kB
Markdown
# Salesforce Threat Catalog
## Overview
This comprehensive threat catalog identifies potential security threats specific
to Salesforce implementations, their impact, and mitigation strategies.
## Threat Categories
### Authentication Threats
#### T-AUTH-001: Brute Force Attack
**Description**: Automated attempts to guess user credentials
**Attack Vectors**:
- Login page attacks
- API authentication endpoints
- Password reset mechanisms
- Security questions
**Impact**:
- Unauthorized access
- Account lockouts
- Service disruption
- Data breach
**Indicators**:
```sql
-- Detection query
SELECT Username, COUNT(*) as FailedAttempts,
MIN(LoginTime) as FirstAttempt,
MAX(LoginTime) as LastAttempt
FROM LoginHistory
WHERE Status = 'Failed'
AND LoginTime > System.now().addHours(-1)
GROUP BY Username
HAVING COUNT(*) > 5
```
**Mitigations**:
- Enforce strong password policies
- Implement account lockout policies
- Enable MFA for all users
- Monitor failed login attempts
- Use CAPTCHA after failures
- Implement rate limiting
#### T-AUTH-002: Session Hijacking
**Description**: Theft or manipulation of valid session tokens
**Attack Vectors**:
- XSS attacks to steal cookies
- Man-in-the-middle attacks
- Session fixation
- Cross-site request forgery
**Technical Details**:
```javascript
// Vulnerable code example
document.cookie = 'sid=' + sessionId; // No secure flag
// Secure implementation
document.cookie = 'sid=' + sessionId + '; secure; httpOnly; sameSite=strict';
```
**Mitigations**:
- Use secure session cookies
- Implement session timeout
- Bind sessions to IP addresses
- Regenerate session IDs
- Enable clickjack protection
#### T-AUTH-003: Credential Stuffing
**Description**: Using leaked credentials from other breaches
**Attack Pattern**:
```python
# Attack simulation
for credential in leaked_database:
try:
login(credential.username, credential.password)
if success:
compromised_accounts.append(credential)
except:
continue
```
**Mitigations**:
- Implement MFA
- Monitor for unusual login patterns
- Use threat intelligence feeds
- Educate users on password reuse
- Implement device fingerprinting
### Authorization Threats
#### T-AUTHZ-001: Privilege Escalation
**Description**: Gaining higher privileges than authorized
**Attack Vectors**:
- Profile manipulation
- Permission set exploitation
- Role hierarchy abuse
- API parameter tampering
**Example Vulnerability**:
```apex
// Vulnerable code
public without sharing class DataAccess {
public static List<Account> getAccounts() {
return [SELECT Id, Name, AnnualRevenue FROM Account];
// No access checks!
}
}
// Secure code
public with sharing class DataAccess {
public static List<Account> getAccounts() {
if(!Schema.sObjectType.Account.isAccessible()) {
throw new SecurityException('Insufficient privileges');
}
return [SELECT Id, Name FROM Account WITH SECURITY_ENFORCED];
}
}
```
**Mitigations**:
- Use "with sharing" keyword
- Implement CRUD/FLS checks
- Regular permission audits
- Principle of least privilege
- Monitor permission changes
#### T-AUTHZ-002: Sharing Violation
**Description**: Accessing records beyond intended scope
**Attack Scenarios**:
- URL parameter manipulation
- SOQL injection to bypass sharing
- Apex class without sharing
- Manual share exploitation
**Detection**:
```apex
// Monitor for sharing violations
trigger DetectSharingViolation on Account (after update) {
for(Account acc : Trigger.new) {
if(acc.OwnerId != Trigger.oldMap.get(acc.Id).OwnerId) {
// Check if user has legitimate access
if(!hasLegitimateAccess(UserInfo.getUserId(), acc.Id)) {
createSecurityAlert('Potential sharing violation', acc.Id);
}
}
}
}
```
### Data Security Threats
#### T-DATA-001: Data Exfiltration
**Description**: Unauthorized extraction of sensitive data
**Attack Methods**:
- Mass data export
- API scraping
- Report manipulation
- Screen scraping
- Email forwarding
**Detection Patterns**:
```apex
public class DataExfiltrationDetector {
public static void detectAnomalousExport(Id userId) {
// Check for unusual export patterns
Integer recentExports = [SELECT COUNT()
FROM DataExport__c
WHERE User__c = :userId
AND CreatedDate = LAST_N_HOURS:1];
if(recentExports > 10) {
createAlert('Potential data exfiltration', userId);
}
// Check for large volume queries
List<ApexLog> logs = [SELECT Id, Operation
FROM ApexLog
WHERE LogUserId = :userId
AND Operation LIKE '%SELECT%'
AND DurationMilliseconds > 10000];
if(!logs.isEmpty()) {
analyzeQueryPatterns(logs);
}
}
}
```
**Mitigations**:
- Implement data loss prevention
- Monitor export activities
- Limit API access
- Use field-level security
- Enable event monitoring
#### T-DATA-002: SQL/SOQL Injection
**Description**: Malicious query manipulation
**Vulnerable Code**:
```apex
// NEVER DO THIS!
public static List<Account> searchAccounts(String searchTerm) {
String query = 'SELECT Id, Name FROM Account WHERE Name LIKE \'%' + searchTerm + '%\'';
return Database.query(query);
}
// Secure implementation
public static List<Account> searchAccounts(String searchTerm) {
String wildcardSearchTerm = '%' + String.escapeSingleQuotes(searchTerm) + '%';
return [SELECT Id, Name FROM Account WHERE Name LIKE :wildcardSearchTerm];
}
```
**Attack Examples**:
```sql
-- Malicious input: ' OR Id != null--
-- Results in: SELECT Id, Name FROM Account WHERE Name LIKE '%' OR Id != null--%'
```
**Mitigations**:
- Use bind variables
- Escape user input
- Validate input patterns
- Use static SOQL when possible
- Implement query governors
### Application Security Threats
#### T-APP-001: Cross-Site Scripting (XSS)
**Description**: Injection of malicious scripts
**Attack Vectors**:
- Visualforce pages
- Lightning components
- Custom HTML
- Unescaped merge fields
**Vulnerable Examples**:
```html
<!-- Visualforce vulnerability -->
<apex:page>
<div>{!$CurrentPage.parameters.userInput}</div>
<!-- Dangerous! -->
</apex:page>
<!-- Secure version -->
<apex:page>
<div>{!HTMLENCODE($CurrentPage.parameters.userInput)}</div>
</apex:page>
```
```javascript
// Lightning vulnerability
component.set('v.htmlContent', userInput); // Dangerous!
// Secure version
component.set('v.htmlContent', $A.util.escapeHTML(userInput));
```
**Mitigations**:
- Enable LockerService
- Use HTMLENCODE/JSENCODE
- Validate all input
- Use CSP headers
- Regular security scanning
#### T-APP-002: Cross-Site Request Forgery (CSRF)
**Description**: Forcing authenticated users to execute unwanted actions
**Attack Scenario**:
```html
<!-- Malicious site -->
<img src="https://instance.salesforce.com/apex/deleteRecord?id=001XX000003DHPh" />
```
**Protection Implementation**:
```apex
public class CSRFProtection {
public static Boolean validateToken(String token) {
String expectedToken = generateToken();
return Crypto.verifyHMac(
'HmacSHA256',
Blob.valueOf(token),
Blob.valueOf(expectedToken)
);
}
private static String generateToken() {
return EncodingUtil.base64Encode(
Crypto.generateDigest(
'SHA256',
Blob.valueOf(UserInfo.getSessionId() + UserInfo.getUserId())
)
);
}
}
```
### Integration Security Threats
#### T-INT-001: API Abuse
**Description**: Excessive or malicious API usage
**Attack Patterns**:
- Rate limit exploitation
- Resource exhaustion
- Data harvesting
- Service disruption
**Monitoring**:
```apex
@RestResource(urlMapping='/api/secure/*')
global class SecureAPI {
global class RateLimiter {
private static final Integer MAX_REQUESTS = 100;
private static final Integer TIME_WINDOW = 3600; // seconds
public static Boolean checkLimit(String clientId) {
String key = 'rate_limit:' + clientId;
Integer count = Cache.Org.get(key);
if(count == null) {
count = 0;
}
if(count >= MAX_REQUESTS) {
logRateLimitViolation(clientId);
return false;
}
Cache.Org.put(key, count + 1, TIME_WINDOW);
return true;
}
}
}
```
#### T-INT-002: Man-in-the-Middle
**Description**: Interception of communication
**Attack Vectors**:
- Unencrypted connections
- Certificate spoofing
- DNS hijacking
- Proxy attacks
**Secure Implementation**:
```apex
public class SecureCallout {
public static HttpResponse makeSecureCallout(String endpoint, String body) {
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
// Certificate pinning
req.setClientCertificateName('ClientCert');
// Timeout to prevent hanging
req.setTimeout(30000);
// Verify SSL
req.setCompressed(false);
Http http = new Http();
HttpResponse res = http.send(req);
// Verify response
if(res.getStatusCode() != 200) {
throw new CalloutException('Unexpected response: ' + res.getStatusCode());
}
return res;
}
}
```
### Infrastructure Threats
#### T-INFRA-001: Denial of Service
**Description**: Overwhelming system resources
**Attack Types**:
- API flooding
- Complex query attacks
- Governor limit exploitation
- Batch job abuse
**Protection Measures**:
```apex
public class DDoSProtection {
// Implement circuit breaker pattern
private static Map<String, CircuitBreaker> breakers = new Map<String, CircuitBreaker>();
public class CircuitBreaker {
private Integer failureCount = 0;
private DateTime lastFailureTime;
private final Integer threshold = 5;
private final Integer timeout = 60; // seconds
public Boolean isOpen() {
if(failureCount >= threshold) {
if(DateTime.now().getTime() - lastFailureTime.getTime() > timeout * 1000) {
reset();
return false;
}
return true;
}
return false;
}
public void recordFailure() {
failureCount++;
lastFailureTime = DateTime.now();
}
public void reset() {
failureCount = 0;
lastFailureTime = null;
}
}
}
```
### Social Engineering Threats
#### T-SOCIAL-001: Phishing
**Description**: Deceptive attempts to obtain credentials
**Common Techniques**:
- Fake login pages
- Email spoofing
- SMS phishing
- Voice phishing
- Watering hole attacks
**User Education Topics**:
- Verify sender authenticity
- Check URLs carefully
- Never share credentials
- Report suspicious activity
- Use official channels
### Insider Threats
#### T-INSIDER-001: Malicious Insider
**Description**: Authorized user with malicious intent
**Risk Indicators**:
```apex
public class InsiderThreatDetector {
public static void analyzeUserBehavior(Id userId) {
// Unusual access patterns
Integer unusualAccess = [SELECT COUNT()
FROM LoginHistory
WHERE UserId = :userId
AND LoginTime.hour() NOT IN (8,9,10,11,12,13,14,15,16,17)
AND CreatedDate = LAST_N_DAYS:7];
// Large data access
Integer bulkQueries = [SELECT COUNT()
FROM DataAccessLog__c
WHERE User__c = :userId
AND Records_Accessed__c > 1000
AND CreatedDate = TODAY];
// Permission changes
Integer permChanges = [SELECT COUNT()
FROM SetupAuditTrail
WHERE CreatedById = :userId
AND Action LIKE '%Permission%'
AND CreatedDate = LAST_N_DAYS:1];
if(unusualAccess > 5 || bulkQueries > 10 || permChanges > 0) {
createRiskAlert(userId, 'Potential insider threat');
}
}
}
```
## Threat Mitigation Framework
### Preventive Controls
1. **Access Management**: Strong authentication, least privilege
2. **Input Validation**: Sanitize all user input
3. **Encryption**: Protect data at rest and in transit
4. **Security Training**: Regular user education
5. **Secure Development**: Follow security best practices
### Detective Controls
1. **Monitoring**: Real-time security monitoring
2. **Logging**: Comprehensive audit trails
3. **Analytics**: Behavioral analysis
4. **Alerts**: Automated threat detection
5. **Reviews**: Regular security assessments
### Corrective Controls
1. **Incident Response**: Defined procedures
2. **Isolation**: Contain threats quickly
3. **Recovery**: Restore normal operations
4. **Investigation**: Root cause analysis
5. **Improvement**: Update controls based on lessons learned
## Threat Intelligence Integration
### External Threat Feeds
```apex
public class ThreatIntelligence {
@future(callout=true)
public static void checkThreatFeeds() {
// Check IP reputation
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.threatintel.com/check');
req.setMethod('POST');
req.setBody(JSON.serialize(getRecentIPs()));
HttpResponse res = http.send(req);
if(res.getStatusCode() == 200) {
processThreatData(res.getBody());
}
}
private static void processThreatData(String threatData) {
Map<String, Object> threats = (Map<String, Object>)JSON.deserializeUntyped(threatData);
for(String ip : threats.keySet()) {
Map<String, Object> threat = (Map<String, Object>)threats.get(ip);
if((Boolean)threat.get('malicious')) {
blockIP(ip);
notifySecurityTeam(ip, threat);
}
}
}
}
```
## Risk Scoring
### Threat Risk Matrix
```
Risk = Likelihood × Impact
Likelihood Levels:
- Very High (5): Daily occurrence
- High (4): Weekly occurrence
- Medium (3): Monthly occurrence
- Low (2): Yearly occurrence
- Very Low (1): Rare occurrence
Impact Levels:
- Critical (5): Complete system compromise
- High (4): Major data breach
- Medium (3): Limited data exposure
- Low (2): Minor disruption
- Minimal (1): No significant impact
```
## Continuous Improvement
1. **Regular Updates**: Keep threat catalog current
2. **Threat Modeling**: Identify new threats
3. **Penetration Testing**: Validate controls
4. **Incident Analysis**: Learn from breaches
5. **Industry Collaboration**: Share threat intelligence