← Back to Security & Compliance
SEC-018 Security & Compliance 20 min read For: CTOs & Security Operations

Incident Response for Salesforce: What to Do When Something Goes Wrong

Establishing data breach workflows, dynamic session termination mechanisms, and operational response checklists for the CRM.

VS

Vishal Sharma

Salesforce Architecture Specialist · Updated May 2026

What you will learn in this tutorial
  • Understand the shared responsibility model in cloud incident response.
  • Establish immediate containment protocols for compromised API keys and user credentials.
  • Apply architectural isolation strategies to halt active data exfiltration and privilege escalations.
  • Execute systematic forensic investigations using Event Monitoring and Setup Audit Trail.
  • Coordinate post-incident recovery processes and deploy Transaction Security Policies to harden the org.
  • Learn how to programmatically terminate compromised active user sessions in Apex.

1. Developing a Salesforce-Specific Incident Response Framework

In the domain of enterprise SaaS, incident response (IR) requires a radical departure from traditional infrastructure-centric cybersecurity playbooks. When an incident occurs within a Salesforce environment, there are no network subnets to isolate, no physical firewalls to unplug, and no operating system images to roll back. Instead, security teams must navigate a complex, highly integrated cloud application tier. Developing a Salesforce-specific Incident Response Framework is critical to protecting intellectual property, customer data, and maintaining business continuity.

A modern Salesforce IR framework must be constructed upon the foundation of the cloud Shared Responsibility Model. Under this model, Salesforce guarantees the physical security, network routing, infrastructure isolation, and platform availability of the multi-tenant architecture. The customer, however, retains absolute ownership and responsibility for securing the data layer, user access control, profile and permission configurations, API integrations, and the behaviour of custom code. Consequently, when a security anomaly is detected—such as a sudden spike in bulk data exports, unauthorized administrative changes, or credential spraying attacks—the responsibility to detect, contain, investigate, and remediate the incident rests entirely with the customer's architectural and security operations teams.

Specifically, organisations must establish a rigorous triage system to categorise incidents: Priority 1 (P1) incidents represent active data exfiltration or compromised administrative access; Priority 2 (P2) represents suspicious API behaviour or non-compliant permission set assignments; and Priority 3 (P3) represents isolated user credential issues. Additionally, because Salesforce relies heavily on Connected Apps for third-party integrations, the identification phase must include maintaining a comprehensive, up-to-date registry of all API connections. Every integration must have a documented business owner, technical contact, and a clear mapping of the specific data objects it is authorised to access. When an anomaly is detected, this registry allows the incident response team to instantly identify the system owner and determine if the unusual behaviour is a legitimate integration patch or an active, malicious credential compromise.

To operate effectively, the Salesforce IR playbook must define clear trigger criteria and operational phases. These phases align with the standard NIST incident handling cycle but are adapted for SaaS: Identification, Containment, Eradication, Recovery, and Lessons Learned. Identification involves monitoring platform-generated alerts, customer feedback, or anomaly detection engines. Containment demands swift, surgical operations to restrict compromised access without causing collateral damage to critical business processes. Eradication focuses on removing the root cause of the vulnerability, such as correcting a misconfigured guest user profile or revoking a leaked API token. Recovery restores normal operations securely, while the final phase ensures lessons are documented and translated into permanent platform hardening controls.

2. Immediate Containment Protocols: Actions for Credential Compromise

The most frequent security incident in enterprise orgs is credential compromise, spanning hijacked administrator accounts, leaked API integration keys, or stolen employee credentials. When a compromise is identified, every second counts. The primary architectural objective is immediate containment: preventing the attacker from executing further data reads or configuration changes.

When an account is compromised, administrators are faced with two immediate choices: deactivating the user record or freezing the user record. In an active incident, freezing the user is the preferred and safest first action. Deactivating a user record completely disables the user and releases their licence back to the pool. However, Salesforce will block deactivation if the target user has active dependencies in the metadata, such as being the default owner of leads, cases, a running user of an active scheduled Apex job, or a designated workflow user. Resolving these dependencies during an active breach is time-consuming and prone to human error. Freezing the user, by contrast, has zero dependencies. It instantly blocks all login attempts and API access for that user account without altering licensing, metadata associations, or ownership records, providing an immediate and reliable lock on access.

