Cron Job Created or Modified

This rule monitors for (ana)cron jobs being created or renamed. Linux cron jobs are scheduled tasks that can be leveraged by system administrators to set up scheduled tasks, but may be abused by malicious actors for persistence, privilege escalation and command execution. By creating or modifying cron job configurations, attackers can execute malicious commands or scripts at predefined intervals, ensuring their continued presence and enabling unauthorized activities.

Elastic rule (View on GitHub)

  1[metadata]
  2creation_date = "2023/06/09"
  3integration = ["endpoint"]
  4maturity = "production"
  5updated_date = "2024/09/23"
  6
  7[transform]
  8[[transform.osquery]]
  9label = "Osquery - Retrieve File Listing Information"
 10query = """
 11SELECT * FROM file WHERE (path LIKE '/etc/cron.allow.d/%' OR path LIKE '/etc/cron.d/%' OR path LIKE '/etc/cron.hourly/%'
 12OR path LIKE '/etc/cron.daily/%' OR path LIKE '/etc/cron.weekly/%' OR path LIKE '/etc/cron.monthly/%' OR path LIKE
 13'/var/spool/cron/crontabs/%')
 14"""
 15
 16[[transform.osquery]]
 17label = "Osquery - Retrieve Cron File Information"
 18query = "SELECT * FROM file WHERE (path = '/etc/cron.allow' OR path = '/etc/cron.deny' OR path = '/etc/crontab')\n"
 19
 20[[transform.osquery]]
 21label = "Osquery - Retrieve Additional File Listing Information"
 22query = """
 23SELECT f.path, u.username AS file_owner, g.groupname AS group_owner, datetime(f.atime, 'unixepoch') AS
 24file_last_access_time, datetime(f.mtime, 'unixepoch') AS file_last_modified_time, datetime(f.ctime, 'unixepoch') AS
 25file_last_status_change_time, datetime(f.btime, 'unixepoch') AS file_created_time, f.size AS size_bytes FROM file f LEFT
 26JOIN users u ON f.uid = u.uid LEFT JOIN groups g ON f.gid = g.gid WHERE ( path LIKE '/etc/cron.allow.d/%' OR path LIKE
 27'/etc/cron.d/%' OR path LIKE '/etc/cron.hourly/%' OR path LIKE '/etc/cron.daily/%' OR path LIKE '/etc/cron.weekly/%' OR
 28path LIKE '/etc/cron.monthly/%' OR path LIKE '/var/spool/cron/crontabs/%')
 29"""
 30
 31[[transform.osquery]]
 32label = "Osquery - Retrieve Running Processes by User"
 33query = "SELECT pid, username, name FROM processes p JOIN users u ON u.uid = p.uid ORDER BY username"
 34
 35[[transform.osquery]]
 36label = "Osquery - Retrieve Listening Ports"
 37query = "SELECT pid, address, port, socket, protocol, path FROM listening_ports"
 38
 39[[transform.osquery]]
 40label = "Osquery - Retrieve Open Sockets"
 41query = "SELECT pid, family, remote_address, remote_port, socket, state FROM process_open_sockets"
 42
 43[[transform.osquery]]
 44label = "Osquery - Retrieve Information for a Specific User"
 45query = "SELECT * FROM users WHERE username = {{user.name}}"
 46
 47[[transform.osquery]]
 48label = "Osquery - Investigate the Account Authentication Status"
 49query = "SELECT * FROM logged_in_users WHERE user = {{user.name}}"
 50
 51
 52[rule]
 53author = ["Elastic"]
 54description = """
 55This rule monitors for (ana)cron jobs being created or renamed. Linux cron jobs are scheduled tasks that can be
 56leveraged by system administrators to set up scheduled tasks, but may be abused by malicious actors for persistence,
 57privilege escalation and command execution. By creating or modifying cron job configurations, attackers can execute
 58malicious commands or scripts at predefined intervals, ensuring their continued presence and enabling unauthorized
 59activities.
 60"""
 61from = "now-9m"
 62index = ["logs-endpoint.events.file*"]
 63language = "eql"
 64license = "Elastic License v2"
 65name = "Cron Job Created or Modified"
 66note = """## Triage and analysis
 67
 68### Investigating Cron Job Created or Modified
 69Linux cron jobs are scheduled tasks that run at specified intervals or times, managed by the cron daemon. 
 70
 71By creating or modifying cron job configurations, attackers can execute malicious commands or scripts at predefined intervals, ensuring their continued presence and enabling unauthorized activities.
 72
 73This rule monitors the creation of cron jobs by monitoring for file creation and rename events in the most common cron job task location directories.
 74
 75> **Note**:
 76> This investigation guide uses the [Osquery Markdown Plugin](https://www.elastic.co/guide/en/security/master/invest-guide-run-osquery.html) introduced in Elastic Stack version 8.5.0. Older Elastic Stack versions will display unrendered Markdown in this guide.
 77> This investigation guide uses [placeholder fields](https://www.elastic.co/guide/en/security/current/osquery-placeholder-fields.html) to dynamically pass alert data into Osquery queries. Placeholder fields were introduced in Elastic Stack version 8.7.0. If you're using Elastic Stack version 8.6.0 or earlier, you'll need to manually adjust this investigation guide's queries to ensure they properly run.
 78
 79#### Possible Investigation Steps
 80
 81- Investigate the cron job file that was created or modified.
 82- Investigate whether any other files in any of the available cron job directories have been altered through OSQuery.
 83  - $osquery_0
 84  - $osquery_1
 85  - $osquery_2
 86- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for prevalence and whether they are located in expected locations.
 87  - $osquery_3
 88- Investigate other alerts associated with the user/host during the past 48 hours.
 89- Validate the activity is not related to planned patches, updates, network administrator activity, or legitimate software installations.
 90- Investigate whether the altered scripts call other malicious scripts elsewhere on the file system. 
 91  - If scripts or executables were dropped, retrieve the files and determine if they are malicious:
 92    - Use a private sandboxed malware analysis system to perform analysis.
 93      - Observe and collect information about the following activities:
 94        - Attempts to contact external domains and addresses.
 95          - Check if the domain is newly registered or unexpected.
 96          - Check the reputation of the domain or IP address.
 97        - File access, modification, and creation activities.
 98- Investigate abnormal behaviors by the subject process/user such as network connections, file modifications, and any other spawned child processes.
 99  - Investigate listening ports and open sockets to look for potential command and control traffic or data exfiltration.
100    - $osquery_4
101    - $osquery_5
102  - Identify the user account that performed the action, analyze it, and check whether it should perform this kind of action.
103    - $osquery_6
104- Investigate whether the user is currently logged in and active.
105    - $osquery_7
106
107### False Positive Analysis
108
109- If this activity is related to new benign software installation activity, consider adding exceptions — preferably with a combination of user and command line conditions.
110- If this activity is related to a system administrator who uses cron jobs for administrative purposes, consider adding exceptions for this specific administrator user account. 
111- Try to understand the context of the execution by thinking about the user, machine, or business purpose. A small number of endpoints, such as servers with unique software, might appear unusual but satisfy a specific business need.
112
113### Related Rules
114
115- Suspicious File Creation in /etc for Persistence - 1c84dd64-7e6c-4bad-ac73-a5014ee37042
116- Potential Persistence Through Run Control Detected - 0f4d35e4-925e-4959-ab24-911be207ee6f
117- Potential Persistence Through init.d Detected - 474fd20e-14cc-49c5-8160-d9ab4ba16c8b
118- Systemd Timer Created - 7fb500fa-8e24-4bd1-9480-2a819352602c
119- Systemd Service Created - 17b0a495-4d9f-414c-8ad0-92f018b8e001
120
121### Response and remediation
122
123- Initiate the incident response process based on the outcome of the triage.
124- Isolate the involved host to prevent further post-compromise behavior.
125- If the triage identified malware, search the environment for additional compromised hosts.
126  - Implement temporary network rules, procedures, and segmentation to contain the malware.
127  - Stop suspicious processes.
128  - Immediately block the identified indicators of compromise (IoCs).
129  - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that attackers could use to reinfect the system.
130- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are identified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business systems, and web services.
131- Delete the service/timer or restore its original configuration.
132- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and malware components.
133- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.
134- Leverage the incident response data and logging to improve the mean time to detect (MTTD) and the mean time to respond (MTTR).
135"""
136references = [
137    "https://pberba.github.io/security/2022/01/30/linux-threat-hunting-for-persistence-systemd-timers-cron/",
138    "https://www.elastic.co/security-labs/primer-on-persistence-mechanisms",
139]
140risk_score = 47
141rule_id = "ff10d4d8-fea7-422d-afb1-e5a2702369a9"
142setup = """## Setup
143
144This rule requires data coming in from Elastic Defend.
145
146### Elastic Defend Integration Setup
147Elastic Defend is integrated into the Elastic Agent using Fleet. Upon configuration, the integration allows the Elastic Agent to monitor events on your host and send data to the Elastic Security app.
148
149#### Prerequisite Requirements:
150- Fleet is required for Elastic Defend.
151- To configure Fleet Server refer to the [documentation](https://www.elastic.co/guide/en/fleet/current/fleet-server.html).
152
153#### The following steps should be executed in order to add the Elastic Defend integration on a Linux System:
154- Go to the Kibana home page and click "Add integrations".
155- In the query bar, search for "Elastic Defend" and select the integration to see more details about it.
156- Click "Add Elastic Defend".
157- Configure the integration name and optionally add a description.
158- Select the type of environment you want to protect, either "Traditional Endpoints" or "Cloud Workloads".
159- Select a configuration preset. Each preset comes with different default settings for Elastic Agent, you can further customize these later by configuring the Elastic Defend integration policy. [Helper guide](https://www.elastic.co/guide/en/security/current/configure-endpoint-integration-policy.html).
160- We suggest selecting "Complete EDR (Endpoint Detection and Response)" as a configuration setting, that provides "All events; all preventions"
161- Enter a name for the agent policy in "New agent policy name". If other agent policies already exist, you can click the "Existing hosts" tab and select an existing policy instead.
162For more details on Elastic Agent configuration settings, refer to the [helper guide](https://www.elastic.co/guide/en/fleet/8.10/agent-policy.html).
163- Click "Save and Continue".
164- To complete the integration, select "Add Elastic Agent to your hosts" and continue to the next section to install the Elastic Agent on your hosts.
165For more details on Elastic Defend refer to the [helper guide](https://www.elastic.co/guide/en/security/current/install-endpoint.html).
166"""
167severity = "medium"
168tags = [
169    "Domain: Endpoint",
170    "OS: Linux",
171    "Use Case: Threat Detection",
172    "Tactic: Persistence",
173    "Tactic: Privilege Escalation",
174    "Tactic: Execution",
175    "Data Source: Elastic Defend",
176]
177timestamp_override = "event.ingested"
178type = "eql"
179
180query = '''
181file where host.os.type == "linux" and
182event.action in ("rename", "creation") and file.path : (
183  "/etc/cron.allow", "/etc/cron.deny", "/etc/cron.d/*", "/etc/cron.hourly/*", "/etc/cron.daily/*", "/etc/cron.weekly/*",
184  "/etc/cron.monthly/*", "/etc/crontab", "/var/spool/cron/crontabs/*", "/var/spool/anacron/*"
185) and not (
186  process.executable in (
187    "/bin/dpkg", "/usr/bin/dpkg", "/bin/dockerd", "/usr/bin/dockerd", "/usr/sbin/dockerd", "/bin/microdnf",
188    "/usr/bin/microdnf", "/bin/rpm", "/usr/bin/rpm", "/bin/snapd", "/usr/bin/snapd", "/bin/yum", "/usr/bin/yum",
189    "/bin/dnf", "/usr/bin/dnf", "/bin/podman", "/usr/bin/podman", "/bin/dnf-automatic", "/usr/bin/dnf-automatic",
190    "/bin/pacman", "/usr/bin/pacman", "/usr/bin/dpkg-divert", "/bin/dpkg-divert", "/sbin/apk", "/usr/sbin/apk",
191    "/usr/local/sbin/apk", "/usr/bin/apt", "/usr/sbin/pacman", "/bin/podman", "/usr/bin/podman", "/usr/bin/puppet",
192    "/bin/puppet", "/opt/puppetlabs/puppet/bin/puppet", "/usr/bin/chef-client", "/bin/chef-client",
193    "/bin/autossl_check", "/usr/bin/autossl_check", "/proc/self/exe", "/dev/fd/*",  "/usr/bin/pamac-daemon",
194    "/bin/pamac-daemon", "/usr/local/bin/dockerd", "/opt/elasticbeanstalk/bin/platform-engine",
195    "/opt/puppetlabs/puppet/bin/ruby", "/usr/libexec/platform-python", "/opt/imunify360/venv/bin/python3",
196    "/opt/eset/efs/lib/utild", "/usr/sbin/anacron", "/usr/bin/podman", "/kaniko/kaniko-executor"
197  ) or
198  file.path : "/var/spool/cron/crontabs/tmp.*" or
199  file.extension in ("swp", "swpx", "swx", "dpkg-remove") or
200  file.Ext.original.extension == "dpkg-new" or
201  process.executable : (
202    "/nix/store/*", "/var/lib/dpkg/*", "/tmp/vmis.*", "/snap/*", "/dev/fd/*", "/usr/libexec/platform-python*"
203  ) or
204  process.executable == null or
205  process.name in ("crontab", "crond", "executor", "puppet", "droplet-agent.postinst", "cf-agent") or
206  (process.name == "sed" and file.name : "sed*") or
207  (process.name == "perl" and file.name : "e2scrub_all.tmp*") 
208)
209'''
210
211
212[[rule.threat]]
213framework = "MITRE ATT&CK"
214[[rule.threat.technique]]
215id = "T1053"
216name = "Scheduled Task/Job"
217reference = "https://attack.mitre.org/techniques/T1053/"
218[[rule.threat.technique.subtechnique]]
219id = "T1053.003"
220name = "Cron"
221reference = "https://attack.mitre.org/techniques/T1053/003/"
222
223
224
225[rule.threat.tactic]
226id = "TA0003"
227name = "Persistence"
228reference = "https://attack.mitre.org/tactics/TA0003/"
229[[rule.threat]]
230framework = "MITRE ATT&CK"
231[[rule.threat.technique]]
232id = "T1053"
233name = "Scheduled Task/Job"
234reference = "https://attack.mitre.org/techniques/T1053/"
235[[rule.threat.technique.subtechnique]]
236id = "T1053.003"
237name = "Cron"
238reference = "https://attack.mitre.org/techniques/T1053/003/"
239
240
241
242[rule.threat.tactic]
243id = "TA0004"
244name = "Privilege Escalation"
245reference = "https://attack.mitre.org/tactics/TA0004/"
246[[rule.threat]]
247framework = "MITRE ATT&CK"
248[[rule.threat.technique]]
249id = "T1053"
250name = "Scheduled Task/Job"
251reference = "https://attack.mitre.org/techniques/T1053/"
252[[rule.threat.technique.subtechnique]]
253id = "T1053.003"
254name = "Cron"
255reference = "https://attack.mitre.org/techniques/T1053/003/"
256
257
258
259[rule.threat.tactic]
260id = "TA0002"
261name = "Execution"
262reference = "https://attack.mitre.org/tactics/TA0002/"

