Query Details

Detect Shebang Code Inside Device Files

Query

**DDetect Shebang code inside Device Files**

**Description:** Shebangs (#!) are native to Unix-like operating systems (macOS and Linux). Standard Windows consoles (Command Prompt and PowerShell) do not natively use them. However, they do work on Windows when using tools such as the Python Launcher, Git Bash, Cygwin, or Unix-like environments such as WSL. In simple terms, a Shebang tells the operating system which interpreter should execute a script. For example: #!/usr/bin/python3

For this query, I would recommend performing some threat hunting first and creating a whitelist for known false positives or trusted devices (for example, devices managed by developers). Once the detection is properly tuned, it can be a good way to monitor the download or import of Shebang files on suspicious directories, making it a strong candidate for a threat detection rule.
```
DeviceFileEvents 
| extend AF=parse_json(AdditionalFields) | where tostring(AF.FileType) == "Shebang" 
| where FolderPath has_any ("\\Downloads\\", "\\AppData\\Local\\Temp\\", "/tmp/", "/var/tmp/", "/Users/Shared/", "/Downloads/")
 | project Timestamp, DeviceName,DeviceId, ActionType, FileName, FolderPath, SHA256, InitiatingProcessFileName, 
InitiatingProcessCommandLine,ReportId
```

Explanation

This query is designed to detect files with a Shebang (#!) in their code on devices, specifically focusing on files located in directories that are often used for temporary or downloaded files. Here's a simple breakdown of what the query does:

  1. Data Source: It looks at events related to files on devices (DeviceFileEvents).

  2. Shebang Detection: It checks if the file type is a "Shebang" by examining additional fields in the data.

  3. Suspicious Directories: It filters the results to only include files found in certain directories that are commonly used for downloads or temporary storage, such as Downloads, AppData\Local\Temp, /tmp/, and others.

  4. Output Information: For files that meet these criteria, it provides details such as the timestamp of the event, the device name and ID, the action taken on the file, the file name and path, the file's SHA256 hash, and information about the process that initiated the file event.

The purpose of this query is to help identify potentially suspicious activity by monitoring for Shebang files in directories where they might not typically be expected, which could indicate unauthorized or malicious scripts being downloaded or executed. Before using this as a detection rule, it's recommended to perform threat hunting to identify false positives and create a whitelist for trusted devices or users, such as developers who might legitimately use Shebang scripts.

Details

Sergio Albea profile picture

Sergio Albea

Released: June 11, 2026

Tables

DeviceFileEvents

Keywords

DeviceFiles

Operators

DeviceFileEventsextendparse_jsonwheretostringhas_anyproject

Actions