miércoles, 21 de mayo de 2014

Auditing Security of a Linux System


The purpose of this post is to detail what type reviews will be performed on a linux computer to determine if it meets the security requirements of the PCI DSS standard. To do this, whenever possible, I will detail the commands to use in each case.

However, although the main purpose is to audit compliance with PCI DSS, the proposed revisions can be used as a starting point for any security audit of a linux computer you want to perform.

All the commands in this post have been tested on Ubuntu 12.04 computer, so it is possible that some of them need to be modified to work properly on other Linux distributions. We can use the
lsb_release-a command for the exact version of the system we are reviewing, or obtain it from the /etc/os-release.

Requirement 1: Install and maintain a firewall configuration to protect cardholder data


The command

Iptables -L -v

will show the firewall rules used in the system. In case of a laptop, you should review compliance with PCI DSS 1.4 that required to install and mantain a personal firewall. In any case, you should review the rules defined in the fw because in certain circumstances can serve as a compensating control in the absence of compliance with other requirements of the standard.

Requirement 2: Do not use vendor-supplied defaults for system passwords and other security parameters


To verify some aspects
To verify some aspects of compliance with this requirement, we can use the following commands:

Dpkg -l

This command allow us to list all installed packages in order to detect unnecessary packets that should have been uninstalled.


route -n

This command allows us to list all the routes defined in the system.

Additionally, analysing the following files we could determine if it has changed the name resolution of the system:


/etc/resolv.conf
/etc/hosts
/etc/nsswitch.conf

Also, you must check the next file to detect if exist unnecessary or predefined user accounts that should have been deleted or disabled:

/etc/passwd

Likewise, you should check out the company's hardening guide and identify any additional evidence that should be adquired to ensure it is being properly applied.

It is also important to identify which is the primary function of this server, and use the review to identify any package or service that does not make sense for that primary function. For example, if the primary server role is to act as a web server, it makes sense that we locate apache packages installed, but would not have it we found packages of Oracle or Nessus. The existence of these packages could make us suspect that the server is being used for more than one primary function and therefore the requirement 2.2.1 is not in place.

We can use the following command to list all running processes and services listening on the UDP and TCP ports to verify that there are no processes or unnecessary services running and all that are running are adequately documented and justified:

ps -edf
Lsof -i UDP -n -P
Lsof -i TCP -n -P

We should aldo review this folder to detect scheduled tasks:

/var/spool/cron/crontabs

Additionally, we review this list of processes and services to identify insecure protocols (such FTP, Telnet, etc.) and check that they have been documented and implemented additional security measures for these protocols.

Finally, to complete the review of this requirement, we will review the following file to check the existing SSH configuration on the server:

cat /etc/ssh/sshd_config

In this file we can verify which port SSH is running, what versions are allowed (should only be permitted v2 because v1 is vulnerable) and what encryption protocol is being used to ensure that is a sufficiently robust protocol. Additionally, you should check that the value of AllowTcpForwarding is "no", unless is justify the need to use this server as jumping server to manage other systems.

Requirement 6: Develop and maintain secure systems and applications


To check this requirement, we have to validate that there are no unsafe versions of software on the system. With this purpose in mind, we can use the following commands:

Uname -a

This command allow us to know witch kernel version is used and verify that there are not know vulnerabilities for that version, or in other words, that the kernel is correctly patched.

In the other hand, with the next command we can list all the packages installed in the system and their versions, so we can also check if there are any package vulnerable in the system. Remember that to meet this requeriment you must to install security patches for all the software included in the PCI DSS scope:

Dpkg -l

Last, but not least, we shoud review the next file to verify that there are not developers or testing user accounts. This kind of accounts must be deleted before the system or the apps are deployed in production environment:

/etc/passwd

Requirement 7: Restrict access to cardholder data by business need to know


In order to verify compliance with the PCI DSS requirement 7, you can perform the following checks:

/etc/sudoers
/etc/pam.d/sudo
/etc/pam.d/su

In these files we can check which users have permission to increase their privileges to root and under what conditions they can. All cases should be properly documented and justified.

We should also review the perms of the next file and any backup that it could have to be sure it can not be open or edited for any user:

/etc/shadow

On the other side, we should check that the setuide files can not be edited by don't authorized users to increase their system privileges. We could use next command for this purpose:

find / -perm -4000 -ls 2> /dev/null

Next commands allow us to list all files that can be open or edited by any user and are not located on /proc folder:

find / -type f -perm -006 2>/dev/null | grep -v /proc
find / -type f -perm -002 2>/dev/null | grep -v /proc

We should analyze these files to check if exists a justification for the privileges that are defined in each case.

In addition, we should review the next file to verify what shell have assigned each account:

/etc/passwd

Also, we should review next file to check if are defined any restriction to the users login:
Así mismo, se deberá revisar el fichero

/etc/security/access.conf

This file allow to limit the kind of access that some accounts can have. In example, you can configure it to prohibit the remote access to the root account or the console access to some user or app accounts.

Finally, you should review the next file to verify that the line “none *” exists and is not commented, as well as there are no users with extra capabilities without a justified reason for it:

/etc/security/capability.conf


Requirement 8: Identify and authenticate access to system components


To check the major part of PCI DSS requirement 8 we should review the next file:

/etc/pam.d/common-password

In this file we can find what algoritm is used to hash the passwords stored in /etc/shadow and verify if it is used pam_cracklib.so to configure a password policy that meets requirement 8.2.1 of PCI DSS.

