Cron Job Created or Changed by Previously Unknown Process

Linux cron jobs are scheduled tasks that can be leveraged 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/05/21"
  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
 12'/etc/cron.hourly/%' OR path LIKE '/etc/cron.daily/%' OR path LIKE '/etc/cron.weekly/%' OR path LIKE
 13'/etc/cron.monthly/%' )
 14"""
 15
 16[[transform.osquery]]
 17label = "Osquery - Retrieve rc-local.service File Information"
 18query = """
 19SELECT * FROM file WHERE ( path = '/etc/cron.allow' OR path = '/etc/cron.deny' OR path = '/etc/crontab' OR path =
 20'/usr/sbin/cron' OR path = '/usr/sbin/anacron' )
 21"""
 22
 23[[transform.osquery]]
 24label = "Osquery - Retrieve Additional File Listing Information"
 25query = """
 26SELECT f.path, u.username AS file_owner, g.groupname AS group_owner, datetime(f.atime, 'unixepoch') AS
 27file_last_access_time, datetime(f.mtime, 'unixepoch') AS file_last_modified_time, datetime(f.ctime, 'unixepoch') AS
 28file_last_status_change_time, datetime(f.btime, 'unixepoch') AS file_created_time, f.size AS size_bytes FROM file f LEFT
 29JOIN 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
 30'/etc/cron.d/%' OR path LIKE '/etc/cron.hourly/%' OR path LIKE '/etc/cron.daily/%' OR path LIKE '/etc/cron.weekly/%' OR
 31path LIKE '/etc/cron.monthly/%' )
 32"""
 33
 34[[transform.osquery]]
 35label = "Osquery - Retrieve Running Processes by User"
 36query = "SELECT pid, username, name FROM processes p JOIN users u ON u.uid = p.uid ORDER BY username"
 37
 38[[transform.osquery]]
 39label = "Osquery - Retrieve Listening Ports"
 40query = "SELECT pid, address, port, socket, protocol, path FROM listening_ports"
 41
 42[[transform.osquery]]
 43label = "Osquery - Retrieve Open Sockets"
 44query = "SELECT pid, family, remote_address, remote_port, socket, state FROM process_open_sockets"
 45
 46[[transform.osquery]]
 47label = "Osquery - Retrieve Information for a Specific User"
 48query = "SELECT * FROM users WHERE username = {{user.name}}"
 49
 50[[transform.osquery]]
 51label = "Osquery - Investigate the Account Authentication Status"
 52query = "SELECT * FROM logged_in_users WHERE user = {{user.name}}"
 53
 54
 55[rule]
 56author = ["Elastic"]
 57description = """
 58Linux cron jobs are scheduled tasks that can be leveraged by malicious actors for persistence, privilege escalation and
 59command execution. By creating or modifying cron job configurations, attackers can execute malicious commands or scripts
 60at predefined intervals, ensuring their continued presence and enabling unauthorized activities.
 61"""
 62from = "now-9m"
 63index = ["logs-endpoint.events.*", "endgame-*"]
 64language = "kuery"
 65license = "Elastic License v2"
 66name = "Cron Job Created or Changed by Previously Unknown Process"
 67note = """## Triage and analysis
 68
 69### Investigating Cron Job Created or Changed by Previously Unknown Process
 70Linux cron jobs are scheduled tasks that run at specified intervals or times, managed by the cron daemon. 
 71
 72By creating or modifying cron job configurations, attackers can execute malicious commands or scripts at predefined intervals, ensuring their continued presence and enabling unauthorized activities.
 73
 74This rule monitors the creation of previously unknown cron jobs by monitoring for file creation events in the most common cron job task location directories.
 75
 76> **Note**:
 77> 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.
 78> 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.
 79
 80#### Possible Investigation Steps
 81
 82- Investigate the cron job file that was created or modified.
 83- Investigate whether any other files in any of the available cron job directories have been altered through OSQuery.
 84  - $osquery_0
 85  - $osquery_1
 86  - $osquery_2
 87- 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.
 88  - $osquery_3
 89- Investigate other alerts associated with the user/host during the past 48 hours.
 90- Validate the activity is not related to planned patches, updates, network administrator activity, or legitimate software installations.
 91- Investigate whether the altered scripts call other malicious scripts elsewhere on the file system. 
 92  - If scripts or executables were dropped, retrieve the files and determine if they are malicious:
 93    - Use a private sandboxed malware analysis system to perform analysis.
 94      - Observe and collect information about the following activities:
 95        - Attempts to contact external domains and addresses.
 96          - Check if the domain is newly registered or unexpected.
 97          - Check the reputation of the domain or IP address.
 98        - File access, modification, and creation activities.
 99- Investigate abnormal behaviors by the subject process/user such as network connections, file modifications, and any other spawned child processes.