Triage and analysis

Investigating Cron Job Created or Modified

Linux cron jobs are scheduled tasks that run at specified intervals or times, managed by the cron daemon.

By creating or modifying cron job configurations, attackers can execute malicious commands or scripts at predefined intervals, ensuring their continued presence and enabling unauthorized activities.

This rule monitors the creation of cron jobs by monitoring for file creation and rename events in the most common cron job task location directories.

Note: This investigation guide uses the Osquery Markdown Plugin introduced in Elastic Stack version 8.5.0. Older Elastic Stack versions will display unrendered Markdown in this guide. This investigation guide uses placeholder fields to dynamically pass alert data into Osquery queries. Placeholder fields were introduced in Elastic Stack version 8.7.0. If you're using Elastic Stack version 8.6.0 or earlier, you'll need to manually adjust this investigation guide's queries to ensure they properly run.

Possible Investigation Steps

  • Investigate the cron job file that was created or modified.
  • Investigate whether any other files in any of the available cron job directories have been altered through OSQuery.
    • $osquery_0
    • $osquery_1
    • $osquery_2
  • Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for prevalence and whether they are located in expected locations.
    • $osquery_3
  • Investigate other alerts associated with the user/host during the past 48 hours.
  • Validate the activity is not related to planned patches, updates, network administrator activity, or legitimate software installations.
  • Investigate whether the altered scripts call other malicious scripts elsewhere on the file system.
    • If scripts or executables were dropped, retrieve the files and determine if they are malicious:
      • Use a private sandboxed malware analysis system to perform analysis.
        • Observe and collect information about the following activities:
          • Attempts to contact external domains and addresses.
            • Check if the domain is newly registered or unexpected.
            • Check the reputation of the domain or IP address.
          • File access, modification, and creation activities.
  • Investigate abnormal behaviors by the subject process/user such as network connections, file modifications, and any other spawned child processes.
    • Investigate listening ports and open sockets to look for potential command and control traffic or data exfiltration.
      • $osquery_4
      • $osquery_5
    • Identify the user account that performed the action, analyze it, and check whether it should perform this kind of action.
      • $osquery_6
  • Investigate whether the user is currently logged in and active.
    • $osquery_7