Requirement 10: Track and monitor all access to network resources and cardholder data


To analyze compliance with this requirement of PCI DSS must be reviewed two aspects; time configuration and syslog settings.

Reviewing next file we know the UTC time zone being used by the system:

/etc/timezone

This other command allow us to verify the NTP Servers configuration for the time synchronization of the system:

Ntpdate

On the other side, next command allow us to know if syslog process is running:

ps -edf | grep syslog

Reviewing the next file we can know if syslog is configured to receive events from other systems or devices and what permits will have the generated log files:

/etc/rsyslog.conf

Finally, reviewing this file (or its equivalent defined in first lines of the file /etc/rsyslog.conf) we can know what events are generated and where they are saved or sent. On this way, we can verify if all the security events included on the PCI DSS scope are stored centralized as the standard requires:

/etc/rsyslog.d/50-default.conf


Requirement 11: Regularly test security systems and processes


Check what type of file integrity monitoring solution is installed. Depending on the type of solution being used, we must do appropriate revisions to ensure that the requirement 11.5 of PCI DSS. ie, at least weekly, the solution should check the changes made to files considered critical as system executables, application executables, parameter files, etc.


I hope you enjoy and find useful this post. If you have found any error or you wish propose any improvement, please, don't hesitate to propose it in a comment.


Twitter: @omarbenjumea

http://about.me/omarbenjumea

lunes, 19 de mayo de 2014

Auditar la seguridad de un sistema Linux


El propósito de este post es detallar qué tipo de revisiones se deben realizar en un equipo linux para determinar si cumple con los requisitos de seguridad del estándar PCI DSS. Para ello, siempre que sea posible, vamos a detallar los comandos a utilizar para obtener la información necesaria en cada caso.

No obstante, aunque el propósito principal sea auditar el cumplimiento de PCI DSS, las revisiones propuestas pueden utilizarse como punto de partida para cualquier revisión de seguridad de un equipo linux que se quiera realizar.

Todos los comandos indicados en este post han sido probados en un equipo Ubuntu 12.04, por lo que es posible que algunos de ellos deban ser modificados para que funcionen correctamente en otras distribuciones de linux. Podemos utilizar el comando lsb_release -a para conocer la versión exacta del sistema que estamos revisando, o bien obtenerla del archivo /etc/os-release.

 

Requisito 1: Install and maintain a firewall configuration to protect cardholder data


El comando

Iptables -L -v

mostrará las reglas de firewall utilizadas en el equipo. En caso de tratarse de un equipo portátil, se debería revisar el cumplimiento del req 1.4 de PCI DSS que exige que se instale y se mantenga un firewall personal en este tipo de equipos. En todo caso, es aconsejable revisar las reglas de fw definidas en el equipo ya que en determinadas circunstancias pueden servir como control compensatorio ante la ausencia de cumplimiento de otros requerimientos del estándar.

 

Requisito 2: Do not use vendor-supplied defaults for system passwords and other security parameters


Para verificar algunos aspectos del cumplimiento de este requisito, podremos utilizar los siguientes comandos:

Dpkg -l

Nos permitirá listar todos los paquetes instalados con objeto de detectar paquetes innecesarios que debieran haber sido desinstalados.

route -n

Nos permitirá listar todas las rutas definidas en el sistema. Adicionalmente, el análisis de los siguientes ficheros nos permitirá determinar si se ha modificado la resolución de nombres del sistema o si se ha personalizado el encaminamiento:

/etc/resolv.conf
/etc/hosts
/etc/nsswitch.conf

Adicionalmente, se debería revisar el archivo

/etc/passwd

para detectar la existencia de cuentas de usuario innecesarias o por defecto que deberían haber sido ser borradas o deshabilitadas.

Así mismo, se debería revisar la guía de hardening documentada por la organización para este tipo de sistemas e identificar cualquier comprobación adicional que deba ser realizada para garantizar que está siendo correctamente aplicada.

También es importante identificar cual es la función primaria de este servidor, y aprovechar la revisión para identificar cualquier paquete o servicio que no tenga sentido para dicha función primaria. Así, por ejemplo, si la función primaria del servidor es la de actuar como servidor web, tendrá sentido que localicemos paquetes de apache instalados, pero no lo tendría que encontráramos paquetes de Oracle o Nessus. La existencia de dichos paquetes nos podría hacer sospechar que el servidor se está utilizando para más de una función primaria y por lo tanto se está incumpliendo el requisito 2.2.1.

Podemos utilizar los siguientes comandos para listar todos los procesos en ejecución, así como los servicios escuchando en los puertos UDP y TCP con objeto de verificar que no hay procesos o servicios innecesarios ejecutándose y que todos los que se están ejecutando están adecuadamente documentados y justificados:

ps -edf
Lsof -i UDP -n -P
Lsof -i TCP -n -P

También se debería revisar el contenido de la carpeta

/var/spool/cron/crontabs

para detectar la existencia de tareas programadas.

Adicionalmente, deberemos revisar este listado de procesos y servicios para identificar protocolos inseguros (FTP, Telnet, etc..) y verificar que se hayan documentado e implementado medidas de seguridad adicionales para estos protocolos.

Finalmente, para terminar con la revisión de este requisito, revisaremos el siguiente fichero para revisar la configuración de SSH existente en el servidor:

cat /etc/ssh/sshd_config