100  - Investigate listening ports and open sockets to look for potential command and control traffic or data exfiltration.
101    - $osquery_4
102    - $osquery_5
103  - Identify the user account that performed the action, analyze it, and check whether it should perform this kind of action.
104    - $osquery_6
105- Investigate whether the user is currently logged in and active.
106    - $osquery_7
107
108### False Positive Analysis
109
110- If this activity is related to new benign software installation activity, consider adding exceptions — preferably with a combination of user and command line conditions.
111- 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. 
112- 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.
113
114### Related Rules
115
116- Suspicious File Creation in /etc for Persistence - 1c84dd64-7e6c-4bad-ac73-a5014ee37042
117- Potential Persistence Through Run Control Detected - 0f4d35e4-925e-4959-ab24-911be207ee6f
118- Potential Persistence Through init.d Detected - 474fd20e-14cc-49c5-8160-d9ab4ba16c8b
119- New Systemd Timer Created - 7fb500fa-8e24-4bd1-9480-2a819352602c
120- New Systemd Service Created by Previously Unknown Process - 17b0a495-4d9f-414c-8ad0-92f018b8e001
121
122### Response and remediation
123
124- Initiate the incident response process based on the outcome of the triage.
125- Isolate the involved host to prevent further post-compromise behavior.
126- If the triage identified malware, search the environment for additional compromised hosts.
127  - Implement temporary network rules, procedures, and segmentation to contain the malware.
128  - Stop suspicious processes.
129  - Immediately block the identified indicators of compromise (IoCs).
130  - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that attackers could use to reinfect the system.
131- 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.
132- Delete the service/timer or restore its original configuration.
133- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and malware components.
134- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.
135- Leverage the incident response data and logging to improve the mean time to detect (MTTD) and the mean time to respond (MTTR).
136"""
137references = [
138    "https://pberba.github.io/security/2022/01/30/linux-threat-hunting-for-persistence-systemd-timers-cron/",
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 Endgame",
176    "Data Source: Elastic Defend",
177]
178timestamp_override = "event.ingested"
179type = "new_terms"
180
181query = '''
182host.os.type : "linux" and event.action : ("change" or "file_modify_event" or "creation" or "file_create_event") and 
183file.path : (/etc/cron.allow or /etc/cron.deny or /etc/cron.d/* or /etc/cron.hourly/* or /etc/cron.daily/* or 
184/etc/cron.weekly/* or /etc/cron.monthly/* or /etc/crontab or /usr/sbin/cron or /usr/sbin/anacron) 
185and not (
186  (process.name : ("dpkg" or "dockerd" or "rpm" or "snapd" or "yum" or "exe" or "dnf" or "podman" or 
187  "dnf-automatic" or puppet or autossl_check )) or 
188  (file.extension : ("swp" or "swpx")) or 
189  (process.name : "sed" and file.name : sed*) or 
190  (process.name : "perl" and file.name : e2scrub_all.tmp*) or
191  (process.executable : /var/lib/dpkg*)
192)
193'''
194
195
196[[rule.threat]]
197framework = "MITRE ATT&CK"
198[[rule.threat.technique]]
199id = "T1053"
200name = "Scheduled Task/Job"
201reference = "https://attack.mitre.org/techniques/T1053/"
202[[rule.threat.technique.subtechnique]]
203id = "T1053.003"
204name = "Cron"
205reference = "https://attack.mitre.org/techniques/T1053/003/"
206
207
208
209[rule.threat.tactic]
210id = "TA0003"
211name = "Persistence"
212reference = "https://attack.mitre.org/tactics/TA0003/"
213[[rule.threat]]
214framework = "MITRE ATT&CK"
215[[rule.threat.technique]]
216id = "T1053"
217name = "Scheduled Task/Job"
218reference = "https://attack.mitre.org/techniques/T1053/"
219[[rule.threat.technique.subtechnique]]
220id = "T1053.003"
221name = "Cron"
222reference = "https://attack.mitre.org/techniques/T1053/003/"
223
224
225
226[rule.threat.tactic]
227id = "TA0004"
228name = "Privilege Escalation"
229reference = "https://attack.mitre.org/tactics/TA0004/"
230[[rule.threat]]
231framework = "MITRE ATT&CK"
232[[rule.threat.technique]]
233id = "T1053"
234name = "Scheduled Task/Job"
235reference = "https://attack.mitre.org/techniques/T1053/"
236[[rule.threat.technique.subtechnique]]
237id = "T1053.003"
238name = "Cron"
239reference = "https://attack.mitre.org/techniques/T1053/003/"
240
241
242
243[rule.threat.tactic]
244id = "TA0002"
245name = "Execution"
246reference = "https://attack.mitre.org/tactics/TA0002/"
247
248[rule.new_terms]
249field = "new_terms_fields"
250value = ["host.id", "file.path", "process.executable"]
251[[rule.new_terms.history_window_start]]
252field = "history_window_start"
253value = "now-10d"

Triage and analysis

Investigating Cron Job Created or Changed by Previously Unknown Process

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 previously unknown cron jobs by monitoring for file creation 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
  • New Systemd Timer Created - 7fb500fa-8e24-4bd1-9480-2a819352602c
  • New Systemd Service Created by Previously Unknown Process - 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