Its not really feasible for any one at least within this community to probably give you solid advice on what you’ve sent. I would probably recommend against sharing such screenshots such as this, as you may feeding out sensitive information by posting this.
Somewhere in the command line for process 19328 a Add-Type
cmdlet is called.
Powershell invokes csc.exe to compile this class definition into a dll.
A temporary file is created inside the %appdata% folder. In your case it just happens that the random characters lineup and you see rat
in the file name epamrat1.cmdline
.
Just to be clear though, Defender DOES create unsigned DLLs in temp. I asked someone who’s really familiar with defender (Nathan McNulty) and he said he’s seen it before, and when he tried to get more information from Microsoft about it they wouldn’t answer.
We started seeing a few of these a couple weeks ago too, but the parent process that created the DLL was SenseIR. I did a pretty full forensic investigation on the devices and couldn’t find any indication of something malicious going on.
We have seen this exact thing in our environment as well. Created support case with Microsoft but they have not been helpful. Confirmed it’s an FP and that it is legit behavior but offered no explanation as to what was actually happening or why it was occurring.
Update: Microsoft replied and claimed they have fixed the issue. They advised to update to Security Intelligence Version 1.403.3427.0 and above.
CSC is a compiler and perfect if you wanna send code and create a executable.
When Defender does an automated investigation is uses powershell and CSC to create dlls on the fly to do what it needs to then they are immediately deleted. If the process originates from Defender (as appears in this case) then its normal.
Problem I have is zero trust applications have trouble seeing far enough back in the chain to verify its defender initiating.
Rule#1 decades ago was to never have a complier on your production machines, but it’s built into .NET now. This seems ripe for exploitation for some sort of living off the land attack.
It’s mde detecting itself again.
It does do that on the fly compilation using csc command line csharp compiler all the time, but that’s used by threat actors too.
The only processes involved are MDE ones; it’s not detecting based on something else.
The URLs are all MDE cloud.
Every once in a while they introduce a detection involving that and it triggers.
Dcrat’s souce code is on GitHub C# code, which makes it easy to write detections for.
I’ve seen them on occasion. It’s annoying, but if you want verification, you don’t have to listen to me — you can use the defender expert’s option in MDE.
epamrat1.cmdline, sounds like a remote access tool.. probably malicious. Check the logs and figure out who created the file/command.
This reminds me of a sample scenario from Microsoft
С помощью PowerShell вы можете получать, добавлять, удалять, или изменять значения переменных окружения (среды). В переменных окружения Windows хранит различную пользовательскую и системную информацию (чаще всего это пути к системным и временным папкам), которая используется операционной системой и приложениями, установленными на компьютере.
В Windows доступны несколько типов переменных окружения:
- Переменные окружения процесса – создаются динамически и доступны только в текущем запущенном процесс
- Пользовательские переменные окружения – содержат настройки конкретного пользователя и хранятся в его профиле (хранятся в ветке реестре
HKEY_CURRENT_USER\Environment
) - Системные переменные окружения – глобальные переменные окружения, которые применяются для все пользователей (хранятся в ветке
HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
)
Типы переменных окружения Windows указаны в порядке уменьшения приоритета. Т.е. значение переменной окружения %TEMP% в пользовательском профиле будет иметь больший приоритет, чем значение системной переменной окружения %TEMP%.
Для управления переменными окружениями обычно используется вкладка Advanced в свойствах системы. Чтобы открыть System Properties, выполните команду
SystemPropertiesAdvanced
и нажмите на кнопку Environment Variable.
В этом окне можно создать и отредактировать переменные среды для текущего пользователя или системные переменные окружения.
Чтобы вывести полный список переменных окружения и их значения в PowerShell, выполните команду:
Как вы видите, для доступа к переменным окружения в PowerShell используется отдельный виртуальный диск Env:, доступный через провайдер Environment.
Получить значение определенной переменной окружения Path:
Т.к. переменные окружения, по сути, это файлы на виртуальном диске, нажатием кнопки TAB вы можете использовать автозавершение для набора имени переменной окружения.
Чтобы разбить значение переменной окружения на строки, выполните:
(Get-ChildItem env:Path).value -split ";"
Добавить значение в переменную окружения Path:
$Env:Path += ";c:\tools"
Однако это добавляет временное значение в переменную окружения
Path
. При следующей перезагрузке новое значение в переменной будет сброшено. Чтобы добавить постоянное значение в системную переменную окружения, используется такая конструкция:
Несмотря на то, что фактически переменные окружения и их значения хранятся в реестре, прямое изменение их значений в реестре используется редко. Причина в том, что текущий процесс при запуске считывает значение переменных окружения из реестра. Если вы измените их, процесс не будет уведомлён об этом.
Если вам нужно из PowerShell изменить в реестре значение переменной окружения, используются команды:
$variable = Get-ItemPropertyValue -Path 'HKCU:\Environment\' -Name 'Path'
$add_path = $variable + ';C:\Git\'
Set-ItemProperty -Path 'HKCU:\Environment\' -Name 'Path' -Value $add_path
Вы можете создать локальную переменную окружения. По умолчанию такая переменная окружения будет доступна только в текущем процессе (PowerShell), из которого она создана. После того, как процесс будет закрыт – переменная окружения будет удалена.
$env:SiteName = 'winitpro.ru'
Get-ChildItem Env:SiteName
Если нужно создать глобальную системную переменную (нужны права администратора), используйте команду:
Очистить и удалить глобальную переменную окружения:
$env:Path += "C:\Program Files\7-Zip"
should be $env:Path += ";C:\Program Files\7-Zip"
(note the ;
) and it is effective for the remainder of the current session (process) only.
If you want this modification to persist, i.e. to be available in all future sessions:
Either: Place the command in your
$PROFILE
file.Or: Modify the persistent definition of the
Path
environment variable in the registry, e.g. interactively viasysdm.cpl
- Note: Robustly updating
Path
programmatically is nontrivial, unfortunately – see this answer.
- Note: Robustly updating
$7zip a -t7z...
In order to execute commands whose names or paths are stored in variables, you must invoke them via &
, the call operator (which is a syntactic necessity in PowerShell):
& $7zip a -t7z ...
The same goes for command names or paths that are quoted as a whole:
C:\"Program Files"\7-Zip\7z.exe
happens to work without&
, because the argument starts with an unquoted string.- A an aside: Starting with a quoted string and appending an unquoted one is fundamentally unsupported in PowerShell; e.g.,
& "C:\Program Files\"7-Zip\7z.exe
wouldn’t work, because the7-Zip\7z.exe
part would become a separate argument – see this answer.
- A an aside: Starting with a quoted string and appending an unquoted one is fundamentally unsupported in PowerShell; e.g.,
By contrast,
"C:\Program Files"\7-Zip\7z.exe"
would require&
By contrast, use of &
is optional with verbatim, unquoted command names and paths (e.g, 7z
, C:\tools\7z.exe
)
See this answer for details.
- Clear temp file with disk cleanup and,
- Clear other temp files from different locations
- C:\Windows\Temp
- C:\Windows\Prefetch
- C:\Users\*\AppData\Local\Temp
Script to clear Cache and Temporary files on Windows Devices
Manually deleting this much data will take some time and will most likely need a lot of human intervention. Doing the aforementioned procedures manually on a single computer does not take long. But, if you are running 7 to 8 virtual machines with Windows operating system and doing a lot of technical work, there might be performance issues with your machines. Now, doing these manual actions in all the machines takes a long time. To avoid this problem, let’s design a utility. This tool eliminates the need for manual intervention by deleting all data from the aforementioned places, running a disc cleanup tool, and clearing the recycle bin.
Delete Recycle Bin Data
Fetch the path from the system and create a variable $Path and assign the path. Make sure to separate the drive and the path as mentioned below.
- `Get-ChildItem` will retrieve the specified items and their child’s items from that location.
- `-ErrorAction` SilentlyContinue will ignore permission security-related issues. The Remove-Item will delete all the data in the present location. The Recurse parameter searches the Path directory its subdirectories and the Force parameter displays hidden files.
- `Write-Host` allows you to emit output to the information stream and you can specify the color of text by using the `-ForegroundColor` parameter.
- If you want to ignore some files that you do not want to delete, then you can use the `-exclude` parameter.
#1# Removing recycle bin files # Set the path to the recycle bin on the C drive $Path = 'C' + ':\$Recycle.Bin' # Get all items (files and directories) within the recycle bin path, including hidden ones Get-ChildItem $Path -Force -Recurse -ErrorAction SilentlyContinue | # Remove the items, excluding any files with the .ini extension Remove-Item -Recurse -Exclude *.ini -ErrorAction SilentlyContinue # Display a success message write-Host "All the necessary data removed from recycle bin successfully" -ForegroundColor Green
Delete Temp Data
Here, we have specified the paths where the temporary data is present. As you can see, this is explained in detail in the “Delete Recycle Bin data” section.
#2# Remove Temp files from various locations write-Host "Erasing temporary files from various locations" -ForegroundColor Yellow # Specify the path where temporary files are stored in the Windows Temp folder $Path1 = 'C' + ':\Windows\Temp' # Remove all items (files and directories) from the Windows Temp folder Get-ChildItem $Path1 -Force -Recurse -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue # Specify the path where temporary files are stored in the Windows Prefetch folder $Path2 = 'C' + ':\Windows\Prefetch' # Remove all items (files and directories) from the Windows Prefetch folder Get-ChildItem $Path2 -Force -Recurse -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue # Specify the path where temporary files are stored in the user's AppData\Local\Temp folder $Path3 = 'C' + ':\Users\*\AppData\Local\Temp' # Remove all items (files and directories) from the specified user's Temp folder Get-ChildItem $Path4 -Force -Recurse -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue # Display a success message write-Host "removed all the temp files successfully" -ForegroundColor Green
Note: Please note that the $Path3 has the symbol ‘*’, which denotes ‘All’. $Path3 will give you the error, you need to replace it with your system’s path.
Perform disk Cleanup
The `Cleanmgr` command will remove unused files from the hard drive of your computer. For eg. Temp files, Internet files, downloaded files, and Recycle Bin files can all be cleared using command-line parameters. The Sagerun:1 indicates it will perform disk cleanup only once.
#3# Using Disk cleanup Tool # Display a message indicating the usage of the Disk Cleanup tool write-Host "Using Disk cleanup Tool" -ForegroundColor Yellow # Run the Disk Cleanup tool with the specified sagerun parameter cleanmgr /sagerun:1 | out-Null # Emit a beep sound using ASCII code 7 Write-Host "$([char]7)" # Pause the script for 5 seconds Sleep 5 # Display a success message indicating that Disk Cleanup was successfully done write-Host "Disk Cleanup Successfully done" -ForegroundColor Green # Pause the script for 10 seconds Sleep 10
To create the utility, copy the above-mentioned code and save it in the notepad with the extension .ps1 (.ps1 indicates PowerShell file).
Right-click the file and click “Run with PowerShell”. It will run this utility and will delete the data automatically without any manual intervention.
Please to comment…
Description
Use living off the land tools to zip a file and stage it in the Windows temporary folder for later exfiltration. This rule is adapted from https://github.com/SigmaHQ/sigma/blob/master/rules/windows/process_creation/proc_creation_win_powershell_zip_compress.yml
MITRE ATT&CK® Techniques
Data Staged: Local Data Staging
Adversaries may stage collected data in a central location or directory on the local system prior to Exfiltration. Data may be kept in separate files or combined into one file. Interactive command shells may be used, and common functionality within cmd and bash may be used to copy data into a staging location.
Data Source
Windows Sysmon via FortiSIEM Agent
Remediation Guidance
No remediation guidance specified
Time Window
300 seconds
Trigger Conditions
Filter
SubPattern Definitions
SubPattern Name: Filter
This is the named definition of the event query, this is important if multiple subpatterns are defined to distinguish them.
SubPattern Query
This is the query logic that matches incoming events
eventType="Win-Sysmon-1-Create-Process" AND command REGEXP ".*Compress-Archive .*" AND command REGEXP ".* -Path .*" AND command REGEXP ".* -DestinationPath .*" AND command REGEXP ".*\$env:TEMP\\.*"
Group by Attributes
This defines how matching events are aggregated, only events with the same matching attribute values are grouped into one unique incident ID
command,hostName
Aggregate Constraint
This is most typically a numerical constraint that defines when the rule should trigger an incident
COUNT(*) >= 1
Incident Attribute Mapping
This section defines which fields in matching raw events should be mapped to the incident attributes in the resulting incident.
The available raw event attributes to map are limited to the group by attributes and the aggregate event constraint fields for each subpattern
command = Filter.command,
hostName = Filter.hostName