Furthermore, freezing a user is highly advantageous because it does not disrupt the platform's internal operational plumbing. If a user record is deactivated, any active record ownership, lookup relationships, or validation rule criteria referencing that user will throw immediate errors, potentially halting downstream business processes or failing active orders. Freezing acts as an invisible block at the gateway level. From the user's perspective, they are immediately locked out, but from the database's perspective, the user's active associations remain intact. During the containment window, this allows administrators to systematically transfer record ownership, reassign tasks, and update pending approval processes without the pressure of an active security threat disrupting production flows.

Once the account is frozen, the security team must terminate all active sessions associated with that user. Simply freezing a user or changing their password does not automatically terminate existing active OAuth sessions or browser cookies; the attacker could continue to exfiltrate data using their current session token. To eradicate active sessions, administrators must navigate to the Session Management console or programmatically delete the corresponding records from the AuthSession table in Apex. This ensures that the attacker's active tokens are invalidated across all devices and API clients instantly.


// Apex script to programmatically locate and terminate active sessions for a compromised user
public static void terminateUserSessions(String targetUsername) {
    User targetUser = [SELECT Id FROM User WHERE Username = :targetUsername LIMIT 1];
    List activeSessions = [
        SELECT Id, UsersId, SessionType 
        FROM AuthSession 
        WHERE UsersId = :targetUser.Id
    ];
    
    if (!activeSessions.isEmpty()) {
        delete activeSessions;
        System.debug('Successfully terminated ' + activeSessions.size() + ' active sessions for ' + targetUsername);
    } else {
        System.debug('No active sessions found for compromised user.');
    }
}
        

3. Mitigating Active Data Egress and Privilege Escalation Events

Active data egress and privilege escalation represent high-severity incidents that require immediate, broad-spectrum containment strategies. These events typically manifest as an integration account suddenly pulling millions of records, or an internal user account granting themselves administrative profiles via permission sets. Security teams must have the authority and technical knowledge to apply aggressive platform controls to halt these threats.

If an API integration is identified as the source of a bulk data leak, the immediate containment step is to revoke its OAuth authorization and freeze the integration service user. If the leak is occurring via a custom Connected App, the administrator should immediately block the Connected App in the Connected Apps OAuth Usage console, which invalidates all active developer keys and client secrets. If the data leak originates from an unauthenticated public source, such as an Experience Cloud guest user profile, the administrator must immediately disable the public site or restrict the guest user's object permissions to "No Access," halting public egress while a forensic review is conducted.

In privilege escalation scenarios where an unauthorised user has obtained administrative rights, containment requires a systematic rollback of high-risk permissions. The incident response team must immediately run Apex scripts to identify and delete any custom permission sets or permission set groups assigned within the incident window. Furthermore, to prevent lateral movement, administrators can implement a temporary restriction on the corporate network whitelist. By adjusting the Login IP Ranges at the Profile level for all standard and administrative profiles, you can restrict login capability strictly to verified corporate VPN endpoints, effectively locking out any external attackers operating outside the approved network boundary.


// Apex script to identify and revoke high-risk administrative permission assignments
public static void revokeAdminAssignments(Datetime incidentWindowStart) {
    // Find permission set assignments created during the incident window
    List suspectAssignments = [
        SELECT Id, AssigneeId, PermissionSet.Name, PermissionSet.PermissionsModifyAllData 
        FROM PermissionSetAssignment 
        WHERE SystemModstamp >= :incidentWindowStart
        AND (PermissionSet.PermissionsModifyAllData = true OR PermissionSet.PermissionsCustomizeApplication = true)
    ];
    
    if (!suspectAssignments.isEmpty()) {
        delete suspectAssignments;
        System.debug('Revoked ' + suspectAssignments.size() + ' high-risk administrative assignments.');
    }
}
        

4. Forensic Analysis: Leveraging Event Monitoring and Setup Audit Trail

Once the active threat is successfully contained, the incident shifts into the forensic analysis phase. The core objective is to reconstruct a complete, audit-ready timeline of the attacker's activities: what configuration changes they made, what data they queried, what files they downloaded, and how they initially accessed the system.

The first and most direct source of configuration forensics is the Setup Audit Trail. This log captures all modifications made to the organisation's metadata and settings, tracking the date, time, actor, and exact nature of the change. It is invaluable for detecting backdoors, such as the creation of a new administrator account, the creation of an unapproved Remote Site Setting, or the relaxation of session security policies. The Setup Audit Trail stores the last 180 days of metadata history, and can be queried programmatically via SOQL or downloaded as a CSV file.


