Digital Forensics, Incident Response and Malware Analysis
domingo, 10 de mayo de 2020
Probando la detección de archivos eliminados en Sysmon v11
A finales del mes pasado se liberó la versión 11 de Sysmon. Esta herramienta, parte de la célebre y bien conocida suite de herramientas SysInternals, permite monitorear los sistemas Windows. A medida que Sysmon ha evolucionado, sus autores le han agregado más funcionalidades que permiten identificar las acciones que los atacantes realizan cuando comprometen uno de estos sistemas.
La última capacidad que fue agregada a Sysinternals en la versión 11 es la detección de eliminación de archivos y es que es muy común que los atacantes eliminen los archivos maliciosos después de completar un ataque, como bien sabemos esto corresponde a la fase de borrado de huellas, donde los atacantes tratan de reducir la probabilidad de ser detectados. En este artículo vamos a instalar la versión 11 de Sysmon y probar esta nueva funcionalidad.
En primer lugar, necesitamos un archivo de configuración de Sysmon. Si bien podemos crear nuestro propio archivo de configuración manualmente, esto es un trabajo monumental ya que requiere hacer muchas pruebas e ir agregando excepciones para el software legítima, así como agregar reglas para identificar técnicas de ataque. Por ello, recomiendo utilizar alguno de los archivos de configuración de la comunidad y extenderlo para cubrir nuestras necesidades.
Vamos a utilizar el archivo de configuración del investigador Olaf hartong, modificado hace 5 meses a la fecha de escritura de este artículo. Este archivo es de código abierto y está disponible en su GitHub.
Simplemente descargamos el archivo de configuración y lo instalamos con el comando
Sysmon -i config.xml
Ahora pasaremos a extender el archivo de configuración para habilitar la nueva función de monitoreo de la versión 11, el borrado de archivos, para ello basta agregar las siguientes líneas en el archivo de configuración, con esto se van a auditar todos los eventos de eliminación de archivos en el sistema.
<RuleGroup name="" groupRelation="or">
<FileDelete onmatch="exclude">
</FileDelete>
</RuleGroup>
Aplicamos la nueva configuración de Sysmon con la bandera -c.
Abrimos el log de eventos de Sysmon y filtramos por el evento 23, e inmediatamente vemos los eventos de borrado de archivos. Los campos registrados son: Fecha, GUID, Usuario, Imagen del programa, archivo destino (target filename), valores hash, si es ejecutable (booleano) y si está archivado (booleano), este último valor no me queda muy claro aún.
Habilitar el monitoreo de todos los archivos eliminados, generará una importante cantidad de eventos, es posible también agregar condiciones específicas, por ejemplo auditar sólo los archivos que estén dentro de ciertas carpetas.
Aplicamos el nuevo archivo de configuración. Ahora los únicos eventos registrados de archivos eliminados son lo que están en esa ruta, por ejemplo el siguiente evento muestra que se eliminó el archivo file.txt desde la terminal de comandos cmd. Esta ruta es sólo un ejemplo, generar la configuración apropiada para el evento FileDelete necesitará más pruebas a fin de poder registrar eventos interesantes, manteniendo un buen balance entre cantidad de eventos generados y el valor potencial de estos eventos.
Monitorear archivos eliminados es una capacidad que faltaba en versiones anteriores de Sysmon y que viene muy bien para incrementar la visibilidad de seguridad en los equipos Windows.
viernes, 1 de mayo de 2020
Los mejores libros de ciberseguridad
Ser investigador de ciberseguridad, independientemente de nuestra especialidad, es una tarea que requiere de una preparación continua y sobretodo, pasión. El progreso que tendremos si contamos con estas dos cualidades será más alto que si nos quedamos sólo con lo que vimos en la Universidad o los entrenamientos obligatorios de nuestra empresa.
Como probablemente saben, soy un promotor de los cursos de SANS Institute ya que son muy didácticos y de gran calidad. Estos cursos tienen un gran enfoque práctico dirigido a las necesidades del día a día. Usualmente en la parte final del curso incluyen un reto CTF en el que puedes probar todas tus habilidades y competir por una hermosa moneda de ganador. La desventaja de estos cursos es su alto costo y es que, sobretodo para los precios de América Latina, resulta difícil para muchas personas reunir el dinero para autofinanciarse este tipo de cursos. Entonces, qué otra alternativa existe para continuar nuestra preparación en estos apasionantes temas?
Además de tomar cursos del SANS o de otras empresas de capacitación a mí también me ha servido leer y aprovechar varios libros de seguridad informática. Si bien, en muchas ocasiones, esto no se puede comparar con un entrenamiento completo en forma, nos servirán para expandir nuestros conocimientos en muchos temas si contamos con la disciplina y constancia suficientes para absorber los contenidos.
En este artículo voy a recomendar algunos libros de diferentes especialidades de seguridad informática, esperando que también a ustedes les sean de utilidad. Si creen que falta algún libro por mencionar que sea excelente, por favor avísenme para agregarlo a la lista.
REVERSING Y ANÁLISIS DE MALWARE
The IDA Pro Book, Eagle (Recomendable para los ya adentrados en reversing)
ANÁLISIS FORENSE DIGITAL Y WINDOWS INTERNALS
Windows Internals 7th edition - Part 2 Russinovich, Allievi, Ionescu, Solomon (Preventa disponible)
RESPUESTA A INCIDENTES
OS X Incident Response, Bradley
BLUE TEAM
Blue Team Field Manual (BTFM), White, Clark (Excelente precio)
RED TEAM
Read Team Field Manual (RTFM), Clark (Excelente precio)
FORENSE EN MÓVILES
Practical Mobile Forensics, Mahalik, Tamma, Skulkin, Bommisetty (Muy recomendable también el curso de SANS FOR 585 de la autora Heather Mahalik)
ANÁLISIS DE VOLCADOS DE MEMORIA
PENTEST, HACKING y PYTHON
Nmap Network Exploration and Security Auditing Cookbook, Calderón (Del autor mexicano Paulino Calderón, también desarrollador de Nmap)
Gray Hat Hacking, Harper, Regalado, Linn, Sims, Spasojevic, Martinez, Baucom, Eagle, Harris (Uno de los autores es el researcher mexicano Daniel Regalado)
OSINT Y CTI
Psychology of Intelligence Analysis, Heuer (Excelente precio)
Structured Analytical Techniques for Intelligence Analysis, Heuer
CONTEXTO DE LA SEGURIDAD
Future Crimes, Goodman (Excelente precio)
DECEPTION
The Cuckoo´s Egg, Stoll (Viejo pero aún relevante)
ATAQUE Y DEFENSA PASO A PASO
Counter Hack Reloaded, Skoudis, Liston (Viejo pero aún relevante)
CULTURA HACKER
Ghost in the Wires, Mitnick, Wozniak
The Art of Invisibility, Mitnick
Tribe of Hackers: cybersecurity advise, Carey, Jin
Tribe of Hackers: Red Team, Carey, Jin
Tribe of Hackers: Blue Team, Carey, Jin
Nota: los vínculos a los libros sugeridos se generaron como parte del programa de afiliados de Amazon.
Ghost in the Wires, Mitnick, Wozniak
The Art of Invisibility, Mitnick
Tribe of Hackers: cybersecurity advise, Carey, Jin
Tribe of Hackers: Red Team, Carey, Jin
Tribe of Hackers: Blue Team, Carey, Jin
Nota: los vínculos a los libros sugeridos se generaron como parte del programa de afiliados de Amazon.
lunes, 13 de enero de 2020
Solving the Kringlecon 2 CTF
This time I had the pleasure to solve the Kringle Con 2019 with my friend Alexa Gomez from Colombia, it was cool to team up to try to solve the challenge as it is a social, rather than an individual experience. We overcome frustration and difficulties and we were able to complete the 12 objectives and send our write up to the Kringlecon organizers to have the opportunity to compete for the full courses and not just the Tshirts. Teams in the Kringlecon are not encouraged but are not prohibited either. The only problem is that in case that we win, we will have to raffle the prize, for us this was not a problem.
I think that Alexa is a solid player, never giving up, that was key solving all the objectives! I think that the challenge that I enjoyed the most was the reversing one, as that has been one of the areas that I have enjoyed most recently. You can see our write up available on our Github, feel free to download it and read it.
Kringlecon 2019 Write UP
Thinking about the challenges that we faced, for me it was difficult to dedicate any time except for Saturdays and Sundays and at times it was difficult to fight against frustration when we didn't get the right answer, on those times it was better to step back a little bit and re think the problem. Also, analyzing what I could have done better, I think I overlooked some hints, maybe that will be helpful when playing next year.
Participating in CTFs is a good way to learn something new, so even if you don't get the answers you will win more knowledge and skills. The progress can be very difficult depending on the time that one has available to play, experience, etc. When you can team up with a colleague it can be very positive if you do it with the right people. Finally, when you complete all the objectives you feel really good :). I encourage anyone in infosec to try to play CTFs from time to time.
miércoles, 2 de octubre de 2019
File renaming technique vs Sysmon Powershell detection
One of the techniques used
by attackers to evade some endpoint-based detections is renaming
Powershell binary
before running the malicious command. For example, according to Black Hills Information Security, on 2017 they were able to bypass Cylance using this technique
https://www.blackhillsinfosec.com/bypassing-cylance-part-4-metasploit-meterpreter-powershell-empire-agent/
https://www.blackhillsinfosec.com/bypassing-cylance-part-4-metasploit-meterpreter-powershell-empire-agent/
In this blog post we
are going to evaluate if it is possible to bypass a Sysmon based Powershell detection
search by renaming Powershell binary to something else before running the
malicious Powershell command.
Let’s assume that for
whatever reason we were not able to detect the attack on the delivery phase and
the attacker is able to rename the native Powershell program and run the
malicious command using the renamed copy, as shown in the following image.
When looking at Sysmon
event id 1, we see that the Description is unchanged, despite being renamed.
If the detection search
is looking for “powershell” in the Image or CommandLine and the hunter is
looking for “powershell”, the detection is going to be evaded. However, as
previously shown the description is not altered when the file is renamed,
therefore this field can be used to resist the “renaming evasion technique”, as
demonstrated in the following image.
Even if PowerShell is
renamed, it retains its Description “Windows PowerShell”, which is tracked by
Sysmon. If the search is using this
field, it will not be evaded by the file renaming technique. It will require
extra steps from the attacker to bypass this search.
Defenders should have
multiple detections for the various phases of the kill chain, to detect
delivery, exploitation, command and control and actions on objectives. Even if
the attackers would had been able to bypass an exploitation-based search, we should
had detected them on the other stages, hopefully as early as possible. Also it is necessary to complement endpoint based detection with network visibility.
domingo, 14 de abril de 2019
Jailbreaking iOS iphone 4s with Home Depot jailbreak
When analyzing iOS applications it is important to have an unrestricted environment to be able to fully analyze all the aspects related to that application and determine if it shows malicious behavior, decrypt the app to analyze strings and headers and even analyze the assembly code of the app, if time permits. When we are talking about overcoming restrictions on an iphone device, it means jailbreaking it. In this article, I will show the steps that I followed to jailbreak an old iphone 4s that I have.
Verify that there is an existing jailbreak for the iphone model and iOS version that you have.
In my case, there were several candidates but the jailbreak known as Home Depot seemed like a good option.
https://yalujailbreak.net/home-depot-jailbreak-offsets/
https://cydiainstaller.net/home-depot-jailbreak/
It is not a good idea to jailbreak your production device, because jailbreaking reduce the security posture of your device, making it easier for someone to get access to your data, therefore ideally you should this device for testing only. You should also create an apple account to be used only for this device, not your production account.
Download the Home Depot IPA file, version R3 worked for me
http://wall.supplies/MixtapePlayerRC3.ipa
If you are paranoid, like me, it is a good idea to download all the required software from a virtual machine, so you don't risk downloading and running potentially malicious programs.
Download and install iTunes
Create a new apple account for this process
Download Cydia Impactor
https://cydia.saurik.com/api/latest/2
Finally, run Cydia Impactor and drag and drop MixtapePlayerRC3.ipa file into it. It will ask for your apple account credentials, provide the credentials of the account you created. This will install the Home Depot jailbreak app.
In the iphone go to Settings > General > Device Management > Select the user used to sign the application and Trust It.
Open the Home Depot app, select Prepare for Jailbreak > Accept > Dismiss > Proceed with Jailbreak > Begin Installation.
Once it is completed Cydia is installed. Open Cydia and delete the repo repo666 by sliding it to the left as it causes an error. Update all the packages.
Install BigBoss Recommended Tools, as it has several command line useful tools, such as git, curl, etc.
Video where I found most of the instructions (in Spanish)
https://www.youtube.com/watch?v=qZeiW3Cyx1Y
Install OpenSSH in Cydia
This will allow you to access your device through SSH, the default password is alpine, you have access it and change it to prevent unauthorized use. Use the command passwd to change root and mobile accounts passwords.
That's it, enjoy it!
Verify that there is an existing jailbreak for the iphone model and iOS version that you have.
In my case, there were several candidates but the jailbreak known as Home Depot seemed like a good option.
https://yalujailbreak.net/home-depot-jailbreak-offsets/
https://cydiainstaller.net/home-depot-jailbreak/
It is not a good idea to jailbreak your production device, because jailbreaking reduce the security posture of your device, making it easier for someone to get access to your data, therefore ideally you should this device for testing only. You should also create an apple account to be used only for this device, not your production account.
Download the Home Depot IPA file, version R3 worked for me
http://wall.supplies/MixtapePlayerRC3.ipa
If you are paranoid, like me, it is a good idea to download all the required software from a virtual machine, so you don't risk downloading and running potentially malicious programs.
Download and install iTunes
Create a new apple account for this process
Download Cydia Impactor
https://cydia.saurik.com/api/latest/2
Finally, run Cydia Impactor and drag and drop MixtapePlayerRC3.ipa file into it. It will ask for your apple account credentials, provide the credentials of the account you created. This will install the Home Depot jailbreak app.
In the iphone go to Settings > General > Device Management > Select the user used to sign the application and Trust It.
Open the Home Depot app, select Prepare for Jailbreak > Accept > Dismiss > Proceed with Jailbreak > Begin Installation.
Once it is completed Cydia is installed. Open Cydia and delete the repo repo666 by sliding it to the left as it causes an error. Update all the packages.
Install BigBoss Recommended Tools, as it has several command line useful tools, such as git, curl, etc.
Video where I found most of the instructions (in Spanish)
https://www.youtube.com/watch?v=qZeiW3Cyx1Y
Install OpenSSH in Cydia
This will allow you to access your device through SSH, the default password is alpine, you have access it and change it to prevent unauthorized use. Use the command passwd to change root and mobile accounts passwords.
That's it, enjoy it!
domingo, 3 de febrero de 2019
Enabling Windows Firewall log
One of the key evidence items to acquire and analyze in a security incident is information about network connections established on the device that is being investigated. Unfortunately, not on every situation this information will be available, because if the device was powered off, the network connections are lost, as it is volatile information that resides in the RAM memory of the computer. In this case, we would try to locate and analyze hibernation files (extremely valuable, but not always available) or offline files trying to identify any remnant of a network connection, such as the pagefile.sys or service specific logs, but this information would be very limited and incomplete as compared to the information that could have been displayed by the command netstat. We could also try to obtain logs from any firewalls available on the organization, but we would depend on logging being enabled and that the network traffic of the device under investigation had passed through the specific network path where the firewall is located. Finally, network activity could also happen when the device is not at the enterprise, common for laptops, in that case obviously the firewall would have no relevant logs for that specific investigation.
Modern OS have host-based firewalls which can be easily configured to store logs about the network connections, providing a valuable source of information in case of a security incident. Regarding the Windows operating system, it is very easy to enable logging of the network connections through the integrated Windows Firewall. If the log is enabled, it will require administrator privileges to delete it, which will not always be the case if the attacker cannot achieve admin rights on the compromised host. Even if the attacker achieves admin rights, not all of them will be aware of the log so there will be a good chance that it will be available for collection and analysis.
Windows Firewall log can be enabled extremely easy, both through command line interface and through GUI and it allows the user to determine what kind of network connections should be logged (failed or successful). I will show how to enable it using the command line interface. We can log both allowed and dropped connections, but I recommend doing it only for allowed connections, as dropped connections would log lots of noise, especially related to the UPnP protocol.
netsh advfirewall set allprofiles logging allowedconnections enable
netsh advfirewall set allprofiles logging droppedconnections disable
We can also increase the size of the log, the acceptable range is 1-32767 kilobytes.
netsh advfirewall set allprofiles logging maxfilesize 32767
The window Firewall will be created by default on C:\Windows\System32\LogFiles\Firewall, although it can be configured to a different location. If you try to open the active file, you will get an error. To solve this problem, simply create a copy of the file and open it. The structure of the log is very simple and straightforward to read, it is in clear text and stores the following fields:
Since it is generated by the host, it will be synced with other logs generated on the same computer, allowing for quick correlation. If the logs were generated by a network firewall, we would first have to check if it is synced to the same NTP server or otherwise calculate the time skew and adjust the timestamps, which is not always a fun or easy task to do.
You can determine if logging is enabled for a given Windows computer by running the following command:
netsh advfirewall show allprofiles
The relevant parameters for every profile are LogAllowedConnection, LogDroppedConnection FileName and MaxFileSize.
Enabling the Windows Firewall log is a quick win, as it is very simple to do and can provide extremely valuable information during a DFIR investigation. Because of its small size, it can be used for triage and rapidly search a given IP address or uncommon port that has been previously identified as malicious or suspicious. In the following article, I will show several use cases for this information, and I will share a useful script to extract information from the log to make it more actionable.
If you disabled Windows Firewall because you use a third-party host firewall, make sure that you have logging enabled in the third-party firewall, determine the retention time and make sure it meets your requirements.
lunes, 17 de julio de 2017
Detecting lsass Acess with Sysmon Process Access
Local Security Authority
Subsystem Service process (lsass.exe) is responsible for enforcing the security
policy on the system and handling password operations. Therefore, it contains user
passwords. One of the things that
attackers do when they have gained access to a system is to inject code into
that process to obtain clear text passwords, from the attacker’s perspective
this is great as they won’t have to consume precious time trying to attack
password hashes, as opposed as accessing password hashes from the SAM Windows registry
hive.
Sysmon is a useful and free tool created by Mark Russinovich
y Thomas Garnier from Microsoft that can
audit processes among many other things. One of the things that can be audited
on the most recent version is Process Access, which can detect any tools that
have accessed lsass process and that could have potentially dumped credentials.
By default process access audit is disabled, so it is required to tune Sysmon
to audit this event, which can be done with the following xml configuration
file.
<Sysmon schemaversion="3.2">
<HashAlgorithms>*</HashAlgorithms>
<EventFiltering>
<!-- Log all
drivers except if the signature -->
<!--
contains Microsoft or Windows -->
<ProcessAccess onmatch="include">
<TargetImage
condition="contains">lsass.exe</TargetImage>
</ProcessAccess>
<!-- Enable
Network Connections -->
<NetworkConnect onmatch="exclude"/>
</EventFiltering>
</Sysmon>
Next we update sysmon configuration by using –c flag and
passing the xml file as parameter.
To test the configuration, I used
mimikatz, which is a (in)famous tool used to get clear text credentials from
lsass process. I set up a meterpreter listener and created a reverse
meterpreter tcp executable called lolm.exe, which I executed on the test
Windows computer. As expected, I was able to load mimimkatz plugin and dump
clear text credentials using kerberos command.
Sysmon was able to successfully
log the event, it traced time and date, full path of the meterpreter executable
and the call trace. It is important to notice that Sysmon will not only detect Mimikatz, but any tool that access lsass process, therefore other tools used to dump
credentials from lsass would be detected as well.
In the following articles we will see how we can tune sysmon configuration to detect other attacks.
Suscribirse a:
Entradas (Atom)