False Positive Analysis

  • If this activity is related to new benign software installation activity, consider adding exceptions — preferably with a combination of user and command line conditions.
  • If this activity is related to a system administrator who uses cron jobs for administrative purposes, consider adding exceptions for this specific administrator user account.
  • Try to understand the context of the execution by thinking about the user, machine, or business purpose. A small number of endpoints, such as servers with unique software, might appear unusual but satisfy a specific business need.
  • Suspicious File Creation in /etc for Persistence - 1c84dd64-7e6c-4bad-ac73-a5014ee37042
  • Potential Persistence Through Run Control Detected - 0f4d35e4-925e-4959-ab24-911be207ee6f
  • Potential Persistence Through init.d Detected - 474fd20e-14cc-49c5-8160-d9ab4ba16c8b
  • Systemd Timer Created - 7fb500fa-8e24-4bd1-9480-2a819352602c
  • Systemd Service Created - 17b0a495-4d9f-414c-8ad0-92f018b8e001

Response and remediation

  • Initiate the incident response process based on the outcome of the triage.
  • Isolate the involved host to prevent further post-compromise behavior.
  • If the triage identified malware, search the environment for additional compromised hosts.
    • Implement temporary network rules, procedures, and segmentation to contain the malware.
    • Stop suspicious processes.
    • Immediately block the identified indicators of compromise (IoCs).
    • Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that attackers could use to reinfect the system.
  • Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are identified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business systems, and web services.
  • Delete the service/timer or restore its original configuration.
  • Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and malware components.
  • Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.
  • Leverage the incident response data and logging to improve the mean time to detect (MTTD) and the mean time to respond (MTTR).

References

Related rules

to-top