-- SOQL query to extract recent high-risk metadata modifications from the Setup Audit Trail
SELECT CreatedDate, CreatedBy.Username, Action, Section, Display 
FROM SetupAuditTrail 
WHERE Action LIKE '%Perm%' OR Action LIKE '%Profile%' OR Action LIKE '%Security%'
ORDER BY CreatedDate DESC 
LIMIT 100
        

In addition to Setup Audit Trail, architects must master the interpretation of Event Log Files (ELFs) within Event Monitoring. ELFs provide unmatched granularity by capturing the underlying database operations and REST/SOAP API calls. In the event of a bulk data breach, the ApiAnomalyEvent and CredentialStuffingEvent logs are primary triggers. However, the true forensic gold resides in the ReportExport, BulkApi, and RestApi event types. These logs do not merely capture that a query occurred; they record the exact SOQL statement executed, the columns retrieved, the number of rows returned, and a unique correlation ID (Request ID). By matching the Request ID across the URI log (which tracks standard user page views) and the RestApi log, forensic analysts can trace the exact path the attacker took through the user interface to execute the query, proving whether the data exfiltration was performed via automated scripts or manual, targeted downloads.

5. Post-Incident Recovery, Root Cause Analysis, and Hardening

Eradication and recovery mark the transition from active crisis back to stable business operations. The recovery process involves restoring any deleted metadata, resetting compromised credentials, verifying data integrity, and conducting a thorough Root Cause Analysis (RCA) to ensure the vulnerability is permanently sealed.

If the incident resulted in unauthorised data deletion or modification, the restoration strategy must rely on robust enterprise backup solutions. Standard sandbox seeding tools are insufficient; organisations must leverage native tools like the Salesforce Backup service or enterprise-grade third-party solutions to restore data records along with their parent-child relationships, owner IDs, and system fields. Following restoration, the security team must reset passwords, revoke compromised OAuth tokens, and re-establish secure API connection channels using updated credentials and digital certificates.

The Root Cause Analysis is a collaborative, blame-free post-mortem aimed at uncovering the procedural or technical failures that permitted the breach. The findings must be translated into immediate platform hardening actions. A primary hardening mechanism is the deployment of real-time Transaction Security Policies within Event Monitoring. These policies allow administrators to define Apex-based rules that evaluate user transactions in real-time. For example, a policy can evaluate the volume of records requested in a report export and automatically block the transaction and freeze the user if the request exceeds a pre-defined threshold. By combining continuous monitoring, automated incident response alerts, and regular tabletop exercises, enterprise organisations can transform a security incident into a valuable learning opportunity, permanently strengthening their defense posture against future threats.

Key Takeaways

  • Salesforce incident response operates entirely at the application and database tiers, relying on a shared responsibility model.
  • Freezing a compromised user record is the optimal immediate containment action, bypassing metadata dependencies that block standard deactivation.
  • Terminating compromised user access requires explicit deletion of active sessions in the AuthSession table to invalidate existing OAuth tokens.
  • Active data leaks must be contained aggressively by blocking Connected Apps, disabling public sites, or restricting guest user profile access.
  • Setup Audit Trail and Event Monitoring log files provide critical forensic evidence, capturing metadata changes and precise data query operations.
  • Post-incident containment must culminate in a rigorous Root Cause Analysis and the deployment of preventative Transaction Security Policies.

Checkpoint: Test Your Understanding

Question 1: Why is 'Freezing' a user record preferred over 'Deactivating' it as an immediate containment action during an active account compromise?

A. Freezing immediately deletes all historical data owned by the user, preventing exfiltration.
B. Deactivating a user can be blocked by system dependencies like active workflows, scheduling, or default ownerships, whereas freezing has zero dependencies and blocks access instantly.
C. Freezing automatically alerts the Salesforce infrastructure team to run a forensic sweep.
D. Freezing allows the compromised user to keep logging in but masks all sensitive fields.

Question 2: You suspect an API client is currently exfiltrating data via a Connected App. Which action halts this exfiltration instantly with the least impact on unrelated services?

A. Disabling API Access globally across the entire Salesforce instance.
B. Blocking the specific Connected App in the Connected Apps OAuth Usage console and freezing the associated integration user.
C. Deleting the custom objects being accessed by the API client.
D. Changing the system administrator password for the organisation.

Question 3: Which Salesforce tool is the primary source for forensic evidence showing exactly which data records were exported by a user in a report?

A. Setup Audit Trail
B. Event Monitoring Event Log Files (ELF)
C. Login History console
D. Debug Logs with System level logging level

Discussion & Feedback