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/07/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]
139risk_score = 47
140rule_id = "ff10d4d8-fea7-422d-afb1-e5a2702369a9"
141setup = """## Setup
142
143This rule requires data coming in from Elastic Defend.
144
145### Elastic Defend Integration Setup
146Elastic 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.
147
148#### Prerequisite Requirements:
149- Fleet is required for Elastic Defend.
150- To configure Fleet Server refer to the [documentation](https://www.elastic.co/guide/en/fleet/current/fleet-server.html).
151
152#### The following steps should be executed in order to add the Elastic Defend integration on a Linux System:
153- Go to the Kibana home page and click "Add integrations".
154- In the query bar, search for "Elastic Defend" and select the integration to see more details about it.
155- Click "Add Elastic Defend".
156- Configure the integration name and optionally add a description.
157- Select the type of environment you want to protect, either "Traditional Endpoints" or "Cloud Workloads".
158- 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).
159- We suggest selecting "Complete EDR (Endpoint Detection and Response)" as a configuration setting, that provides "All events; all preventions"
160- 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.
161For more details on Elastic Agent configuration settings, refer to the [helper guide](https://www.elastic.co/guide/en/fleet/8.10/agent-policy.html).
162- Click "Save and Continue".
163- 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.
164For more details on Elastic Defend refer to the [helper guide](https://www.elastic.co/guide/en/security/current/install-endpoint.html).
165"""
166severity = "medium"
167tags = [
168    "Domain: Endpoint",
169    "OS: Linux",
170    "Use Case: Threat Detection",
171    "Tactic: Persistence",
172    "Tactic: Privilege Escalation",
173    "Tactic: Execution",
174    "Data Source: Elastic Defend",
175]
176timestamp_override = "event.ingested"
177type = "eql"
178
179query = '''
180file where host.os.type == "linux" and
181event.action in ("rename", "creation") and file.path : (
182  "/etc/cron.allow", "/etc/cron.deny", "/etc/cron.d/*", "/etc/cron.hourly/*", "/etc/cron.daily/*", "/etc/cron.weekly/*",
183  "/etc/cron.monthly/*", "/etc/crontab", "/var/spool/cron/crontabs/*", "/var/spool/anacron/*"
184) and not (
185  process.executable in (
186    "/bin/dpkg", "/usr/bin/dpkg", "/bin/dockerd", "/usr/bin/dockerd", "/usr/sbin/dockerd", "/bin/microdnf",
187    "/usr/bin/microdnf", "/bin/rpm", "/usr/bin/rpm", "/bin/snapd", "/usr/bin/snapd", "/bin/yum", "/usr/bin/yum",
188    "/bin/dnf", "/usr/bin/dnf", "/bin/podman", "/usr/bin/podman", "/bin/dnf-automatic", "/usr/bin/dnf-automatic",
189    "/bin/pacman", "/usr/bin/pacman", "/usr/bin/dpkg-divert", "/bin/dpkg-divert", "/sbin/apk", "/usr/sbin/apk",
190    "/usr/local/sbin/apk", "/usr/bin/apt", "/usr/sbin/pacman", "/bin/podman", "/usr/bin/podman", "/usr/bin/puppet",
191    "/bin/puppet", "/opt/puppetlabs/puppet/bin/puppet", "/usr/bin/chef-client", "/bin/chef-client",
192    "/bin/autossl_check", "/usr/bin/autossl_check", "/proc/self/exe", "/dev/fd/*",  "/usr/bin/pamac-daemon",
193    "/bin/pamac-daemon", "/usr/local/bin/dockerd", "/opt/elasticbeanstalk/bin/platform-engine",
194    "/opt/puppetlabs/puppet/bin/ruby", "/usr/libexec/platform-python", "/opt/imunify360/venv/bin/python3",
195    "/opt/eset/efs/lib/utild", "/usr/sbin/anacron", "/usr/bin/podman", "/kaniko/kaniko-executor"
196  ) or
197  file.path : "/var/spool/cron/crontabs/tmp.*" or
198  file.extension in ("swp", "swpx", "swx", "dpkg-remove") or
199  file.Ext.original.extension == "dpkg-new" or
200  process.executable : (
201    "/nix/store/*", "/var/lib/dpkg/*", "/tmp/vmis.*", "/snap/*", "/dev/fd/*", "/usr/libexec/platform-python*"
202  ) or
203  process.executable == null or
204  process.name in ("crontab", "crond", "executor", "puppet", "droplet-agent.postinst", "cf-agent") or
205  (process.name == "sed" and file.name : "sed*") or
206  (process.name == "perl" and file.name : "e2scrub_all.tmp*") 
207)
208'''
209
210
211[[rule.threat]]
212framework = "MITRE ATT&CK"
213[[rule.threat.technique]]
214id = "T1053"
215name = "Scheduled Task/Job"
216reference = "https://attack.mitre.org/techniques/T1053/"
217[[rule.threat.technique.subtechnique]]
218id = "T1053.003"
219name = "Cron"
220reference = "https://attack.mitre.org/techniques/T1053/003/"
221
222
223
224[rule.threat.tactic]
225id = "TA0003"
226name = "Persistence"
227reference = "https://attack.mitre.org/tactics/TA0003/"
228[[rule.threat]]
229framework = "MITRE ATT&CK"
230[[rule.threat.technique]]
231id = "T1053"
232name = "Scheduled Task/Job"
233reference = "https://attack.mitre.org/techniques/T1053/"
234[[rule.threat.technique.subtechnique]]
235id = "T1053.003"
236name = "Cron"
237reference = "https://attack.mitre.org/techniques/T1053/003/"
238
239
240
241[rule.threat.tactic]
242id = "TA0004"
243name = "Privilege Escalation"
244reference = "https://attack.mitre.org/tactics/TA0004/"
245[[rule.threat]]
246framework = "MITRE ATT&CK"
247[[rule.threat.technique]]
248id = "T1053"
249name = "Scheduled Task/Job"
250reference = "https://attack.mitre.org/techniques/T1053/"
251[[rule.threat.technique.subtechnique]]
252id = "T1053.003"
253name = "Cron"
254reference = "https://attack.mitre.org/techniques/T1053/003/"
255
256
257
258[rule.threat.tactic]
259id = "TA0002"
260name = "Execution"
261reference = "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