The content of this article was published (in Spanish) in the edition 25th of the digital magazine .Seguridad of UNAM-CERT.
PNAF v0.1 public prototype is an implementation of a TU/e masters thesis developed as internship project at Fox-IT B.V in The Netherlands. This public prototype DOES NOT include any internal information about TU/e nor Fox-IT.
From Version 0.1.2, PNAF is a project of UNAM-Chapter [The Honeynet Project]
Main development repository
News, updates and howtos
Resources downloads
Version 0.1.2 will get just minor updates (bugs/parsing) and it is the last version of 0.1.x branch. You can either clone this repository and install it on your standalone machine, or download the Virtual Machine image available on http://pnaf.honeynet.org.mx/download/
PNAF is a framework intended to provide the capability of getting a security assessment of network platforms by analysing in-depth the network traffic (in a passive way) and by providing a high-level interpretation in an automated way. It combines different analysis techniques and tools. The framework is intended to achieve the following goals:
PNAF (original prototype) is comprised by three main modules. Each module has its own engines which manage specific tools and process the data. PNAF is written in Perl, why? because Perl rules!
The general model of PNAF (Figure 1) defines the workflow of how PNAF decodes, filters and interprets data from network traffic capture files as single input.
Figure 1. Workflow of Passive Network Audit Framework (PNAF)
PNAF includes a set of tools[2] for capturing and analysis of network traffic such as passive profilers, IDS, protocol decoders, etc. Since some of these tools are quite complex by themselves, they may involve complex installation processes as well. Thus, PNAF is designed not only to use the set of tools in an automated way, but also to facilitate their integration by implementing clean and easy ways to deploy the whole unified framework. There are four main installation modes which are explained in the sections below.
PNAF includes an installer that automates the downloading, compilation and configuration of all the tools included within the framework. This installer is a shell script (bash) that provides a wizard based on dialog. In order to use this installation mode, it is necessary to meet the following requirements:
It may be possible to make PNAF work under Ubuntu or any other GNU/Linux distribution based on Debian APT packages. However, it would imply checking of all the libraries’ equivalences corresponding with such distributions. Moreover, it may be possible to use the installer under other systems which are not based on APT nor Emerge. To do so, you would need to install all needed dependencies manually and then make some small changes on the installer itself. For more information you can check the list of dependencies on README file. Further versions of PNAF are planned to include additional support for the installer as well as additional automated (easier) ways to deploy it (e.g. containers).
Since PNAF needs to install a lot of libraries and dependencies that may cause compatibility issues with the native system, then it is recommended to install PNAF within a chroot environment. This article explains how to perform the installation using chroot.
Thus, assuming that a Debian 8 (amd64) system is used:
# aptitude install debootstrap # debootstrap --arch amd64 jessie chroot_pnaf http://ftp.nl.debian.org/debian # mount -t sysfs sysfs chroot_pnaf/sys # mount -t proc proc chroot_pnaf/proc # mount -o bind /dev chroot_pnaf/dev # mount -o bind /dev/pts chroot_pnaf/dev/pts
Then switch to the chroot environment:
# chroot chroot_pnaf # cd ~
Option 1: From its official repository (main development site)
# aptitude install git # git clone https://dev.honeynet.org.mx/traffic-analysis/pnaf.git
Option 2: From github (mirror)
# git clone https://github.com/jusafing/pnaf
Once pnaf latest release is downloaded, get into the directory and execute the installer.
# cd pnaf # ./install.sh
This will execute the installer wizard. First it is necessary to confirm that you want to install PNAF on the system. Afterwards, it is possible to choose what tools will be installed. Despite the fact that in version 0.1.2 not all the tools are used, it is recommended to install all the listed tools. Thus, PNAF installer by itself can be considered as an automated and easy tool to deploy a set of network traffic analysis tools..
Figure 2. Selection of tools within PNAF installer
If it is the very first time that PNAF is installed on the system, then it should be a “clean installation”. Otherwise, in case of PNAF is already on the system, a clean installation will delete any tool and configuration previously set. So, if you need to install or re-install certain too and keeping a previous configuration, then select “NO” option on this step.
Figure 3. Selection of clean installation
After this step, PNAF will start the compilation and configuration process. which may take around 30-40 minutes depending on the features of the machine. In case of any error encountered by the installer, it will show up the corresponding message and you can check the details in the files install.log (basic log) and install.log.exec (detailed log) to identify the problem. If no problems are encountered, then the installer will show a success confirmation and PNAF will be installed on the system.
It is recommended that in order to update all the environment variables, exit out of the chroot environment and switch back again. Furthermore, it may be useful to add a tag on the chroot shell:
# echo 'PS1="(PNAF) $PS1"' >> ~/.bashrc # exit # chroot chroot_pnaf
To verify that PNAF has been installed correctly:
# pnaf_auditor --help
Figure 4. Execution option of PNAF auditor
The second installation mode can be done by using a preconfigured chroot directory with all the tools already installed and configured. This mode basically avoid the whole process explained in the first installation mode (using debootstrap and run the installer). Moreover, this mode provides a way of deploying environments through the use of templates (chroot directory). In order to use this installation mode, it is only necessary to download the tarball (about 1.3 Gb) that contains the aforementioned template and then just unpack it within the local filesystem.
Note: It is important to emphasize the fact that this mode only works if the native system in which the template is used is Debian 8 (amd64), although it might be possible to make it work on any 64 bit Debian based system.
# wget http://pnaf.honeynet.org.mx/download/chroot_pnaf.tar.bz2 # tar -jxvf chroot_pnaf.tar.bz2 # mount -t sysfs sysfs chroot_pnaf/sys # mount -t proc proc chroot_pnaf/proc # mount -o bind /dev chroot_pnaf/dev # mount -o bind /dev/pts chroot_pnaf/dev/pts # chroot chroot_pnaf
Similarly, it can be tested that PNAF works properly by running:
# pnaf_auditor --help
This installation mode is very simple. It only need to download an image of a virtual machine (OVA file) that contains a pre-installed and configured PNAF environment under a Debian system. This OVA file can be imported using either VirtualBox or Vmware.
Menu File/Import appliance/ and select the OVA file in order to create the virtual machine. This virtual machine includes a chroot directory with all the tools that the installer is able to deploy. The login credential are shown in the Welcome screen itself once the virtual machine is started.
Figure 5. Pre-configured virtual machine with PNAF environment
Once the user is logged in, it is necessary to switch to the PNAF environment included in a chroot directory.
# mount -t sysfs sysfs chroot_pnaf/sys # mount -t proc proc chroot_pnaf/proc # mount -o bind /dev chroot_pnaf/dev # mount -o bind /dev/pts chroot_pnaf/dev/pts # chroot /root/chroot_pnaf
This installation mode is intended to be used when some tools are already installed and configured on the system, so the PNAF core itself (Perl module) is used to process all the information generated by such tools. However, it is not recommended to use this mode since it implies that a huge set of parameters need to be specified on the configuration files, which would make the framework very prone to fail. Thus, it is recommended to use any of the aforementioned installation modes instead.
If you really need to use an independent installation, then just install the Perl module:
# cd pnaf # vim build/pnaf/Pnaf/lib/Pnaf/Core.pm (set all the parameters: paths, binaries, configuration files, etc.) # cd build/pnaf/Pnaf # perl Makefile.PL # make # make test # make install
Version 0.1.2 takes all the configuration options directly from the arguments passed during execution. In order to see the available option of PNAF (pnaf_auditor), it can be used the following options:
# pnaf_auditor –-help
In addition, in order to visualize the versions of the tools included on the built version:
# pnaf_auditor –-version
In case any specific configuration is needed (e.g. a specific path or rules file for suricata, log files for prads, etc), all the configuration files within the directory /pnaf/etc can be set.
This PoC will show how to perform a basic analysis of network traffic files using PNAF. It has to be emphasized that PNAF extracts and interprets information in different ways, depending the purpose and depth of the desired analysis. Thus, the information presented on this PoC does not represent all the findings that can be obtained using PNAF.
The following table describes the kind of information and purpose obtained on this general analysis.
Type of data | Purpose |
Asset identification | Identification of assets that perform activities within the network including their type of link connection, protocols involved, usage rates, platforms, software, among others. |
Security events (IDS based alerts) | Identification of potential anomalous or malicious activities based on IDS data. |
Resources | Identification of resources that provide information of workflow activities as well as data sources such as URL, domains, transferred files, etc. |
Software audit | Passive identification of software that is being used within the network. This information is taken as baseline to identify potential vulnerabilities based on CVEs. |
Having the PCAP file test1.cap, pnaf_auditor is executed as follows:
# pnaf_auditor –-cap test1.cap –log_dir /pnaf/www/test1
These options specify that the file will be taken by the tools used by PNAF and the output data will be stored within /pnaf/www/test1 directory.
Figure 6. PNAF generic processing execution
Now, assuming that a more specific analysis is needed, it is possible to execute pnaf_auditor using the following options:
# pnaf_auditor –-cap test2.cap –log_dir /pnaf/www/test2 --home_net 192.168.1.0/24 –-payload
With these parameters pnaf_editor will analyze the pcap file test2.cap, taking the network segment 192.168.1.0/24 as “home_net”, which is the internal network of theorganization. It is possible to specify the home_net using CIDR format. Furthermore, it is specified that payloads will be decoded in case any IDS alert is triggered. This is specially useful to analyse and identify potential false positives.
In order to get a basic meaningful information, based on a bunch of raw data, the analysis can be done through different stages.
Logs generated during the execution are displayed on the standard output (Figure 7 below). This phase is important since the analyst can check what tools are being used to retrieve raw logs, as well as the basic overview of parsed events and assets audit.
Figure 7. Execution log and summary
PNAF provides a basic web visualization that includes the following data:
All JSON data generated by PNAF can be used and interpreted within the framework itself, however it is important to emphasize that such data can be also exported to feed data analysis systems such as SIEM.
In order to use the basic web visualization, it is necessary to enable the web server Apache.
# apachectl start
By default, all the findings are stored in /pnaf/www directory. When pnaf_auditor is executed, –log_dir option can be used to specify that the output directory is set directly within the webdir. In the running example the output directory was set on /pnaf/www/test2 which can be accessed directly through a web browser on http://localhost or the corresponding IP address of the server where PNAF has been deployed.
Figure 8. PNAF basic web visualization
The web directory has the following structure (practical example on Figure 9):
DIRECTORY_NAME/ (Raw logs generated by tools) | |----- JSON/ (Parsed files in JSON format) | | | |---SUMMARY/ (JSON tree view of dataset and audits) | | | (This is the main basic visualizer) | | | | | |---dataset (Parsed data of all toolsets) | | |---auditSummary (Summary of audit information) | | |---dataset.html (All software found within trafic) | | |---auditOutput (Audit based on CVE (NIST) and software) | | |---dataset.html (Audit data sorted per single asset) | | | |-------VIEW1/ (Alternative JSON viewer) | | | |-------VIEW2/ (Deprecated)
Figure 9. Files generated for web visualization
The analysis of this PoC is performed from general data to specific findings. First, it is useful to review the file json/summary/dataset.html. Here, the analyst can visualize data logs generated by all the tools using JSON viewers. Each tree has two main categories:
Depending on the depth of the analysis, it is possible to dig into details on each dataset, as well as perform searching using the textbox embedded on the viewer.
Figure 10. Dataset of tools used in PNAF
The next step on the analysis involves checking the parsed and correlated data stored on the file /json/summary/auditSummary.html . Here, the analyst can visualize detailed information of each asset identified on the network traffic. For instance, it is possible to review information about URLs, SSL certificates, IDS alerts, transferred files, software, etc. Moreover, it is possible to review the audit correlation through a Tracking category (just as the main dataset explained before), in which audit data is sorted out by single asset. In order to do so, the file /json/summary/auditTracking.html can be accessed.
Figura 11. Audit summary. Main correlation
Figure 12. Audit summary. Tracking category (sorted by assets)
Finally, the file /json/summary/auditOutput.html shows findings about vulnerabilities in software identified within the network traffic, based on CVE database[3]. This analysis includes a score that measures the impact of the aforementioned vulnerabilities. Furthermore, a list of assets identified within blacklists (IP & domain name based and taken from trusted sources: e.g. EmergingTheats DB) is presented.
Figure 13. Audit summary. Vulnerability and blacklisted asset analysis based on trusted databases
Taking into consideration all the data gathered by the tools, the information interpreted by PNAF, as well as the meaningful (specific) interpretation performed by the analyst herself, then a big picture of the context and characteristics of the network can be determined. In fact, the kind of information that should be filtered and put focus on, depends upon the kind of problem, context and issue that needs to be identified.
It is very important to note that PNAF is prone to false positives due to the nature of PNA itself, in which the single input and potential lack of complete datasets (e.g. actual logs from applications, etc) may cause a miss interpretation and inaccurate correlation, leading to inaccurate findings that need to be verified manually by the analyst himself.
Currently PNAF is under development. Version 0.1.2 is the last version of 0.1 branch. Next versions will include improvements mainly on the visualization of the results, stability, ease of deployment and integration with external software for data analysis. For additional information you can follow the activities on the official blog of the UNAM-Chapter of the Honeynet Project and its development repository:
[1] Passive Network Audit Framework, Master thesis. Santillan, Javier. Eindhoven University of Technology. The Netherlands. 2014
[2]Tabla 1. “Herramientas de análisis de tráfico de red” del artículo anterior
]]>
El contenido de este artículo será publicado en el número 25 de la revista .Seguridad del UNAM-CERT.
El modelo general de PNAF (Figura 1), define el funcionamiento y flujo de datos a través del cual PNAF decodifica, filtra e interpreta información a partir del tráfico de red.
Figura 1. Modelo de análisis de Passive Network Audit Framework (PNAF)
PNAF incluye una serie de herramientas[3] para captura y análisis de tráfico de red. Debido a sus características y capacidades, algunas de estas herramientas por sí mismas pueden involucrar complejos procesos de instalación y configuración. Por esta razón, PNAF está diseñado para proveer modos de instalación que faciliten y automaticen el proceso de manera que el analista pueda hacer uso del framework sin mayor problema. Existen cuatro modos de instalación los cuales se explican a continuación.
PNAF incluye un instalador que automatiza la descarga, compilación y configuración de todas las herramientas. Este instalador incluye un Wizard (asistente de instalación) basado en dialog. Para poder utilizar este modo de instalación es necesario cumplir los siguientes requerimientos:
Es posible su funcionamiento en Ubuntu u otra distribución basada en Debian, sin embargo implica verificar las equivalencias en paquetes instalados por Apt. Asimismo, es posible usar el instalador en otros sistemas no basados en Debian siempre y cuando se instalen manualmente todas las dependencias necesarias para la compilación de las herramientas. Para esto se puede consultar el archivo README e instalar las dependencias equivalentes de la lista de Apt/emerge.
Debido a que PNAF instala una gran cantidad de dependencias, se recomienda instalar el framework en un ambiente chroot para evitar cualquier problema de compatibilidad de dependencias en el sistema nativo. En esta prueba de concepto se hará de esa manera y el proceso se explica a continuación.
Asumiendo que se cuenta con un sistema Debian 8 de 64 bits (amd64):
# aptitude install debootstrap
# debootstrap --arch amd64 jessie chroot_pnaf http://ftp.mx.debian.org/debian
# mount -t sysfs sysfs chroot_pnaf/sys
# mount -t proc proc chroot_pnaf/proc
# mount -o bind /dev chroot_pnaf/dev
# mount -o bind /dev/pts chroot_pnaf/dev/pts
Ahora se cambia al ambiente chroot
# chroot chroot_pnaf
# cd ~
Opción 1: Desde el repositorio oficial del proyecto
# aptitude install git
# git clone https://dev.honeynet.org.mx/traffic-analysis/pnaf.git
Opción 2: Desde el mirror en github
# git clone https://github.com/jusafing/pnaf
Una vez descargado, ingresar al directorio y ejecutar el instalador
# cd pnaf
# ./install.sh
Esto ejecutará el asistente. Primero se deberá confirmar que se desea instalar PNAF. Posteriormente se pueden seleccionar las herramientas que se incluirán en el framework. A pesar de que no todas las herramientas se utilizan en esta versión de PNAF (v0.1.2), se recomienda seleccionar todas para utilizarlas de manera independiente. Visto de este modo, PNAF es también un asistente para la instalación de herramientas de análisis de tráfico de red.
Figura 2. Selección de herramientas en la instalación de PNAF
Si es la primera vez que se instala PNAF se debe seleccionar una instalación limpia “clean installation”. En caso de que exista una instalación previa, la instalación limpia eliminará cualquier herramienta y archivos instalados por PNAF. Si solo se desea agregar o reinstalar ciertas herramientas, se debe seleccionar “NO” en este paso.
Figura 3. Selección del tipo de instalación
A partir de ese momento el instalador comenzará a compilar y configurar todas las herramientas. Este proceso puede durar aproximadamente 30 minutos dependiendo de las capacidades del equipo. En caso de que exista un error en el proceso de instalación, el instalador mostrará el mensaje correspondiente y se pueden verificar los archivos install.log e install.log.exec para identificar el problema. De lo contrario, si el proceso terminó correctamente, PNAF ha quedado instalado y listo para usarse.
Como recomendación, para actualizar las variables de ambiente hay que salir del ambiente chroot y volver a entrar. Asimismo, para identificar cuando se esté dentro del directorio de chroot, es conveniente agregar una etiqueta al shell :
# echo 'PS1="(PNAF) $PS1"' >> ~/.bashrc
# exit
# chroot chroot_pnaf
Para verificar que PNAF se ha instalado correctamente:
# pnaf_auditor --help
Figura 4. Opciones de ejecución de PNAF
El segundo modo de instalación corresponde al uso de un directorio chroot con todas las herramientas pre-compiladas y pre-configuradas. Esta alternativa básicamente evita todo el proceso de compilación y creación del directorio raíz con debootstrap presentada en el modo anterior. Por otro lado, facilita tener una plantilla con un directorio preparado para usar con chroot. Usando este modo solo es necesario descargar el archivo empaquetado .tar.bz2 (aproximadamente 1.3Gb) y desempaquetarlo en el sistema de archivos local.
Es importante mencionar que este modo funciona solo si el sistema local en el que se planea instalar es Debian 8 amd64 (la compilación de todas las herramientas depende de la arquitectura y de las versiones de las dependencias usadas por Apt).
# wget http://pnaf.honeynet.org.mx/download/chroot_pnaf.tar.bz2
# tar -jxvf chroot_pnaf.tar.bz2
# mount -t sysfs sysfs chroot_pnaf/sys
# mount -t proc proc chroot_pnaf/proc
# mount -o bind /dev chroot_pnaf/dev
# mount -o bind /dev/pts chroot_pnaf/dev/pts
# chroot chroot_pnaf
Igualmente se puede verificar que PNAF se ha instalado correctamente:
# pnaf_auditor –help
En este modo de instalación es necesario descargar una imagen de máquina virtual en formato OVA para ser importando con VirtualBox o Vmware.
En el menú File/Import appliance/ seleccionar el archivo OVA y crear la máquina virtual
Esta máquina virtual tiene instalado PNAF con todas las opciones mostradas en el instalador. Las credenciales de acceso para el usuario root se muestran en el mensaje de bienvenida una vez que se inicia la máquina virtual.
Figura 5. Máquina virtual pre-configurada con PNAF
Una vez dentro de la máquina virtual se debe ingresar nuevamente al directorio con chroot.
# mount -t sysfs sysfs chroot_pnaf/sys
# mount -t proc proc chroot_pnaf/proc
# mount -o bind /dev chroot_pnaf/dev
# mount -o bind /dev/pts chroot_pnaf/dev/pts
# chroot /root/chroot_pnaf
Esta opción incluye la instalación del core (núcleo) de PNAF, es decir, instalación independiente del módulo de Perl. Este modo se puede utilizar cuando se desee usar PNAF con una instalación propia de las herramientas. Sin embargo, no es recomendable ya que se necesitan configurar una gran cantidad de opciones incluyendo la ruta de los archivos binarios de cada una de las herramientas, archivos de configuración, logs, etc. Para esto, una vez descargado PNAF, editar la configuración de cada una de las herramientas:
# cd pnaf
# vim build/pnaf/Pnaf/lib/Pnaf/Core.pm (establecer rutas)
# cd build/pnaf/Pnaf
# perl Makefile.PL
# make
# make test
# make install
La mayoría de las opciones de configuración se definen directamente como argumentos al momento de la ejecución del auditor de PNAF (pnaf_auditor).
Para visualizar las herramientas incluidas en el framework se puede ejecutar
# pnaf_auditor –-version
Para mayor información sobre las opciones disponibles en PNAF 0.1.2
# pnaf_auditor –-help
En caso de necesitar una configuración específica, por ejemplo agregar firmas del IDS Suricata, se pueden modificar los archivos de configuración dentro del directorio /pnaf/etc
A continuación se analizarán tres archivos de captura en formato PCAP. La flexibilidad de las herramientas usadas por PNAF permite extraer e interpretar la información de maneras diferentes. El análisis en esta prueba de concepto no representa la totalidad de información que se puede obtener. Así, la PoC incluye un análisis general los archivos de captura de manera que se obtenga la siguiente información y cuyo propósito se explica en la siguiente tabla:
Información a identificar | Propósito |
Identificación de activos | Identificación de los equipos que participan en el tráfico de red incluyendo estadísticas de uso por tipo de conexión, protocolos, tasas de transferencia, etc. |
Posible eventos de seguridad (alertas de IDS) | Identificación de posibles actividades anómalas o maliciosas a partir de un motor IDS |
Recursos que se acceden | Identificación de recursos como URLs, dominios, archivos transferidos |
Auditoría de software usado en la organización | Identificación pasiva del software utilizado en la red tanto por clientes como por servidores. A partir de esta información se lleva a cabo la identificación de potenciales vulnerabilidades basadas en CVE. |
Teniendo el archivo de captura test1.cap, se ejecuta pnaf_auditor de la siguiente manera:
# pnaf_auditor –-cap test1.cap –log_dir /pnaf/www/test1
Esto ejecutará una serie de herramientas y procesará la información almacenando los resultados en el directorio /pnaf/www/test1
Figura 6. Ejecución de PNAF
Ahora, asumiendo que se desea obtener un filtrado específico se puede ejecutar pnaf_auditor con las siguientes opciones
# pnaf_auditor –-cap test2.cap –log_dir /pnaf/www/test2 --home_net 192.168.1.0/24 –-payload
En esta ejecución se indica que se analizará el archivo de captura test2.cap y que la red de la organización “home_net” es el segmento 192.168.1.0/24. (Se pueden indicar más segmentos en formato CIDR[4] separados por comas). Asimismo, se indica que se desea extraer el payload en caso de identificar una alerta de IDS (útil para análisis a fondo y verificación de falsos positivos).
La interpretación de la información se puede llevar a cabo en distintas etapas.
El log generado durante la ejecución muestra el resumen de los resultados. Esta fase es importante porque se obtiene información sobre las herramientas utilizadas, asi como del panorama general de los datos obtenidos. La siguiente figura muestra la explicación del log generado por PNAF.
Figura 7. Log de ejecución y resultados generales de PNAF
PNAF permite una visualización de los resultados a través de una interfaz web básica. Esta interfaz permite listar:
Para poder utilizar la interfaz web es necesario activar el servidor web apache incluido en PNAF.
# apachectl start
Usando la configuración default, todos los directorios de resultados que se almacenen en /pnaf/www e indicados en la opción –log_dir, podrán ser visualizados en web, usando http://localhost o la dirección IP específica donde se ejecute PNAF.
Figura 8. Visualización web básica de PNAF
Dentro de este directorio se tiene la siguiente estructura y se muestra un ejemplo en la Figura 9:
Figura 9. Archivos generados para la visualización web de PNAF
El análisis en esta PoC va de lo general a lo particular. Primeramente se puede dar un vistazo general en el contenido del archivo json/summary/dataset.html. Aquí, el analista puede acceder a la información clasificada de las herramientas. Cada herramienta contiene dos categorías principales, Summary (resumen de los datos) y Tracking (información por activos -IPs, servers, etc-). Según la necesidad del analista y los hallazgos encontrados, se pueden extraer datos a profundidad por cada herramienta y filtrar la información mediante el cuadro de búsqueda en cada árbol de herramienta.
Figura 10. Conjunto de datos (datasets) de las herramientas usadas en PNAF
Continuando con el análisis, ahora se visualiza el filtrado y pre-procesamiento de datos generados por PNAF, el cual lleva a cabo una correlación básica y conjunta la información creando diferentes categorías. Para ello se accede al archivo /json/summary/auditSummary.html y es aquí donde el analista puede extraer información detallada de la actividad de cada uno de los activos que intervienen en el tráfico de red. Por ejemplo, se puede obtener información sobre URL, certificados SSL, alertas IDS, archivos transferidos, Software utilizado, etc. De la misma manera, si la auditoría se prefiere hacer tomando como clasificación general a los activos, entonces se puede visualizar el archivo /json/summary/auditTracking.html
Figura 11. Resumen de auditoría. Clasificación general
Figura 12. Resumen de auditoría. Clasificación por activos
Finalmente, el archivo /json/summary/auditOutput.html muestra el resultado del análisis de vulnerabilidades basadas en CVE[6] y versiones de software encontradas. Este análisis incluye un sistema de puntaje (score) que indica el posible impacto de las vulnerabilidades identificadas. Asimismo, se muestra la lista de equipos identificados en listas negras de dominios o IP o cuya interacción estuvo involucrada con equipos de la red.
Figura 13. Resumen de auditoría. Análisis de vulnerabilidad de software basado en CVE
Conjuntando toda la información recopilada y filtrada tanto por PNAF como por el mismo analista, es posible determinar el estado general y características de la red. La información detallada dependerá del tipo de problema o necesidad que desea resolver.
Finalmente, es importante hacer énfasis en el hecho de que PNAF es susceptible a falsos positivos debido a la naturaleza misma de PNA, en donde, al no contar con la información completa y obtener datos a partir de una interpretación del tráfico de red, cierta información podría representar hechos erróneos. Así, una de las tareas del analista implica la identificación y verificación de información certera.
Actualmente PNAF se encuentra en desarrollo en la versión 0.2. Futuras versiones incluirán cambios significativos en la interfaz web y estabilidad del framework. Para actualizaciones consultar las páginas del proyecto.
[1] Frameworks para monitoreo, forense y auditoría de tráfico de red I. Revista .Seguridad número 24.
[2] Passive Network Audit Framework, Master thesis. Santillan, Javier. Eindhoven University of Technology. The Netherlands. 2014
[3]Tabla 1. “Herramientas de análisis de tráfico de red” del artículo anterior
[4] https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing
[5] https://en.wikipedia.org/wiki/JSON
[6] https://cve.mitre.org/
]]>
Actualmente existen diversas técnicas y tecnologías para el monitoreo del tráfico de red. Las redes de datos manejan información con protocolos y aplicaciones cada vez más complejas. Esto, combinado con la gran cantidad de información que se transfiere y la migración paulatina a modelos de comunicación codificados o cifrados, ha hecho también del monitoreo una tarea cada vez más compleja.
En los últimos años se han desarrollado tecnologías de análisis de datos como los SIEM (Security Information and Event Management), SIM (Security Information Management), SEM (Security Event Management), NSM (Network Security Monitoring), PNA (Passive Network Audit), etcétera. Estas tecnologías han ido madurando a través de la adición de nuevos modelos de análisis de información e incluso de nuevos mecanismos de detección e identificación de patrones, usando el aprendizaje de máquina o machine learning. En este contexto, existen también diversas técnicas y herramientas que pueden ayudar a los administradores a desarrollar o elegir un modelo de monitoreo, detección y auditoría que mejore el nivel de seguridad de sus organizaciones.
Ciertas técnicas podrían ser más efectivas, dependiendo del contexto del monitoreo y tomando en cuenta sus características, ventajas y enfoque. La Figura 1 presenta un panorama general sobre la relación entre los modelos de monitoreo y detección que se abordan en este artículo y que proveen lineamientos para desarrollar o implementar frameworks usando diversas tecnologías.
Es un modelo de análisis de tráfico de red que proporciona lineamientos para desarrollar un framework que incluya técnicas y herramientas para monitoreo, detección y retención de evidencia sobre incidentes de seguridad. Este modelo está basado en el análisis de datos generados por herramientas de seguridad como los IDS (Intrusion Detection Systems), analizadores de flujos, entre otros. NSM hace énfasis en las técnicas a seguir para poder alcanzar una mejor detección, es decir, no solamente describe qué herramientas pueden ser utilizadas, también cómo, cuándo y dónde utilizarlas dentro del contexto de la red, así como las consideraciones de implementación, zonas y puntos de monitoreo. Una de las herramientas más conocidas y utilizadas en este tipo de framework es Sguil[1], un front-end para el análisis de datos extraídos del IDS Snort[2] y el analizador de flujos Argus[3], entre otras herramientas.
Dentro del proceso de atención a incidentes de red (Network Incident Response Process) mostrado en la Figura 2, NSM está involucrado en la fase de Detección (Detect), específicamente en dos de sus procesos: Contención Pronta del Incidente (Short Term Incident Containment), donde se tiene información sobre el incidente detectado; y en Emergencia (Emergency), donde se identifica y provee evidencia del incidente. Asimismo, NSM describe el llamado Modelo de Referencia de Intrusiones (Reference Intrusion Model)[5] el cual define cuatro tipos de datos:
En relación a NSM y la detección de intrusos, algunos debates[6] mencionan que los desarrolladores de IDS buscan una “detección inmaculada”, es decir, detección precisa; mientras que los practicantes de NSM buscan una “colección de datos inmaculada”, es decir, captura de evidencia tanto como sea posible.
La minería de datos es un proceso de extracción de modelos descriptivos a partir de grandes cantidades de datos, mediante el uso de modelos de análisis estadísticos, machine learning, entre otros. En el contexto de la seguridad en TI, la minería de datos se aplica en los llamados SIEM (Security Information and Event Management) para la identificación de patrones con propósitos de detección, auditoría e interpretación de información. Las fuentes de datos a analizar pueden ser herramientas como IPS (Intrusion Prevention Systems o Sistemas de Prevención de Intrusiones), IDS, firewalls, routers, bitácoras de sistemas, etcétera. Como se muestra en la Figura 3, a partir de estos datos se lleva a cabo una correlación (correlation) con el objetivo de filtrar información (reduction) para identificación e interpretación de eventos específicos relacionados, por ejemplo, con incidentes de seguridad.
Los SIEM combinan características de los SIM (Security Information Manager) y de los SEM (Security Event Manager), cuyos enfoques en términos generales son el análisis en tiempo real (SIM) y almacenamiento a largo plazo de registros de eventos (SEM).
Entre las características principales que los SIEM proporcionan están:
Actualmente existen herramientas SIEM open source tales como OSSIM de Alien Vault[8]. También existen opciones comerciales que integran algunas características adicionales, sin embargo el fundamento base es proveer características de un SIEM. Algunas de ellas son Alien Vault USM[9], Tenable SIEM [10], Splunk[11], entre otros.
De manera similar a los SIEM, la Auditoría Pasiva de Tráfico de Red (Passive Network Audit) involucra el análisis de bitácoras y correlación de datos, sin embargo, lo que define a PNA como un modelo de análisis independiente a los SIEM es el uso de tráfico de red como su fuente principal y única para la obtención de información y generación de reportes. A su vez, PNA implica solamente la utilización de herramientas pasivas para la extracción de información, es decir, ninguna acción llevada a cabo durante el proceso de análisis altera o interviene en la operación de la red que se analiza.
Mientras los SIEM se basan en acumulación de datos (data aggregation) de diversas fuentes como firewalls, bitácoras de sistemas, IDS, IPS, routers, etcétera, PNA se enfoca al tráfico de red como fuente de información. Como se aprecia en la Figura 4, la acumulación de datos (“Multiple data aggregation”) se hace de manera interna, ya que involucra un proceso adicional que es el procesamiento y decodificación previa de datos (“Pre-processing & decoding”) para generación de “bitácoras” o datos que normalmente serían la fuente de información inicial para un SIEM, sin embargo, en este caso son obtenidos sólo a partir del tráfico de red y son en realidad una “aproximación” a bitácoras reales. Esto quiere decir que en realidad dicha extracción implica una interpretación y en ciertos casos una extrapolación de información a partir de datos que representen una “firma” sobre determinada actividad o sistema (por ejemplo, el tráfico de headers HTTP puede contener datos para generar información similar que normalmente se obtendría a partir de una bitácora de un servidor web como Apache, etcétera). Así, a partir de este preprocesamiento es posible entonces identificar y decodificar protocolos, versiones de software, dominios, alertas de IDS, flujos, etcétera que comúnmente serían tomados de bitácoras de sistemas u otros dispositivos, con la ventaja de que todo el proceso se desarrolla de manera pasiva y únicamente a partir de tráfico de red.
PNA también se conoce como Identificación Pasiva de Red (Passive Network Discovery) y algunas fuentes[12] la describen como una tecnología para responder a las preguntas ¿Quién y qué hay en la red de la organización? y ¿Qué se está haciendo en la red de la organización?, mediante identificación de utilización de la red, análisis forense de eventos, identificación de vulnerabilidades y perfiles de activos (equipos, servidores, entre otros).
Una desventaja de PNA es que el análisis puede ser limitado y no muy preciso debido a que el tráfico de red puede no contener datos suficientes para identificar y generar información confiable sobre la seguridad y el estado de la red.
A continuación se presenta una introducción al prototipo de un framework de PNA llamado Passive Network Audit Framework (PNAF) (Santillan, 2014). Este framework define un modelo de análisis (Figura 5) para auditoría de tráfico de red a través de la utilización de diversas herramientas las cuales se conjuntan en una implementación de software libre. En este artículo se presenta una breve introducción sobre las características del framework, sin embargo en el próximo número se presentará una prueba de concepto con detalles sobre instalación, configuración y análisis de una muestra de tráfico de red.
Las principales características de PNAF son:
La siguiente tabla presenta un panorama general de algunas de las herramientas que pueden ser utilizadas dentro de PNAF. Cada una de ellas tiene un propósito específico de modo que la información se correlaciona para la identificación de activos y la determinación del contexto de la red.
Herramienta
|
Propósito
|
Datos generados
|
Observaciones
|
Enumeración e identificación de activos (Profiling and Enumeration)
|
|||
P0f
|
Enumeración de red y servicios.
|
Tipos de conexión (Capa 1), versiones de software y plataformas, roles de equipos.
|
Detección mediante múltiples métodos: firmas y comportamiento.
|
Snort Open AppId
|
Identificación de aplicaciones.
|
Tipos de aplicaciones usadas en la red.
|
Identificación mediante análisis de protocolos y no mediante número de puerto.
|
Prads
|
Enumeración de red y servicios.
|
Tipos de conexión (Capa 1), VLAN, versiones de software y plataformas.
|
Detección mediante múltiples métodos.
|
Motores de detección de intrusos (IDS Engines)
|
|||
Suricata
|
Motor IDS, decodificador de capa de aplicación, captura en tiempo real.
|
Alertas basadas en firmas, datos de HTTP, TLS, DNS, SSH, extracción de archivos transferidos.
|
Detección flexible por firmas (signatures), parsers de capa de aplicación y captura de alto rendimiento.
|
Snort IDS
|
Motor IDS.
|
Alertas basadas en firmas.
|
Detección flexible por firmas (signatures).
|
Bro IDS
|
Motor IDS, decodificador de protocolos y verificador de políticas.
|
Alertas de IDS, datos decodificados de capa de aplicación como HTTP, TLS, DNS, SSH.
|
Conjunto de parsers de capa de aplicación.
|
Análisis de flujos de tráfico de red (Network Flow Analysis)
|
|||
Cxtracker
|
Análisis de flujos.
|
Estadísticas de tráfico de red.
|
Análisis de gran cantidad de tráfico.
|
Argus
|
Análisis de flujos.
|
Estadísticas de flujos de tráfico de red, protocolos y decodificación de paquetes.
|
Método eficiente para análisis de grandes cantidades de tráfico.
|
Silk
|
Análisis de flujos.
|
Estadísticas de tráfico de red.
|
Análisis de gran cantidad de tráfico.
|
Tcpflow
|
Reensamblado de sesiones TCP y decodificación HTTP.
|
Datos HTTP.
|
Análisis de payloads.
|
Tcpdstat
|
Identificación de protocolos.
|
Estadísticas de protocolos.
|
Clasificación por capas de protocolos.
|
Inspección profunda de paquetes (Deep Packet Inspection)
|
|||
Chaosreader
|
Decodificación de capa de aplicación.
|
Datos HTTP, DNS, FTP, SMTP.
|
Análisis de payloads.
|
PassiveDNS
|
Análisis pasivo de DNS.
|
Estadísticas de DNS.
|
Identificación de malware basado en DNS (como Fastflux).
|
Tcpxtract
|
Extracción de archivos transferidos.
|
Lista de archivos transferidos.
|
Útil para identificación de malware y violación de políticas.
|
TcpExtract
|
Extracción de archivos transferidos.
|
Lista de archivos transferidos.
|
Basado en Python.
|
Httpry
|
Decodificación de protocolo HTTP.
|
Datos de HTTP y payloads.
|
Análisis a fondo de HTTP.
|
Xplico
|
Extracción de datos de capa de aplicación.
|
Datos HTTP, archivos, información de protocolos.
|
Tiene su propia interfaz web.
|
Nftracker
|
Extracción de archivos transferidos.
|
Lista de archivos transferidos.
|
Útil para identificación de malware y violación de políticas.
|
Ssldump
|
Extracción de información de protocolos SSLv3/SSL.
|
Información de certificados.
|
Útil en análisis de cadenas de confianza (basadas en PKI) mediante certificados.
|
PNAF puede ser utilizado sobre entornos GNU/Linux y su utilización es mediante la línea de comandos (CLI, Command Line Interface). El framework se alimenta de tráfico de red, el cual es analizado usando las herramientas mencionadas en la tabla anterior de modo que el administrador puede visualizar un resumen de una auditoría básica de tráfico de red.
Para mayor información y actualizaciones de PNAF se pueden consultar los siguientes sitios web.
Referencias
[4] Richard Bejtlich. The Tao of network security monitoring: beyond intrusion detection. Pearson Education, 2004.
[5] Richard Bejtlich. The Practice of Network Security Monitoring: Understanding Incident Detection and Response. No Starch Press, 2013.
[6] Post by Richard Bejtlich’s on TaoSecurity blog. http://taosecurity.blogspot.nl/2007/03/ nsm-and-intrusion-detection-differences.html
[12] Ofir Arkin. Demystifying the myth of passive network discovery and monitoring systems. http://www.mcafee.com/us/resources/white-papers/wp-demystifying-passive-network-discovery.pdf
Feel free to ask anything or request help for development
miguelraulb at gmail dot com
Installation Linux Debian installation instructions
Once you have all the modules installed you just have to create a database called spampot or whatever you wish to name it, create a user with password and then assign the name of your database to the user you’ve already created.
Please set this values on the spampot-ng.conf
file.
In order to run the tool you have to run it with sudo or using a wrapper as authbind, here are the instructions
sudo perl spampot-ng.pl
authbind --deep perl spampot-ng.pl
Miguel Raúl Bautista Soria
]]>PNAF v0.1.1 public prototype is an implementation of a TU/e master thesis developed as internship project at Fox-IT B.V in The Netherlands. This public prototype DOES NOT include any internal information about TU/e nor Fox-IT.
From Version 0.1.2, PNAF is a project of UNAM-Chapter [The Honeynet Project]
Version 0.1.2 will get just minor updates (bugs/parsing) and it is the last version of 0.1.x branch. You can either clone this repository and install it on your standalone machine, or download the pre-installed sources available on http://pnaf.honeynet.org.mx/download/
The next version of PNAF is 0.2.x and it is the current main dev project. It will contain significant changes (dockerized?, improved installation, parsing, daemon model, multi-threading support, etc). If you have any feedback/idea please drop an email (see contact information below).
PNAF is a framework intended to provide the capability of getting a security assessment of network plattforms by analysing in-depth the network traffic (in a passive way) and by providing a high-level interpretation in an automated way. It combines different analysis techniques and tools. The framework is intended to achieve the following goals:
PNAF is comprised by three main modules. Each module has its own engines which manage specific tools and process the data.
PNAF is written in Perl, why? because Perl rules!
The current version has been tested on GNU/Linux Debian (6.x or later) and Gentoo (Stage 3) distributions. The main installer prepares automatically the whole environment by compiling all the tools included within the framework as well as their dependencies.
Since the installer downloads some packages using either apt or emerge depending on the distribution, then the installer needs to have access to Internet. Otherwise you can use the option ‘–no-packages’ and then install by yourself the following packages/libraries:
autoconf automake binutils-dev bison build-essential byacc ccache cmake dsniff flex g++ gawk gcc libcap-ng-dev libcli-dev libdatetime-perl libdumbnet-dev libfixposix0 libfixposix-dev libgeoip-dev zlib1g zlib1g-dev libgetopt-long-descriptive-perl libglib2.0-cil-dev libjansson4 libjansson-dev libldns-dev liblzo2-2 libnet1-dev libmagic-dev libmysql++3 libmysqlclient-dev libmysql++-dev libnacl-dev libncurses5-dev libldns1 libnetfilter-conntrack-dev libnetfilter-queue1 libnetfilter-queue-dev libnet-pcap-perl libnfnetlink0 libnfnetlink-dev libnl-3-dev libnl-genl-3-dev libpcap-dev libpcre3 libpcre3-dbg libpcre3-dev libsqlite3-dev libssl-dev liburcu-dev libyaml-0-2 libyaml-dev liblzo2-dev openssl pkg-config python-dev python-docutils sqlite3 swig git-core libglib2.0-dev libtool tcpslice tcpick tshark tcpflow ethtool
autoconf automake binutils bison libtool byacc ccache cmake flex gawk gcc dev-util/cmake sys-libs/libcap-ng dev-perl/glib-perl dev-libs/jansson dev-libs/lzo net-libs/libnet dev-libs/libnl virtual/perl-libnet dev-libs/geoip net-libs/libnetfilter_queue net-libs/libnetfilter_conntrack perl-core/libnet dev-perl/Net-PcapUtils dev-perl/Net-Pcap net-libs/libnfnetlink dev-db/sqlite dev-libs/libyaml dev-lang/swig net-analyzer/tcpflow dev-libs/libcli net-analyzer/dsniff dev-perl/DateTime ethtool
Config::Auto Pod::Usage Proc::Daemon IO::CaptureOutput JSON:XS Cwd JSON::Parse Time::Piece Exception::Class Test::Warn Test::Differences Test::Deep Test::Most HTTP::BrowserDetect Getopt::Long String::Tokenizer URI::Encode Devel::Hexdump Digest::MD5 Data::Dumper YAML NetPacket::Ethernet Net::Subnet
You can install the whole framework (i.e. including the tools) by using the installer script. It has been tested on both Debian 7.x / Gentoo Stage 3 based systems (clean installation, base system, chrooted)
./install.sh
Alternatively you can install the Core Framework (without tools) by using the Makefile. In such a case you need to specify a bunch of option within the PNAF configuration file (binary files, configuration files, log dirs,..). For more information check out the ‘build/pnaf/etc/pnaf.conf’ file.
To install this module type the following:
$ cd build/pnaf/Pnaf
$ perl Makefile.PL
$ make
$ make test
# make install // (as root)
To use the CHROOT way, just download the chroot directory, unpack it in your
local file system and just execute the following:
# chroot chroot_pnaf
(This README file will be shown when you switch to that directory)
NOTE: This way just works using Debian 8 amd64.
Import the OVA image using VirtualBox or Vmware. Login credentials are given in the welcome login screen. (You may need to change/add virtual network interfaces to meet local configuration requirements)
$ pnaf_auditor [options]
Execution:
--debug : Enable debug mode
--conf : Specify configuration file (yaml)
--help : Show this
--version : Show tools versions
--parser arg1[,arg2] : Specify parsers to be loaded
'p0f' : Process enumeration data
'prads' : Process enumeration data
'argusFlow' : Process NFA data (flow analysis)
'snortAppId' : Process enumeration data (App identification)
'httpry' : DPI over HTTP (URL's, UA, etc)
'tcpdstat' : Process enumeration data (protocol dist)
'suricataEve' : Process IDS data (alerts and payloads)
'bro' : DPI over different protocols
'tcpflow' : Process NFA data (session tracking)
--out_dataset : Specify the kind of output data to generate
'all' : Generate all datasets
'audit' : Generate only audit dataset
--home_net : Specify the 'homenet' in CIDR format
--payload : Flag to enable payload decoding (IDS data)
Inputs:
--cap_file : Set input capture file (pcap)
--audit_dict : Path to vulnerability dictionary
--instance_dir : Path to directory with 'initial raw dataset'
Logging:
--log_dir : Path to log directory
--log_file : Path to output directory
$ pnaf_auditor --cap_file test1.cap --log_dir /pnaf/www/test1
Note: input directory must contains actual raw logs that are generated by Tools (e.g. Snort unified2 files, Suricata JSON output, p0f logs, etc
$ pnaf_auditor --instance_dir existinglogs --log_dir /pnaf/www/exlogs
$pnaf_auditor --cap_file test2.cap --log_dir /pnaf/www/test2 --parser bro,snort,suricataEve
$pnaf_auditor --cap_file test3.cap --log_dir /pnaf/www/test3 --homenet 192.168.1.0/14,192.168.2.30/27
$pnaf_auditor --instance_dir mysnortfiles --payload
A (very) basic Web visualization can be used within PNAF.
First, To start HTTP daemon:
# /pnaf/bin/apachectl
Then, when executing pnaf_auditor, place output directories within /pnaf/www/. If you already got some outpudt directories, then copy them to this path.
Output data stored in ‘–log_dir’ contains a tree as follows:
DIRECTORY_NAME/ (Raw logs genrated by tools)
|
|----- JSON/ (Parsed files in JSON format)
| |
| |---SUMMARY/ (JSON tree view of dataset and audits)
| | | (This is the main basic visualizer)
| | |
| | |---dataset (Parsed data of all toolsets)
| | |---auditSummary (Summary of audit information)
| | |---dataset.html (All software found within trafic)
| | |---auditOutput (Audit based on CVE (NIST) and software)
| | |---dataset.html (Audit data sorted per single asset)
| |
| |-------VIEW1/ (Alternative JSON viewer)
| |
| |-------VIEWs/ (Deprecated)
Copyright (C) 2014 by Javier Santillan
This framework contains external tools that have their own licenses. For more information about licensing you can read the corresponding licence files that are included within the tarballs that this framework uses for an automated installation. Such packages have not been modified and any information about licenses/authors is as it can be found on the corresponding releases (oficial websites, github, etc). For more information of versions used by this framework, you can check out the ‘–version’ option of pnaf_auditor.
PNAF does not claim any rights, modifications nor ownerships. The PNAF core itself (Perl module included on this tarball within build/pnaf), is authored by -Javier Santillan- and the licence cited below applies only to PNAF itself.
PNAF core is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. Also add information on how to contact you by electronic and paper mail.
PNAF v0.1.2 Copyright (C) 2014 Javier Santillan This program comes with ABSOLUTELY NO WARRANTY; for details type `–help’
option on pnaf_auditor. This is free software, and you are welcome to redistribute it under certain conditions.
,
]]>The UNAM Honeynet Project is a non-profit security researchers group, dedicated to the security and honeypot research that belongs to the UNAM’s Computer Emergency Response Team (UNAM-CERT).
How long our honeypots have been deployed?
We have been working since 2002 with honeypot technology within our university network, since then we have studied the tactics and motives of the Black Hat community involved in security incidents within our network, letting us have an addtional way to monitor our network, being an irreplaceable resource in our dialy academic and research activities.
Objectives
]]>