En este archivo podemos verificar en qué puerto se ejecuta SSH, qué versiones se permiten (únicamente debería estar permitida la v2, ya que la v1 es vulnerable) y qué protocolo de cifrado se está utilizando para garantizar que se utiliza un protocolo suficientemente robusto. Adicionalmente, se debería revisar que el valor de AllowTcpForwarding sea “no”, al no ser que se justifique la necesidad de utilizar este servidor como salto para administrar otros equipos.

 

Requisito 6: Develop and maintain secure systems and applications


Para revisar este requisito, tenemos que validar que no existen versiones inseguras de software en el sistema. Con este propósito en mente, podemos utilizar los siguientes comandos:

Uname -a

Este comando nos permitirá conocer la versión del kernel y verificar que no existan vulnerabilidades conocidas para esta versión, es decir, que el kernel esté correctamente parchedo.

Por otro lado, con:

Dpkg -l
listaremos todos los paquetes instalados en el sistema y sus respectivas versiones, por lo que podremos realizar la misma operación buscando versiones para las que existan vulnerabilidades conocidas y que por lo tanto debieran estar parcheadas o actualizadas para cumplir este requisito de PCI DSS.

Finalmente, se deberá analizar el fichero

/etc/passwd

para verificar que no existen cuentas de usuario correspondientes a personal de desarrollo ni cuentas de pruebas o testing que no hayan sido borradas en la puesta en producción del sistema.

 

Requisito 7: Restrict access to cardholder data by business need to know


Con el propósito de verificar el cumplimiento del requisito 7 de PCI DSS, se pueden realizar las siguientes revisiones:

/etc/sudoers
/etc/pam.d/sudo
/etc/pam.d/su

En estos ficheros podremos revisar qué usuarios tienen permiso para aumentar sus privilegios a root y en qué condiciones pueden hacerlo. Se deberá comprobar que todos los casos estén debidamente documentados y justificados.

Se deberá revisar que ni el fichero

/etc/shadow

ni sus posibles backups puedan ser leídos por los usuarios.

Por otro lado, se deberá comprobar que los ficheros setuid no puedan ser editados por usuarios no autorizados para aumentar de esta manera sus privilegios en el sistema. Podemos utilizar el siguiente comando para dicha revisión:

find / -perm -4000 -ls 2> /dev/null

Los siguientes comandos nos permitirá listar los ficheros que pueden ser leídos por cualquier usuario y que no están ubicados en /proc:

find / -type f -perm -006 2>/dev/null | grep -v /proc
find / -type f -perm -002 2>/dev/null | grep -v /proc

Se deberán analizar los ficheros obtenidos para ver si existe una justificación para los permisos que tienen establecidos.

Por otro lado, se deberá revisar el fichero

/etc/passwd

para verificar qué shell tiene asignada cada usuario y qué usuarios no tiene asignada ninguna shell.

Así mismo, se deberá revisar el fichero

/etc/security/access.conf

para comprobar si existen restricciones en el login de usuarios. Este fichero permite configurar limitaciones al tipo de acceso que puedan tener determinadas cuentas, por ejemplo, impidiendo el acceso remoto a la cuenta root, o el acceso mediante consola a determinadas cuentas de usuario o aplicación.

Finalmente, se deberá revisar el fichero

/etc/security/capability.conf

