DEV Community

hailports
hailports

Posted on

I Automated My Entire Salesforce Security Review — Here's the Script

I Automated My Entire Salesforce Security Review — Here's the Script

As a senior Salesforce administrator, one of my primary responsibilities is ensuring that our organization’s Salesforce environment is secure. This involves conducting regular security reviews to identify and mitigate risks such as data leaks, unauthorized access, and misconfigurations. Traditionally, these reviews were time-consuming and required manual effort. However, I recently automated the entire process using Apex code and SOQL queries. In this article, I’ll walk you through how I did it, including the steps and sample code.

Introduction

Salesforce is a powerful platform with numerous security features, but maintaining them requires diligence. Automated tools can help streamline the process, ensuring that no stone is left unturned during our regular reviews. By leveraging Apex and SOQL, we can create scripts that automate various aspects of the review, making it more efficient and accurate.

Setting Up the Environment

Before diving into the automation script, ensure you have a development org or sandbox where you can test your code. You should also have access to System permissions, which are required for running Apex jobs and querying certain objects.

Prerequisites

  • Development Org: Access to a Salesforce Development Organization.
  • Apex Editor: Familiarity with the Salesforce Developer Console or any preferred IDE (e.g., VS Code).
  • API Enabled: Ensure that API access is enabled in your org.

Step 1: Define the Scope

First, identify the scope of your security review. For this example, we’ll focus on a few key areas:

  1. User and Profile Permissions
  2. Field-Level Security (FLS)
  3. Sharing Rules
  4. Apex Triggers

Step 2: Create the Apex Class

We'll create an Apex class that will perform the necessary queries and checks.

public class SecurityReview {

    // Method to check user and profile permissions
    public static List<User> checkUserPermissions() {
        return [SELECT Id, Username, Profile.Name FROM User WHERE Profile.Name = 'System Admin' AND isActive = true];
    }

    // Method to check field-level security
    public static List<SObjectFieldPermissions> checkFLS() {
        return [SELECT SobjectType, Field, PermissionsRead, PermissionsCreate, PermissionsEdit, PermissionsDelete 
                FROM FieldPermissions 
                WHERE SobjectType IN ('Account', 'Contact', 'Opportunity') AND IsCustom = false];
    }

    // Method to check sharing rules
    public static List<SharingRule> checkSharingRules() {
        return [SELECT Id, Name, RowCause, FolderId, SobjectType FROM SharingRule WHERE RowCause IN ('AutoShare','UserDefined')];
    }

    // Method to check Apex triggers
    public static List<ApexClass> checkApexTriggers() {
        return [SELECT Id, ApiVersion, Body, NamespacePrefix 
                FROM ApexClass 
                WHERE Body LIKE '%trigger%' AND Status = 'Active'];
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Run the Queries

Next, we'll run these queries and log the results. We can use a simple script to execute these methods and store the output.

public class SecurityReviewRunner {

    public static void main() {
        List<User> users = SecurityReview.checkUserPermissions();
        System.debug('Users with System Admin Profile: ' + users);

        List<SObjectFieldPermissions> fls = SecurityReview.checkFLS();
        System.debug('Field-Level Security: ' + fls);

        List<SharingRule> sharingRules = SecurityReview.checkSharingRules();
        System.debug('Sharing Rules: ' + sharingRules);

        List<ApexClass> apexTriggers = SecurityReview.checkApexTriggers();
        System.debug('Apex Triggers: ' + apexTriggers);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Schedule the Script

To automate this process, we can schedule the script to run at regular intervals using a Salesforce Scheduled Apex job.

public class SecurityReviewScheduler implements Schedulable {

    public void execute(SchedulableContext context) {
        // Run the security review
        new SecurityReviewRunner().main();

        // Optionally, send an email or log results to a custom object
    }
}
Enter fullscreen mode Exit fullscreen mode

To schedule this job:

  1. Go to Setup.
  2. Search for "Apex Classes".
  3. Create and save the class.
  4. Navigate to "Developer Console" or use the Salesforce UI to create a new Apex Class named SecurityReviewScheduler.
  5. Paste the above code into the editor.
  6. Save the class.
  7. Go to Setup > Develop > Apex Classes.
  8. Click on SecurityReviewScheduler and click the Run Now button.

Alternatively, you can schedule it using an Apex Anonymous Block:

System.schedule('Security Review', '0 0 * * * ?', new SecurityReviewScheduler());
Enter fullscreen mode Exit fullscreen mode

Step 5: Analyze the Results

After running the script, review the debug logs to identify any security issues. The System.debug statements will output the results of each query.

Example Debug Output

DEBUG|Users with System Admin Profile: (User:{Id=a07E00000012345, Username=admin@example.com, Profile.Name=System Administrator})
DEBUG|Field-Level Security: (SObjectFieldPermissions:[SobjectType=Account, Field=Name, PermissionsRead=true, PermissionsCreate=false, PermissionsEdit=false, PermissionsDelete=false] ... )
DEBUG|Sharing Rules: (SharingRule:[Id=a0aE00000012345, Name=Accounts, RowCause=AutoShare, FolderId=null, SobjectType=Account])
DEBUG|Apex Triggers: (ApexClass:[Id=a2hE00000012345, ApiVersion=56.0, Body=trigger AccountTrigger on Account (before insert, before update), NamespacePrefix=null])
Enter fullscreen mode Exit fullscreen mode

Addressing Issues

Based on the debug output, you can identify and address any security issues:

  • User Permissions: Ensure that only necessary users have access to sensitive profiles.
  • Field-Level Security: Verify that critical fields are properly secured based on business requirements.
  • Sharing Rules: Review and adjust sharing rules to ensure data is shared appropriately.
  • Apex Triggers: Check if triggers handle sensitive operations correctly.

Step 6: Utilize Org Scanner

For a more comprehensive review, consider using tools like Org Scanner (https://orgscanner.dev/?utm_source=devto&utm_medium=content&utm_campaign=free_blitz). This tool can help identify additional security issues and automate the process further. To use it:

  1. Install the Tool: Follow the installation instructions provided by Org Scanner.
  2. Run the Scan: Use the command-line interface to run a full scan of your org.

Example usage:

orgscanner scan --username [YOUR_USERNAME] --password [YOUR_PASSWORD] --security-review
Enter fullscreen mode Exit fullscreen mode

Conclusion

Automating Salesforce security reviews not only saves time but also ensures that critical aspects are consistently checked. By leveraging Apex and SOQL, we can create robust scripts to perform these tasks efficiently.

Try the free scanner at https://orgscanner.dev/?utm_source=devto&utm_medium=content&utm_campaign=free_blitz

Feel free to share your thoughts or any additional tips in the comments below!

Top comments (0)