para confirmar que existe la linea “none *” no comentada (sin #), y que no se han asignado capacidades extras a usuarios sin que exista un motivo justificado para ello.

 

Requisito 8: Identify and authenticate access to system components


Para verificar la mayoría de los aspectos incluidos en el requisito 8 de PCI DSS será necesario revisar el archivo

/etc/pam.d/common-password

En este archivo podremos revisar qué algoritmo se está usando para el hash con el que se guardan los passwords en /etc/shadow y verificar si se está usando pam_cracklib.so para configurar una política de contraseñas suficiente para dar cumplimiento al requisito 8.2.1 de PCI DSS:

 

Requisito 10: Track and monitor all access to network resources and cardholder data


Para analizar el cumplimiento de este requisito de PCI DSS debemos revisar dos aspectos; la configuración de tiempo y la configuración de syslog.

Revisando el siguiente archivo podremos conocer la zona de tiempo UTC que está siendo utilizada por el sistema:

/etc/timezone

Mediante el siguiente comando, podremos verificar la configuración de servidores NTP que está siendo utilizada para la sincronización horaria del sistema:

Ntpdate

Por otro lado, el siguiente comando nos permitirá saber si el proceso de syslog está habilitado:

ps -edf | grep syslog

Revisando el fichero

/etc/rsyslog.conf

se puede verificar si está habilitado el servicio syslog para recibir eventos de otros sistemas o dispositivos y qué permisos van a tener los ficheros de logs generados.

Finalmente, mediante la revisión del fichero

/etc/rsyslog.d/50-default.conf (o su equivalente indicado al principio del fichero /etc/rsyslog.conf)

podremos identificar qué eventos se están generando y en qué rutas se están guardando estos ficheros de logs (o a qué servidores se están enviando). De esta manera, podremos verificar si se está cumpliendo el requisito de centralizar todos los eventos de seguridad generados por los sistemas incluidos en el alcance de PCI DSS.

 

Requisito 11: Regularly test security systems and processes


Revisar qué tipo de software de monitorización de integridad de ficheros tiene instalado el sistema. En función del tipo de mecanismo que se esté utilizando, se deberán realizar las revisiones pertinentes para garantizar que se cumple el requisito 11.5 de PCI DSS, es decir, que al menos semanalmente se comprueban la modificaciones realizadas en ficheros considerados críticos como ejecutables del sistema, ejecutables de aplicaciones, ficheros de parámetros y configuraciones, histórico de logs u otros archivos que no deban cambiar frecuentemente y se consideren críticos para la seguridad del sistema o de los datos.


Espero que la entrada os guste y os sea de utilidad y, por supuesto, si alguien detecta algún error o tiene alguna sugerencia de mejora de cara a realizar este tipo de auditorías, se agradecerá cualquier aportación al respecto.

¿Aún no me sigues en twitter?: @omarbenjumea
http://about.me/omarbenjumea

lunes, 31 de marzo de 2014

PCI DSS & Incident Response Planning

No organization is safe from suffering a security incident. It may take more or less suffer and solve it, be more or less severe, or even can not find out you're having a security incident (no, I will not talk about APTs this time), but at some point your organization will need to respond to an incident.

Therefore, every organization should have an incident response plan consistent with the potential safety impact of a security incident can result for your business. The absence of a response plan security incidents can significantly increase the response time to an incident and may even cause a not adequate response that finish aggravating the incident's impact.

Paragraph 12.10 v3 PCI DSS requires organizations affected by the standard to implement a response plan and be prepared to respond immediately to any compromise on their systems. In this sense, what is required by the standard is the plan includes within its scope all the key elements that are necessary for the organization to respond effectively in the event that the incident might affect the cardholder data. But considered in developing a response plan, I think it is ridiculous to stick only to the scope of PCI DSS because with little more effort we can have a response plan that reaches across the organization and enable us to respond in a effective and efficient way in case of an incident.

Let us see the steps to follow to develop a plan that allows us to meet the requirement of PCI DSS 12.10 but at the time we prepared to act on incidents involving other areas of our organization.

Preparation


In the preparation phase we carry out the following main activities :

  1. Clarify the scope of our Plan. Not the same prepare a Security Incident Plan to limit the scope only to incidents of Information Security, safety, property security , etc. To comply with PCI DSS, the scope of the Plan must include, at least, all critical systems within the scope of processing, storage and transfer cardholders data.
  2. It should define and document the roles and responsibilities of all participants in the Incident Response Plan.
  3. While many management methodologies proposed security incidents conducting a risk analysis, including the recently published NIST cybersecurity framework, I prefer making only one BIA (Business Impact Analysis ) that allows us to be clear what impact can have a incident in different fields (legal, financial , operational, human damage , reputation ). There are different methodologies or approaches for a BIA but my recommendation, especially in a first implementation of the Plan, is to opt for one that is simple enough to have a realistic BIA in a short space of time. Importantly, the BIA should not just analyse incidents that impair the availability of information, since it is not preparing the Plan Business Continuity, otherwise you have to take into account the impacts in terms of loss confidentiality and integrity of information.
  4. Define scenarios of incidents that can occur based on the analysis in the BIA. Ie document all those events that can cause major impacts identified in the previous section. It is recommended in a first draft of the Plan will not be overambitious and unify and group enough to guarantee the volume of scenarios is manageable. We did not do any useful if document 500 possible casuistic and then we will take 5 years to write response procedures for each of it...
  5. Document the mechanisms established to detect the realization of the scenarios defined in the previous phase. At this stage it is very likely that deficiencies or impossibilities in the detection of some of the scenarios are identified. In cases where feasible, prepare an improvement plan designed to implement controls or improvements to the detection of these scenarios in a tolerable time. In considering the elements that can trigger the process of incident management, PCI DSS requires that, at least, the monitoring systems of the organization are considered, such as IDS / IPS, firewalls or file integrity systems (FIM) events.
  6. Documenting the criteria for classification of incidents. You must define a taxonomy and criteria for classifying a potential incident in the relevant category. Again my recommendation is to prime the simplicity. We should not have more than 10 categories for the first level of classification of incidents.
  7. Documenting the action procedures in case of realization of each type of incident.These procedures should include or reference the BCP procedures that must be followed if the incident affects the business continuity. Additionally, to comply with PCI DSS, you must include or reference procedures for backup of data as well as any aspect or legal requirement to consider in case of incident. The procedures must include details of actions to be performed for:
    1. Contain the incident.
    2. Solving the incident.
    3. Recover normal operation
  8. Document strategies and procedures for communication to a security incident . Ie , what to say, who to say and how to say in each case, or in any case, clearly define who is responsible for making these decisions in case of incident. The damage to the image or reputation of the company can vary greatly depending on what is communicated and how to communicate following a security incident. To comply with PCI DSS these strategies should include, at a minimum, the procedure to communicate any compromise of card data to the payment card brands.
  9. The Plan must be communicated and distributed to all concerned and should ensure their availability for a potential incident. That is, if one of our scenarios is that by reason of a DoS we fall our corporate systems, we should not store our Incident Response Plan just in corporate systems, since we can not retrieve it when needed. Also, if one of the scenarios considered is the lack of access to the office, we did not do any good if we only have it printed on our desktop.
  10. It should define and establish the necessary way for anyone to notify the responsible occurrence of a possible incident. These routes should be simple, quick and have alternatives in case one of them fails.
  11. The incident response team should be adequately trained and with a 24x7 availability to act in case of an incident materialize to prevent the delay in resolution might aggravate their impact and consequences. On the other hand, have well documented procedures and team training are vital to prevent the activities undertaken to resolve the incident may degrade or corrupt the evidence necessary for proper forensic investigation of the incident.
  12. You need to plan a test plan that allows a high degree of assurance that the proposed Plan works correctly in case of incident. Testing will be performed at least annually, are critical to ensure that the defined procedures are truly effective and that all affected personnel have necessary knowledge thereof.
During the incident.

During the incident should note the following:

  1. It must follow the procedures defined in the Plan in each case.
  2. You must keep a detailed log of all the events and actions carried out during the incident.
  3. You should prioritize containment incident.
  4. Once content, you must proceed to its resolution.
  5. Finally, once resolved, should proceed to the recovery of the affected systems.

Continuous Improvement.

PCI DSS requires that a specific section of continuous improvement is included in the incident response plan so that the action and resolution in each security incident is analysed to detect areas improvement in the processes of incident detection or response.

To do this, you must analyse the outputs, understanding what happened and why it happened, for each of the incidents suffered as well as the tests done and analyse what improvements can be made in the Plan in several areas:
  • Improvements in the prevention of incidents.
  • Improved detection of incidents.
  • Improved containment and resolution of incidents.
  • Improved recovery of equipment or business.
  • Improvements in the test plan.
  • Improvements to the defined incidents scenarios.
  • Improved staff training or awareness.
Finally , it is also important to consider the plan within the change management of the organization, so that the Incident Response Plan is updated whenever changes in systems or in the organization leave obsolete any of the incident response procedures.

In short, it is to have a documented plan, distributed, tested and known to allow act in the best way and in the shortest possible time when a security incident happen in order to minimize the impact and consequences that the incident can cause to the organization.

jueves, 13 de febrero de 2014

Plan de Respuesta ante Incidentes de Seguridad & PCI DSS

No hay organización que esté a salvo de sufrir un incidente de seguridad.  Se puede tardar más o menos en padecerlo y en resolverlo, ser más o menos grave, o incluso puedes no enterarte de que estás teniendo un incidente de seguridad (no, tranquilos, no voy a hablar de APTs), pero en algún momento tu organización necesitará reaccionar ante un incidente.

Por ello, toda organización debería contar con un plan de respuesta ante incidentes de seguridad coherente con el impacto potencial que un incidente de seguridad pueda llegar a suponer para su negocio. La ausencia de un plan de respuesta ante incidentes de seguridad puede incrementar considerablemente el tiempo de reacción ante un incidente e incluso puede provocar que la respuesta no sea la adecuada y acabar agravando el impacto del mismo.

El apartado 12.10 de PCI DSS v3 requiere a las organizaciones afectadas por el estándar que implementen un plan de respuesta de este tipo y que estén preparadas para responder de inmediato ante cualquier compromiso en sus sistemas. En este sentido, lo que exije el estándar es que el plan de respuesta incluya en su alcance todos los elementos claves que son necesarios para que la organización responda de manera efectiva en caso de que el compromiso pueda afectar a los datos de titulares de tarjeta. Sin embargo, puestos a desarrollar un plan de respuesta, pienso que es ridículo ceñirse únicamente al ámbito de PCI DSS, ya que con poco más esfuerzo podemos contar con un Plan de Respuesta que alcance a toda la organización y que nos permitirá responder de una manera eficaz y eficiente en caso de que se produzca un incidente.

Veamos pues las pautas a seguir para desarrollar un Plan que nos permita cumplir con el requisito 12.10 de PCI DSS pero que a su vez nos prepare para actuar ante incidentes que afecten a otros ámbitos de nuestra organización.

Preparación


En la fase de preparación deberemos llevar a cabo las siguientes actividades principales:

1- Tener claro el alcance de nuestro Plan. No es lo mismo preparar un Plan ante Incidentes de Seguridad que acotar el alcance únicamente a incidentes de Seguridad de la Información, de seguridad laboral, de seguridad patrimonial, etc... Para cumplir con PCI DSS, el alcance del Plan debe incluir como mínimo, todos los sistemas críticos dentro del ámbito de procesado, almacenaje y transferencia de datos de titulares de tarjeta.

2- Se deben definir y documentar los roles y las responsabilidades de todos los participantes en el Plan de Respuesta ante Incidentes.

3- Aunque numerosas metodologías de gestión de incidentes de seguridad proponen la realización de un análisis de riesgos, incluido el recien publicado marco de ciberseguridad del NIST, yo soy partidario de realizar únicamente un BIA (Business Impact Analisys) que nos permita tener claro qué impacto puede tener un inciente en diferentes ámbitos (legal, financerio, operativo, daños humanos, reputación). Hay diferentes metodologías o aproximaciones para realizar un BIA pero mi recomendación, sobretodo en una primera implantación del Plan, es optar por una que sea suficientemente simple como para tener un BIA realista en poco espacio de tiempo. Es importante señalar que este BIA no debe limitarse a analizar incidentes que dañen la disponibilidad de la información, puesto que no se trata de preparar el Plan de Continuidad de Negocio, si no que se tiene que tener en cuenta también los impactos en cuanto a pérdida de confidencialidad e integridad de la información, así como otros tipos de incidentes no relacionados con la seguridad de la información en caso de que el alcance del Plan sea tal.

4- Definir que escenarios de incidentes se pueden producir partiendo del análisis realizado en el BIA. Es decir, documentar todos aquellos sucesos que puedan causar los principales impactos identificados en el punto anterior. Es recomendable en una primera redacción del Plan no ser excesivamente ambicioso y agrupar e unificar la respuesta ante incidentes de manera que el volumen de escenarios sea manejable. No nos servirá de nada documentar 500 posibles casuísticas si luego vamos a tardar 5 años en redactar los procedimientos de respuesta para cada una de ellas.

5- Documentar los mecanismos establecidos para poder detectar la materialización de los escenarios definidos en la fase anterior. En esta fase es muy probable que se identifiquen deficiencias o imposibilidades en la detección de algunos de los escenarios. En aquellos casos en los que sea viable, se debe preparar un plan de mejora destinado a implantar controles o mejoras que permitan la detección en un tiempo tolerable de dichos escenarios. Al considerar los elementos que pueden disparar el procedimiento de gestión de incidentes, PCI DSS obliga a que como mínimo se consideren los sistemas de monitorización de la organización, como son los IDS/IPS, los firewalls o los sistemas de monitorización de la integridad de los ficheros (FIM).

6- Documentar los criterios de clasificación de los incidentes. Se debe definir una taxonomía y los criterios para clasificar un potencial incidente en su correspondiente categoría. Nuevamente, mi recomendación es que prime la simplicidad no definiendo más de 10 categorías diferentes de incidentes para facilitar su clasificación.

7- Documentar los procedimientos de actuación en caso de materialización de cada tipo de incidente. Los procedimientos deben incluir el detalle de acciones a realizar para:
* Contener el incidente.
* Solventar el incidente.
* Recuperar la operativa normal.
Entre estos procedimientos, se deberán incluir o referenciar los procedimientos del Plan de Continuidad de Negocio que deban ser seguidos en caso de que el incidente afecte a la continuidad del mismo.
Adicionalmente, para cumplir con PCI DSS, se deberán incluir o referenciar los procedimientos de copias de respaldo de los datos y cualquier aspecto o requisito legal a considerar en caso de incidente.

8- Documentar las estrategias y procedimientos de comunicación ante un incidente de seguridad. Es decir, qué se debe decir, a quién se debe decir y cómo se debe decir en cada caso, o en todo caso, definir claramente quien es el responsable de tomar estas decisiones en caso de incidente. El daño a la imagen o la reputación de la compañía puede variar enormemente en función de qué se comunique y cómo se comunique a raíz de un incidente de Seguridad. Para cumplir con PCI DSS estas estrategias deberán incluir, como mínimo, el procedimiento a seguir para comunicar cualquier compromiso de datos de tarjeta a las marcas de tarjeta de pago.

9- El Plan debe ser comunicado y distribuido entre todos los afectados y se debe garantizar su disponibilidad durante un potencial incidente. Es decir, si uno de nuestros escenarios posibles es que por motivo de un DoS se nos caigan nuestros sistemas corporativos, no guardemos únicamente en ellos nuestro Plan de Respuesta ante Incidentes, puesto que no podremos recuperarlo cuando lo necesitemos. Así mismo, si uno de los escenarios contemplados es el no poder acceder a la oficina, tampoco nos serviría de nada tenerlo impreso en nuestro escritorio.

10- Se deben definir y establecer las vías necesarias para que cualquiera pueda notificar a los responsables la ocurrencia de un posible incidente. Estas vías deben ser sencillas, rápidas y contar con diversas alternativas por si una de ellas fallara.

11- El equipo de respuesta ante incidentes debe estar convenientemente entrenado y con una disponibilidad de 24x7 para actuar en caso de que se materialice un incidente para evitar que el retraso en su resolución pueda agravar su impacto y consecuencias. Por otro lado, la correcta procedimentación de la actuación y formación del equipo son vitales para impedir que las actividades realizadas para solventar el incidente puedan degradar o corromper las evidencias necesarias para la adecuada investigación forense del incidente.

12- Se debe planificar un plan de pruebas que permita tener un alto grado de seguridad de que el Plan propuesto funciona correctamente en caso de incidente. Las pruebas, que deberán realizarse como mínimo anualmente, son críticas para garantizar que los procedimientos definidos son realmente eficaces y que todo el personal afectado tiene conocimiento necesario de los mismos. En este sentido, será necesario probar únicamente aquellas tipologías de incidentes que no se hayan dado realmente durante el año, no siendo necesario probar los procedimientos que se hayan usado realmente durante el año, al no ser que se hayan sido mejorados o modificados.

Durante el incidente.


Durante el incidente se deben tener en cuenta los siguientes aspectos:

1- Se deben seguir los procedimientos definidos en el Plan en cada caso.
2- Se debe mantener una bitácora detallada con todos los sucesos y actuaciones llevados a cabo durante el incidente.
3- Se debe priorizar la contención del incidente.
4- Una vez contenido, se debe proceder a su resolución.
5- Finalmente, una vez resuelto, se debe proceder a la recuperación de los sistemas afectados.

Mejora continua:

PCI DSS, y cualquier metodología de gestión de incidentes de seguridad que se precie, exige que se incluya un apartado específico de mejora continua en el plan de respuesta ante incidentes de manera que se analice la actuación y resolución ante cada incidente de seguridad para detectar áreas de mejora en los procesos de detección o respuesta ante los incidentes.

Para ello, se deben analizar los outputs, entendiendo qué ha pasado y por qué ha pasado, para cada uno de los incidentes sufridos así como de las pruebas realizadas y analizar qué mejoras se pueden implementar en el Plan en diversos ámbitos:

* Mejoras en la prevención de los incidentes.
* Mejoras en la detección de los incidentes.
* Mejoras en la contención y resolución de los incidentes.
* Mejoras en la recuperación de los equipos o del negocio.
* Mejoras en el plan de pruebas.
* Mejoras en los escenarios de incidentes definidos.
* Mejoras en la formación del personal.

Por último, también es importante tener en cuenta el plan dentro de la gestión del cambio de la organización, de manera que se actualice el Plan de Respuesta ante Incidentes siempre que algún cambio en los sistemas o la organización deje obsoleto algunos de los procedimientos definidos.



En definitiva, se trata de contar con un Plan documentado, distribuido, probado y conocido que permita actuar de la mejor manera y en el menor tiempo posible ante un incidente de seguridad con el objetivo de minimizar el impacto en diversos ámbitos que dichos incidentes pueden suponer para nuestras organizaciones.

domingo, 8 de diciembre de 2013

PCI DSS 11.3: Pentest Methodology

As commented in the previous post, one of the new requirements of the PCI DSS v3 is to have a procedure that describes the methodology to be followed in conducting the  internal and external pen-test. I have developed a sample procedure that can be easily adapted to the specific casuistry of your Organization in order to meet the requirement 11.3 of the standard.

I hope you find it useful, and any comments or ideas for improvement are welcomed.

 

1. Introduction

 1.1 . Objectives

The purpose of this document is to establish a methodology for planning , implementation and review of the penetration testing to be performed annually in the Organization. This methodology, based on NIST SP 800-115 standard will follow a consistent and repeatable process in each of these tests , ensuring the quality and reliability of these.The responsibility for carrying out these intrusion tests annually is of XXXX department. The tests can be executed both by internal staff as always outsiders and when executed by specialists in testing intrusion that have the experience and knowledge .Finally , it should be noted that the purpose of the tests to be performed will identify vulnerabilities that could be exploited by an attacker to compromise the security of the systems of the Organization thereby compromising the confidentiality, integrity or availability of information stored, processed or transmitted by these.Note that this method includes all the minimum requirements set by the requirement 11.3 of the PCI DSS standard .

 1.2 . Scope

The scope of the penetration test includes the following elements :
  • External intrusion test, i.e. analysing the vulnerabilities that could be exploited by an attacker is located in the Internet:
    • Black box tests: with no users or prior information.
    • Grey box tests: not users, but having the details of the applications and the infrastructure of the organization perimeter .
    • White box test: With users to access systems, application or authenticated areas that want to be tested.
  • Internal intrusion, i.e. analyzing the vulnerabilities that could be exploited by an attacker with access to the internal network of the organization:
    • Black box tests:with no users or prior information.
    • Gray box tests: not users, but having the network diagram of the organization. Additionally, if there are several network segments used by users with different levels of privileges (eg, normal users and admin users ) are allowed to perform audit tests from various network segments.
    • White box tests: tests with domain users, system users or application users. The method to follow is to asign same profiles and access privileges to auditors who are assigned to the users you want to check the level of system security. For example , if we want to see is what a provider can leverage vulnerabilities to compromise the security of our organization, should be assigned to audit users with the same profile and privileges assigned to that provider.
  • Exploitability tests. For vulnerabilities identified in internal and external pentest these tests should check if you really are exploitable considering that the following conditions are met:
    • It was determined that the risk of executing the exploit is acceptable . Keep in mind that running an exploit always carries some risk of causing a denial of service or instability on the target system or application.
    • There is a publicly available exploit for the vulnerability.
    • Can be generated as an exploit at a time and with reasonable effort into the planning of the tests performed.
  • Documentation of the tests performed, the findings, their evidence, the conclusions reached and the recommendations made to address the vulnerabilities identified during testing.
  • Re-test and capture evidence after the resolution of each of the vulnerabilities reported during testing.

 1.3 . Assumptions and limitations

This section should be identified (if any) the assumptions or limitations applicable, both the organization and the team that performed the tests.
 

 1.4 . Risks

In this section should be listed the risks inherent in conducting penetration testing over the information systems of our organization. Additionally, it should be noted for each mitigation measures that will be taken. Examples might be:

Example 1#
  • Risk: Denial of Service in systems or network devices because the network scans.
  • Mitigation measure 1: network scans must be performed in a controlled manner. The start and end of the scan must be notify to responsible personnel to allow monitoring during testing. For any sign of trouble will abort the scan in progress.
  • Mitigation measure 2: scanning tools must be configured to guarantee that the volume of sent packets or sessions established per minute does not cause a problem for network elements. In this sense, we must perform the first scans in a very controlled way and use minimum configurations that may be expanded when is evident that the configuration is not dangerous for network devices or servers in the organization.
Example 2#
  • Risk: During testing, if auditors are successful in testing may have access to confidential information of the organization.
  • Mitigation Measure 1: Both the provider as organization and the individual professionals involved in testing must sign confidentiality agreements in which the responsibilities assumed in case of breach are stated.
  • Mitigation Measure 2: Documents and evidence generated by the audit team will have the classification of confidential information and should only be accessed by authorized staff based on the principle of need to know.
  • Mitigation Measure 3: The audit team will apply all necessary measures to ensure that the confidentiality of information organization can't be compromised because of the tests performed. These measures include encryption of reports and evidence and masking of any sensitive data that is included in the reports or evidence generated .

2 Logistics

 2.1. Staff

Key staff involved in the project by the organization will be listed :
  • Technical Project Manager: XXXXX
  • Chief Information Security Officer: XXXXXX
  • Chief Information Officer: XXXXX
  • Head of Communications: XXXXX
  • Responsible for web site YYYY.com: XXXXX
Telephones and emails to contact all personnel involved in the tests (both, supplier and Organization) are listed in the Annex I "contact sheets" of this document.

Is particularly important to correctly identify the  people to contact in case of major incident, both by the supplier and by the Organization.

 2.2 . Calendar

Penetration testing must include a schedule detailing where the main tasks and milestones to be achieved during testing. In this sense, they should be planned at least the following dates:
  • Pre-project activities
  • Meeting of Project Start
  • Start and end of external tests
  • Start and end of internal testing
  • Project monitoring meetings
  • Delivery reports
  • Presentation of results
  • Meeting project completion

 2.3 . Location of evidence

External intrusion tests will be performed remotely from the supplier's premises .Internal intrusion tests will be conducted in the office XXXX of the Organization. Audit team must to have access to the Organization's network.It must manage access permissions to the building early enough to ensure that the audit team can access without problems during planning period .

 2.4 . Equipment for performing the tests

All the tests will be conducted from the equipment owned by the audit team so no equipment for the execution of the tests is required.The only requirement in this regard will be to have an active network connection for each member of the audit team. Those connections must provide access to the target network segment in every case.

3 Communication strategy

 3.1 . General communication

The following meetings between the audit team and the organization will be conducted during the course of the project :
  • Previous meeting
    • Channel : Telephone
    • Required Attendees : XXXXXX
    • Optional Attendees: XXXXXX
  • Kick-off Meeting
    • Channel : Face to face meeting in the office of the Organization YYYYY.
    • Required Attendees : XXXXXX
    • Optional Attendees: XXXXXX
  • Meeting Follow-up 1
    • Channel : Telephone
    • Required Attendees : XXXXXX
    • Optional Attendees: XXXXXX
  •  Meeting Update 2
    • Channel : Telephone
    • Required Attendees : XXXXXX
    • Optional Attendees: XXXXXX
  • Meeting presentation of results
    • Channel : Face to face meeting in the office of the Organization YYYYY.
    • Required Attendees : XXXXXX
    • Optional Attendees: XXXXXX
  • Closing meeting
    • Channel : Face to face meeting in the office of the Organization YYYYY.
    • Required Attendees : XXXXXX
    • Optional Attendees: XXXXXX

 3.2 . Incident Response and Management

If an incident occurs during the execution of the tests that have an impact on the systems or services of the organization, the incident should be brought immediately to the attention of those responsible for incident management in the project. Contact phones are detailed in Annex II "Contacts Incident". This annex also includes scaling procedures to resolve the incident.

The provider will follow the instructions of the incident management team of the organization to contain and solve any impact caused by penetration testing.


Having identified an incident, penetration testing must be stopped immediately and will not be resumed until receiving authorization from the technical manager of the project.


4 . Target systems and networks

It should be noted that in order to complies with PCI DSS the scope of the test should include, at least the following :
All systems and applications that are part of the perimeter of the cardholder data environment card (CDE ).

 4.1 . Systems included in the scope

  • System 1: IP: System: System Description
  • System 2: IP: System: System Description
  • Wifi network XXXXYYYYY
  • ................

 4.2 . Applications included in the scope

  • Application 1: URL: Description of the application 
  • ...................

 4.3 . Systems excluded from the scope

  • System 5: IP: System: System Description
  • System 6: IP: System: System Description
  • ....................

 4.4 . Applications excluded from the scope

  • Application 3: URL: Description of the application
  • .....................

  

5. Executing the tests

 5.1 . No technical evidence

Non- technical tests to be performed during penetration testing are detailed in this section. Note that some of these tests can be combined with technical tests to increase their effectiveness:
  • Attempted access to the facilities of the organization without identification , posing as employees of the Organization.
  • Review of bins or containers for sensitive information of the organization.
  • Attempt to obtain confidential information using social engineering techniques, both onsite and telephone .
(Note that these tests are an example. Each organization can add or remove evidence of this type according to your circumstances and objectives) .

 5.2 . technical tests

Technical tests must be follow the OSSTMM methodology. Tests must be conducted at network, system and application level and must ensure that at least identifies any vulnerabilities documented by OWASP and SANS ,as well as those identified in the PCI DSS standard v3:

  • Inejections: Code, SQL, OS commands, LDAP , XPath , etc.
  • Buffer overflows .
  • Insecure storage of cryptographic keys
  • insecure Communications
  • Improper error handling
  • Cross -site scripting (XSS )
  • Control of inappropriate access.
  • Cross - site request forgery (CSRF ) .
  • Broken authentication and incorrectly session management.
  • Any other vulnerability considered High Risk by the organization.
Additionally, we must carry out tests to validate the effectiveness of the controls established to segment the data environment cardholders (CDE ) from other systems and networks of the Organization.

  

6. Information Management

Note that all information generated as part of the audits will be owned by the organization and will have the classification of Confidential. Therefore, it must be stored and transmitted ever in encrypted way.

Reports and evidence generated should only be accessed by authorized personnel based in the need to know principle. 

 
Information concerning the audit will be stored only for a term of X years, being securely deleted and unrecoverable after that period.


The supplier undertakes to store the information on audit only for a period of X months, thus committing itself to eliminate it safely and unrecoverable after that period.

 6.1 . evidence

For all findings or vulnerabilities identified during the tests carried out will be generated and documented sufficient evidence to prove the existence of the same. The format of the evidence can be variable in each case, screen capture, raw output of security tools, photographs, paper documents , etc.

 6.2 . deliverables

As a result of tests performed should generate a document containing at least the following sections:
  1. Introduction
  2. Executive Summary
  3. Methodology
  4. Identified vulnerabilities
  5. Recommendations for correcting vulnerabilities
  6. Conclusions
    Annex I: Evidence