Archivo

Posts Tagged ‘security’

Install Kubernetes Goat (ES)

junio 13, 2021 Deja un comentario
Kubernetes Logo

En estos dos ultimos años estoy muy involucrado en proyectos revisando intraestructuras basadas en contenedores Docker y Kubernetes, en esta busqueda encontré con este genial proyecto que facilita el aprendizaje de vulnerabilidades en Kubernetes.

Kubernetes Goat está diseñado para ser un entorno de clúster intencionalmente vulnerable para aprender y practicar la seguridad de Kubernetes. Es un proyecto creado por Madhu Akula.

En este articulo, veremos como realizar la instalación sobre un equipo con Ubuntu 20.04 y VirtualBox. Kubernetes Goat necesita una instalación previa de Minikube el cual facilita tener un cluster local de Kubernetes.

A.- Instalar Minikube

1.- Descarga de Minikube

Podemos descargar la última versión o una versión específica de la página de versiones de Minikube. Una vez descargado, necesitamos hacerlo ejecutable y agregarlo a nuestra RUTA:

$ curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 && chmod +x minikube && sudo mv minikube /usr/local/bin/

2.- Iniciar Minikube

Podemos iniciar Minikube con el comando de inicio de minikube, que inicia un clúster de un solo nodo con la última versión estable de Kubernetes.

$ minikube start

3.- Comprobar el estado

Con el comando de estado de minikube, mostramos el estado de Minikube:

$ minikube status

B.- Instalar Kubernetes Goat

1.- Descargar el proyecto

# git clone https://github.com/madhuakula/kubernetes-goat.git

# cd kubernetes-goat/

2.- Configurar la cuenta helm2 rbac e inicializar tiller

# kubectl apply -f scenarios/helm2-rbac/setup.yaml

# helm2 init –service-account tiller

3.- Desplegar Helm chart para verificar la configuración ,

implementación del escenario helm chart metadata-db

# helm2 install –name metadata-db scenarios/metadata-db/

4.- Desplegar los manifiestos de escenarios vulnerables

# kubectl apply -f scenarios/batch-check/job.yaml

# kubectl apply -f scenarios/build-code/deployment.yaml

# kubectl apply -f scenarios/cache-store/deployment.yaml

# kubectl apply -f scenarios/health-check/deployment.yaml

# kubectl apply -f scenarios/hunger-check/deployment.yaml

# kubectl apply -f scenarios/kubernetes-goat-home/deployment.yaml

# kubectl apply -f scenarios/poor-registry/deployment.yaml

# kubectl apply -f scenarios/system-monitor/deployment.yaml

# kubectl apply -f scenarios/hidden-in-layers/deployment.yaml

5.- Crear el forwardeo de puertos en los PODS para permitir el acceso local.

# bash access-kubernetes-goat.sh

6.- Igresar a Kubernetes Goat

Si todo salio bien , ahora podremos ingresar a la aplicación de la siguiente forma:

Ingresar a : http://127.0.0.1:1234/

Finalmente, Si desean practicar los escenarios pueden revizarlos aqui : https://madhuakula.com/kubernetes-goat/index.html

Espero les siva

@jroliva

Anuncio publicitario

Pre-Commit Hooks con Talisman[DevSecOps]

Luego de unas semanas de receso obligatorio por que me infecte del COVID mas feo de este mundo, casi no la cuento, pero ya estoy bien!! no se preocupen 😀 , haciendo lo que mas gusta 😀

Es asi que retomamamos el tema de #DevSecOps, El integración continua de código (CI) hace que muchas veces se tengan almacenadas de forma equivocada información confidencial, como claves de acceso, tokens de acceso, claves SSH, entre otros elementos que aveces son necesarios almacenar localmente para luego subir al repositorio.

Talisman es una herramienta que instala un enlace al local y cuando trabajemos con GIT/GITLAB etc,etc. para garantizar que estos elementos llamados «secretos» o la información confidencial no salgan de la estación de trabajo del desarrollador al realizar los comits.

1.- Configuracion de Repositorio GIT

Vamos a configurar un reporsitorio llamado «prueba1»

  • Crear llave

# ssh-keygen
# cat ~/.ssh/id_rsa.pub

  • Creo un reporsitorio «prueba1»
    prueba1 / como privado.

 

  • Descargar un proyecto de prueba, vamos a elegir DVWA

# git clone https://github.com/digininja/DVWA.git

 

  • Ahora configurar finalmente el repositorio local con el repositorio remoto en GITBUB

git init
git add .
git config –global user.email «tuemail@gmail.com»
git config –global user.name «tuuser»
git commit -m «first commit»
git branch -M master
git remote add origin git@github.com:jrolivaeh/prueba1.git
git push -u origin master

Hasta aqui tenemos nuestro repositorio local enlazado con nuestro repositorio remoto en GIT.

2.- Instalación de Talisman en Centos 7

# yum install perl-Digest-SHA git
# curl https://raw.githubusercontent.com/thoughtworks/talisman/master/global_install_scripts/install.bash > ~/install-talisman.sh
# chmod +x ~/install-talisman.sh
# ~/install-talisman.sh

Definir donde se configuraran las variables de entorno , la definimos en el ~/.bashrc

Definimos el modo interactivo haciendo uso del archivo .talismanrc para manejo de excepciones.

Finalmente se define la ubicacion de los repositorios, en este caso de «demo» estamos trabajando en /root/DVWA/ de la VM

3.- Probando Talisman dentro del CI.

Ahora agregamos unos «secretos» que no deberian subirse el repositorio.

# vim secretos

aws_access_key_id = 2367921901012
aws_secret_access_key = vKbptOYlkDFMI/L9NEIMP/bIsEkoQWEJEMKEY
aws_session_token = BWlEJEMPLOK9fgGH0pMPAPuRqw5MoERRpQWE98YUfg5PasR+FvwqnKwRcOIfrRh3c

Finalmente agregaremos el archivo a la rama y finalmente haremos un commit

# git add secretos
# git commit -m «Agregando secretos»

Como vemos Talisman detecto los «secretos» y nos manda una advertencia y alertas.

4.- Agregando excepciones en Talisman.

Si necesitamos crear una excepción por ejemplo de lo que se ha detectado, tenemos que agregar un archivo .talismanrc en el directorio root del proyecto como se muestra a continuación.

cd /root/DVWA
vim .talismanrc

fileignoreconfig:

  • filename: secretos
    checksum: 2502eb040033bd44080fb385ae8b794b808f25542e1e9075d5ed65d4a976c014

Ahora nuevamente mandamos el «comit» y veremos que Talisman aceptara la escepcion.

Espero les sirva, esperemos seguir escribiendo sobre #DevSecOps
Este post va para todos mis amigos que me brindaron apoyo incondicional en superar el virus, Muchas gracias!!

Saludos
@Juan Oliva

Instalación de Cluster de Kubernetes con Vagrant

marzo 4, 2020 1 comentario

Como parte de las labores de despliegue de software, la automatizar los procesos de infraestructura como código, es vital, para las actividades de Pentesting / Ethical Hacking tener construir tus entornos y escenarios locales de prueba sirve infinitamente para poder realizar tus P.O.C.

Es así que aquí va el procedimiento para automatizar la instalacion de un Cluster de Kubernetes usando Vagrant en Centos 7, este es el Escenario.

Ubuntu 16.04.6 LTS
Vagrant 2.2.3

Este es Vagantfile

###########################################

# -*- mode: ruby -*-
# vi: set ft=ruby :

VAGRANTFILE_API_VERSION = «2»
##Variables de configuracion ###
INTERFASE_BRIDGE = «wlps01»
DIRECCION_IP_BRIDGE = «192.168.1.151»
MASCARA_RED = «255.255.255.0»
PUERTA_ENLACE = «192.168.1.1»
##Configuracion de la VM master
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = «centos/7»
config.disksize.size = ’50GB’
config.vm.network «public_network», bridge: INTERFASE_BRIDGE, ip: DIRECCION_IP_BRIDGE, netmask: MASCARA_RED, gateway: PUERTA_ENLACE
config.vm.hostname = «k8s-master»
config.vm.provider «virtualbox» do |v|
v.name = «k8s-master»
v.memory = 2048
v.cpus = 2
end
##Insertar llave SSH
config.ssh.insert_key = false
config.ssh.private_key_path = [‘~/.vagrant.d/insecure_private_key’, ‘~/.ssh/id_rsa’]
config.vm.provision «file», source: «~/.ssh/id_rsa.pub», destination: «~/.ssh/authorized_keys»
##Configuracion de SSH, SELINUX, IPTABLES, SWAP, FIREWALLD
config.vm.provision «shell», inline: <<-EOC
sudo sed -i -e «\\#PasswordAuthentication yes# s#PasswordAuthentication yes#PasswordAuthentication no#g» /etc/ssh/sshd_config
sudo sed -i -e «\\#PermitRootLogin prohibit-password# s#PermitRootLogin prohibit-password#PermitRootLogin yes#g» /etc/ssh/sshd_config
sudo sed -i -e «\\#SELINUX=enforcing# s#SELINUX=enforcing#SELINUX=disabled#g» /etc/selinux/config
sudo systemctl restart sshd.service
sudo setenforce 0
sudo modprobe br_netfilter
sudo echo ‘1’ > /proc/sys/net/bridge/bridge-nf-call-iptables
sudo sed -i ‘/swap/d’ /etc/fstab
sudo swapoff -a
sudo systemctl stop firewalld
sudo systemctl mask firewalld
echo «Instalacion de Docker»
sudo yum -y install vim yum-utils net-tools
sudo yum -y install epel-release
sudo yum install -y yum-utils device-mapper-persistent-data lvm2
sudo yum-config-manager –add-repo=https://download.docker.com/linux/centos/docker-ce.repo
sudo yum install -y docker-ce
echo «Instalacion de Kubernetes»
sudo yum-config-manager –add-repo=http://www.silcom.com.pe/soft/kubernetes.repo
sudo yum-config-manager –enable Kubernetes
sudo yum install -y kubelet kubeadm kubectl
echo «Fin de Instalacion»
EOC
##Reinicio de la VM
config.vm.provision :reload
##Configuracion e inicio de servicio docker y kunernestes
config.vm.provision «shell», env: {«VARIP» => «192.168.1.151»}, inline: <<-EOC
sudo sed -i ‘1i $VARIP k8s-master k8s-master’ /etc/hosts
sudo systemctl start docker && systemctl enable docker
sudo systemctl start kubelet && systemctl enable kubelet
sudo sed -i ‘s/cgroup-driver=systemd/cgroup-driver=cgroupfs/g’ /usr/lib/systemd/system/kubelet.service.d/10-kubeadm.conf
sudo systemctl daemon-reload
sudo systemctl restart kubelet
echo «Inicializacion de Cluster»
sudo kubeadm init –apiserver-advertise-address=$VARIP –pod-network-cidr=10.244.0.0/16
sudo mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
echo «Fin de Inicializacion de Cluster»
echo «Desplegar el pod network»
sudo kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
echo «Pod network creado»
echo «FIN»
EOC
#Fin SSH
end

##############################################################3

Finalmente este es el video donde se muestra el despliegue :

Espero les sirva.
Saludos
@jroliva

 

Asegurando Issabel PBX – «La receta»

junio 26, 2017 12 comentarios

Existen ciertas cosas en la vida que valoro mucho y es el esfuerzo y la capacidad para poder trabajar en Equipo, ya que es muy difícil de conseguir, puesto que nuestra naturaleza humana nos lleva siempre a defender nuestros intereses personales, que muchas veces no son del bien común del equipo o en este caso de la comunidad que persigue un objetivo.

En eso puedo resumir de lo que pude apreciar luego de asistir al #BeFree17 en la ciudad de México, un equipo de diferentes países y continentes inclusive, trabajando como una comunidad para un objetivo común, difundiendo conocimiento y tratando de sacar adelante un proyecto.

Por otro lado también considero que el conocimiento debe ser libre, como parte de la constante creación de nuevas cosas e ideas, con todas estas cosas rondando en mi cabeza, es me puse a trabajar en este paper cuya base fue la presentación que realice el miércoles pasado.

Lo titulé : Asegurando Issabel PBX – «La Receta»  El objetivo del documento es guiar de una manera muy sencilla, con una serie de ingredientes bastante prácticos, en la mejora de algunos aspectos relacionados con la seguridad de la plataforma de comunicaciones Issabel PBX, tanto para servidores implementados en la nube, así como en instalaciones locales.

Como saben Issabel es una plataforma de comunicaciones Software Libre y código abierto basada en Asterisk (Digium the Asterisk Company) integra funcionalidades de PBX, correo electrónico, tareas de colaboración, así como vídeo llamadas.

Todas las instrucciones del presente material fueron realizadas con la versión que
corresponde al archivo ISO issabel4-USB-DVD-x86_64-20170621.iso.

El documento lo pueden descargar desde aquí :

Paper_Asegurando_Issabel_PBX-La_Receta

Espero les sirva

Juan Oliva

Instalación de Kamailio en Centos 7

junio 16, 2016 Deja un comentario

kamailioEs indudable que Kamailio es uno de los software mas potentes en el mundo de la VoIP , por los diferentes escenarios que puedes construir relativos a seguridad, escalabilidad, redundancia y todo lo que termina en «dad»

Sin embargo mucha gente que comienza a aprender su funcionamiento se choca con la curva de aprendizaje, que es necesario tener para entender este programa, como lo dije en un tweet «si no te gusta la consola, kamailio no es lo tuyo» sin embargo nada es imposible de aprender por su puesto.

kamailioAntes de comenzar definamos rápidamente un par de cosas, Kamailio no es igual ni parecido a Asterisk, formalmente Asterisk es lo que se llamaría un «back to back user agent» o «B2UA» el cual es utilizado tradicionalmente para ser una PBX IP ya que cuenta con un sin numero de aplicaciones para un PLANTA IP como voicemail, IVR, Colas,etc,etc.

kamailio

En cambio Kamailio es un SIP PROXY en todos los sentidos, como su nombre lo dice, este tipo de software solo conversa SIP y nada mas, el cual puede trabajar como proxy proiamente, location server, registrar server, servidor de presencia, call routing (LCR) los cuales son algunos de los roles en los que puede trabajar.

kamailioAhora la pregunta sería, para los nativos Asterisk, puedo usar Kamailio como lo uso con Asterisk ?
Pues la respuesta sería que no, ya que si bien es cierto ambos trabajar para brindar servicios de SIP VoIP tienen diferentes usos.

Entonces para que uso Kamailio?
Se puede usar para extender funcionalidades que de pronto Asterisk queda limitado, como por ejemplo, escalar usuarios, ya que Kamailio solo trabaja con SIP su consumo de procesamiento es mucho menor al de Asterisk y puede trabajar como servidor de registro, tambien puedo usarlo para balancear carga hacia un conjunto de servidores Asterisk, o para que sea mi servidor de proteccion hacia internet, solo por citar algunos ejemplos.

kamailioEntonces puedo integrar Asterisk con Kamailio ?
Si, puedo integrarlo de muchas maneras en realidad, algunas muy sencillas otras mas complicadas pero si se puede, de hecho hay varios proyectos y/o productos que han integrado con gran exito Kamalio-Asterisk como Elastix MT SIP WISE

Una vez que hemos revisado un poco para que podemos usar Kamailio, vamos a comenzar con este primer post sobre como instalar Kamailio sobre Centos 7 en una instalación mínima.

1.- Configurar el sistema base
Luego de instalar Centos 7 al mínimo es necesario «arreglar» un par de cosas

Instalar editor, ifconfig , EPEL
yum install net-tools vim
yum -y install epel-release

Desactivar SELINUX
vi /etc/selinux/config
SELINUX=disabled

Desactivar Firewall
systemctl disable firewalld
systemctl status firewalld

2.- Instalar Kamailio
Ahora vamos a instalar desde los repositorios.

Agregar un repositorio
vi /etc/yum.repos.d/kamailio.repo

[kamailio]
name=RPMs for Kamailio on CentOS 7
type=rpm-md
baseurl=http://rpm.kamailio.org/stable/CentOS_7/
gpgcheck=1
gpgkey=http://rpm.kamailio.org/stable/CentOS_7/repodata/repomd.xml.key
enabled=1

Instalar Kamailio básico
yum install kamailio kamailio-utils kamailio-debuginfo

3.- Crear un archivo de configuración básico

vim /etc/kamailio/kamailio.cfg

##### Inicio
debug=2
log_stderror=yes
fork=yes
mpath=»/usr/lib64/kamailio/modules»
loadmodule «pv.so»
loadmodule «xlog.so»

route {
xlog(«L_INFO»,»Requerimiento entrante: $rm de $si a $ru \n»);
forward();
}

onreply_route {
xlog(«L_INFO»,»Respuesta entrante: $rm $rr – de $si a $ru \n»);
}
##### Fin

4.- Levantar el servicio y revisar LOG

Levantamos el servicio y si todo está bien veremos esto
kamailio
También es necesario, sobre todo si salen errores verificar los logs

tail -f /var/log/messages
kamailio

Algunos Links que deberías ver si te interesa saber un poco mas de Kamailio :

Kamailio :: A Quick Introduction
http://es.slideshare.net/oej/kamailio-a-quick-introduction

Kamailio – The Story for Asterisk
http://es.slideshare.net/miconda/kamailiothestory

Usando el módulo PIKE en Elastix MT
http://es.slideshare.net/elastixorg/usando-el-mdulo-pike-en-elastix-mt?qid=db7c2bb7-5d61-4190-a76d-89dd0f97565a&v=&b=&from_search=24

 

En otros post veremos un poco mas kamailio y algunas aplicaciones practicas.

 

Espero les sirva.
Saludos
Juan Oliva

 

 

 

 

Configurando seguridad en Elastix MT

octubre 7, 2015 2 comentarios

ElastixMT

Configuración y dinámica de mi charla realizada en el ElastixWorld de Colombia para lograr configurar el módulo PIKE en Elastix MT

1.- Activar la variable en las definiciones globales
ElastixMT
2.- Verificar la carga del módulo

ElastixMT
3.- Configurar el módulo PIKE a gusto 😀

ElastixMT
4.- Evaluar en la lógica de enrutamiento

ElastixMT

Descargar archivo de configuración
http://www.silcom.com.co/configuration/kamailio.cfg

Vídeo de demostración

Espero les sirva
Saludos
@jroliva

ElastixWorld 2015 – Nos vemos en Colombia!!

septiembre 21, 2015 1 comentario

elastixComo todos los años este 7 de octubre se realizará uno de los eventos más importantes relacionados con el mundo de la VoIP y comunicaciones basadas en software libre.

ElastixWorld , no solo reunirá durante 2 días a las mejores marcas del mercado de telefonía IP como Openvox, Sangoma, Xmartek , Dinstar, Grandstream, Yealink, entre otras, las cuales mostrarán hardware y harán demos en vivo en los stands, si no también juntará a un conjunto de expositores de nivel mundial, que presentarán charlas sobre estudios, casos de éxito en VoIP relacionado con software Libre, presentando temas como balanceo , escalabilidad, programación con  REST , desarrollo con WebRTC , seguridad, etc.

Pueden ver el detalle de las charlas aquí : http://www.elastixworld.com/2015/conferencistas/

En mi caso, este año, tendré el gusto de participar con la charla «Usando el módulo PIKE en Elastix MT»

elastix
En donde haremos textualmente un «hacking» a Elastix MT, pero está vez no será para buscar vulnerabilidades,  si no «hacking» para entender como funciona por dentro, esta relación asombrosa que han conseguido entre kamailio y Asterisk  para luego ingresar al área de la seguridad y ataques, en donde mostraré la configuración y  funcionamiento en vivo del modulo PIKE en está plataforma la cual  es muy interesante, sobre todo para operadores de telefonía o empresas que desean hacer virtual PBX entre otras cosas.

Este año como novedad existirá un stand donde estarán todos los instructores oficiales de Elastix denominado «Elastix Guru» para los asistentes que deseen hacer consultas o dudas de este campo, espero tener el gusto de conocer en ese espacio, a mas de uno que visita este blog.

elastix
Otra actividad que tiene mucha expectativa es el lanzamiento oficial de Elastix 4 a cargo del su creado Edgar Landivar, en donde la mayor feature es que estará basada en Centos 7 lo cual representa una salto muy importante en está rama de la distribución.

elastix

Es así que si estas en Colombia, es un evento al cual no puedes dejar de asistir y si no lo estás,  aún tienes tiempo para comprar tu pasaje y estar presente, realmente lo recomiendo ya que se nutrirán de mucho conocimiento, no solo de VoIP , si no también de soluciones basadas en software libre enfocadas a las comunicaciones IP.

Entonces … nos vemos en Colombia!!

Saludos
Juan Oliva
@jroliva

 

 

 

 

Hacking Fortinet – WAF TEST

agosto 31, 2015 3 comentarios

wafDentro de la amplia gama de soluciones de protección de seguridad informática, existen equipos muy especializados de acuerdo al propósito; Uno de ellos esos equipos es el denominado Web Application Firewall

Según OWASP es un firewall de aplicaciones Web  o «WAF» el cual es es un aparato, plugin de servidor, o el filtro que se aplica un conjunto de reglas a una conversación HTTP. En general, estas reglas cubren ataques comunes tales como cross-site scripting (XSS) y SQL injection. Mediante la personalización de las reglas para su aplicación, muchos ataques pueden ser identificados y bloqueados.

waf

Evidentemente un WAF no es un UTM , ya que el WAF como se cita en el párrafo anterior, es un equipo que se enfoque específicamente en la protección de aplicaciones o sistemas Web,  es necesario precisar ello por que en el articulo anterior donde realizarnos pruebas contra un UTM la mayoría de los ataques hacia aplicaciones web, no fueron bloqueados por el equipo.

fortiweb

Es así , que gracias a Yishay Perry  ( www.fil.org.il ) que es especialista en soluciones Fortinet y un colega en el área de seguridad perimetral, me dio la posibilidad de poder tener acceso al WAF de Fortinet denominado FORTIWEB,  en donde implementamos un escenario de adecuado para realizar algunas pruebas de seguridad ofensiva y validar si el equipo podía bloquear algunos de los ataques hacia aplicaciones web mas representativos.

fortiweb

Escenario

escenario-waf

fortiweb

Test 1 – Cross-site scripting  XSS

La detección de ataques de XSS son bastante complicados de ser detectados por los UTM tradicionales en este caso vamos a ver como reacciona el WAF ante esta vulnerabilidad.

A.- Sin el WAF protegiendo la aplicación web
Probamos la siguiente cadena xss :
alert(document.cookie)

fortiwebVemos que el xss reflejado se completo

B.- Con el WAF protegiendo la aplicación web
Volvemos a probar la misma cadena pero ahora con el WAF protegiendo la aplicación web

fortiwebVemos que el WAF reacciona y bloquea la ejecución del XSS reflejado

fortiweb

Así mismo el WAF genera el registro del evento.

Test 2 – File Inclusion

Esta es otra vulnerabilidad bastante complicada de detectar, vamos a ver como reacciona.

A.- Sin el WAF protegiendo la aplicación web
Probamos la siguiente inclusion : /etc/passwd
fortiwebVemos que se completa el comando y devuelve el contenido del archivo /etc/passwd en la aplicación web

B.- Con el WAF protegiendo la aplicación web
Volvemos a probar la misma cadena pero ahora con el WAF protegiendo.

fortiwebTambién vemos que el WAF reacciona y bloquea la ejecución del XSS

fortiweb

De la misma forma vemos que el WAF genera el registro del evento.

Test 3 – Website Defacement

El defacement o defaseo de paginas es un ataque bastante comun en estos tiempos, veamos como el WAF reacciona.

Escenario: En este caso hemos conseguido subir un webshell, mediante un formulario de upload, luego se ha detectado el archivo index.php que es la pagina principal del sitio web y estamos en el proceso de grabar nuestro defacement , como se muestra a continuación : Selection_222

A.- Sin el WAF protegiendo la aplicación web
Sin el WAF protegiendo es posible grabar el archivo y completar el defacement  de la siguiente forma :

fortiweb
B.- Con el WAF protegiendo la aplicación web

Volvemos a probar tratando de grabar el archivo index.php con el WAF protegiendo y este reacciona de esta forma :

fortiwebAsí mismo el evento queda registrado como se muestra a continuación:

fortiwebEs decir el WAF evita el defacement.

Conclusiones

  • Contar con un equipo mucho mas especializado en ataques web permite reducir mucho las probabilidades de que se puedan explotar vulnerabilidades en las aplicaciones, como el caso de el FortiWEB
  • Si bien es cierto todas las pruebas realizadas fueron positivas con respecto al WAF , ello es porque, se ha realizado configuración especifica de protección para la aplicación que se está defendiendo, es decir cualquiera que sea la solución WAF que se usen, es necesario realizar configuración personalizada en el equipo.
  • Esta guía intenta mostrar, que para cualquier equipo o solución que proteja la seguridad,  es altamente recomendable que se realicen pruebas de seguridad ofensiva para validar cada una de las reglas de protección que el equipo brinda.
  • En el caso del FortiWeb puedo manifestar que es un equipo que protege bastante bien las vulnerabilidades evaluadas.

En otro articulo veremos como implementar un WAF basado en algunas soluciones de software libre existentes.

Espero les sirva.
Saludos
Juan Oliva
@jroliva

 

Categorías: Hacking, Linux Etiquetas: , , , ,

Hacking Fortinet – WAF TEST (English version)

agosto 31, 2015 4 comentarios

wafAmong the wide range of solutions to protect security, there are very specialized equipment according to purpose; One such equipment is called Web Application Firewall

According to OWASP is a Web application firewall or «WAF« which is a device, server plugin, or filter a set of rules that applies to an HTTP conversation. In general, these rules cover common attacks such as cross-site scripting (XSS) and SQL injection. By customizing the rules for its implementation, many attacks can be identified and blocked.

wafEvidently a WAF is not a UTM , the WAF it is a device or software that specifically focus on protecting applications or Web systems, it is necessary therefore that in the previous article where through testing against UTM most attacks on web applications, were not blocked by the team.

fortiwebThanks to Yishay Perry (www.fil.org.il) who specializes in Fortinet solutions and a colleague in the area of perimeter security, gave me the possibility to access the Fortinet WAF called  FortiWeb, where we implemented a scenario suitable to perform some tests of the security offensive and validate  if the team could block some of the attacks more representative on web applications.

fortiweb

Scenario:

 

escenario-waffortiweb

Test 1 – Cross-site scripting  XSS

The detection of XSS attacks are most complicated to be detected by traditional UTM in this case we see how the WAF reacts to this vulnerability.

A. Without the WAF protects web application
Xss tested the following string: alert (document.cookie)
fortiwebsee that reflected XSS is complete
B. With the WAF protects web application
Retest the same test but now with the WAF protects web application
fortiwebsee that the WAF reacts and blocks the execution of reflected XSS
fortiwebAlso the WAF generates the event log.

Test 2 – File Inclusion

This is another vulnerability difficult to detect , let’s see how he reacts.

A. Without the WAF protects web application
We tested the following  path inclusion: /etc/passwd

fortiwebsee that the command completes and returns the contents of /etc/ passwd file in the web application

B. With the WAF protects web application
Retest the same test but now with the WAF protecting.

fortiwebWe also see that the WAF reacts and blocks the execution of XSS

fortiwebas in the previous test we see that the WAF generates the event log.

Test 3 – Website Defacement

The defacement or defaseo of pages is an attack fairly common these days, let’s see how the WAF reacts.

Scenario: In this case we managed to climb a webshell, upload through a form, then detected the file index.php is the main page of the website and are in the process of save our defacement in the file, as shown below:

Selection_222

A. Without the WAF protects web application
Without the WAF protecting , may save the file and complete the defacement as follows:

fortiweb

B. With the WAF protects web application
Retest trying to save the index.php file with the WAF protecting and it reacts like this:

fortiwebLikewise, the event is recorded as shown below:

fortiwebWAF prevents defacement.

Conclusions

  • Have a much more specialized equipment allows web attacks greatly reduce the chances that can exploit vulnerabilities in applications, such as the case of the FortiWeb
  • All tests were positive about the WAF, it is because, there has been specific configuration to protection for the application that is being defended, ie whatever the WAF solution is used, it is necessary to make custom settings on device . 
  • This guide is intended to show that for any equipment or solution to protect the security, it is highly recommended that offensive security testing to validate each of the security rules that the device offers are made. 
  • I can say that FortiWeb is a pretty good device that protects the assessed vulnerabilities.

In another article we will see how to implement a WAF some solutions based on existing free software.

Regards
Juan Oliva
@jroliva

 

Hacking fortinet – bypassing UTM (English version)

julio 31, 2015 4 comentarios

Spanish version :https://jroliva.wordpress.com/2015/07/31/hacking-fortinet-bypassing-utm/

Hello, in the previous post «Hacking FoAceptarrtinet – SQLI test» I made clear my position that I was unhappy with the results obtained. And do not misunderstand, beyond that we received very good feedback from the Fortinet brand which is important to us.

by showing a very good position and receptive to this type of study, however we needed perform another tests the offensive security because SQLI is not everything, Now the current attacks go far beyond, including combined attacks and techniques.

It is so a few days ago, again with my good friend Alexis Torres, developed the following test, detailed below:

Scenario:

fortinet-esenario

The scenario is implemented as follows:

192.168.100.100 — IP WEB SERVER on LAN
192.168.100.120 — IP MS WINDOWS 7 on LAN
192.168.100.1   — IP UTM on LAN

192.168.13.100 — IP SERVIDOR WEB en WAN
192.168.13.200 — IP UTM en LAN

192.168.13.202-203 — ATTACKER 1 (KALI LINUX)
192.80.190.11X — ATTACKER 2 (VPS CENTOS 6.X)

Setup UTM

hackingfortinet

A Appliance Fortinet D60 with licenses of the IPS and Antivirus activated as you can see below:

fortinet

Also, during the tests detailed below, several configuration profiles were tested as follows:

Profile «Default» activated in the IPS

hacking-fortinet

Profile «High Security» activated in the IPS

hacking fortinet

Profile «protect_http_server» activated in the IPS

hacking fortinet
Profile «default» activated in the AV

hackingfortinet

Also set within this profile (AV), the proxy mode, which allows you to capture traffic on a cache, examine it and then send it to the client.

Then to validate that the IPS is configured correctly,  we perform a basic test of SQLI to verify that blocks correctly.

hackingfortinettrying to introduce a SQLI in the web application, we see that the IPS blocks attack:

hackingfortinetAll validated, we start with the tests.

Test 1 – Session Hijacking using XSS

The first attack we tested is the «session hijacking» using stored XSS,  previously we  had proven that XSS reflected were not detected by the IPS, so that when combined with other attack, the IPS had even less likely to be detected , as it’s shown in the following:XSS

As shown, the XSS attack sent via the «document.cookie» object ,  current session to an external URL http: //192.80.190.1XX/b.php

XSSThen the attacker 2 receives the string sent by the XSS stored in the web application, as follows:

hijackingAs shown, the attack result is received in the VPS Linux (attacker 2) only opening a socket connection using netcat to port 80 and the session cookie is received.

After completing the attack, let the UTM web interfase and we do not have the «Security Log / Intrusion Protection» section, that is not registered and does not block it.

fortinet

these attacks are maded in this scenario:

The attacker enters to intranet, who has an invited profile , he identifies that web application has XSS vulnerability and it stores on a common place in the web application then he deploys the malicious URL. The victim enters to intranet like whatever job day, he can review the balance of the day or some import information or maybe he could get an administrator profile.

When the victim gets to click to malicious url, the cookies are sent to attacker’s console.

the attacker can use that cookie in order to access to web application with the same victim’s profile and access all the information.

Test 2 – LFI

Including local files, allows viewing files that are not in the directory of your Web server publishing, as the following example:

fortinetIn that case we are viewing the «passwd» file in the «etc» directory of the operating system.

The attack is complete and is never detected by the IPS.

Test 3 – Reverse Shell using File Upload

It is common in Web applications has forms to upload files, whether images, documents docx, xlsx or pdfs inclusive.

However, this represents a major vector for an attacker because it allows the physical write to the server, which is a very tempting opportunity.

We will not explain  the many techniques to evade filters must have an upload form, however we will use a basic, is rename the extension to the flight, to upload your file, this file generates the reverse shell  through the web application.

Start the the process of the attack

A. Download and set up reverse shell file.
Download PHP reverse shell file and configured as follows:

fortinetAs we can see, in the variable $IP we are declaring the Linux VPS IP to which the shell is sent through the output port 1234, declared the variable $port

B. Rename to confuse evade the upload filter.
Then change the file extension to jpeg as shown below:

fortinet
C. Upload and execute file
With our shell covered in a jpeg file, we will upload
fortinetThen using a proxy as «burp suite» we will rename the file extension on flight.
fortinetSee a little more detail the change
fortinetThen, the file is uploaded, and execute in the URL where it is housed in the web server.
fortinetLater, the attack is complete, without being blocked by the UTM and the reverse shell is obtained, in the listening port 1234 of the VPS  as shown below:

fortinetfortinet

Test 4 Avoiding the perimeter Antivirus and winning remote shell in Windows 7

Context: Some of the features of all UTM is to have an antivirus perimeter, your objetive to be the first defense against the entry of infected files,  before they reach workstations of users, these attacks are best called «client side attacks».

The attack: In post past «Evading Antivirus with Shellter and Metasploit» showed how they could evade the local antivirus,

– Creating the infected file
Let’s create a Shellter infected file as follows:

hackingfortinetAs seen in the capture, it configures the IP 192.179.13.203 , will be receiving the reverse shell on port 5555, in the case that the infected file is execute in the victim.

Execute the handler in Mestasploit
Now
got one handler listening for the reverse shell
hackingfortinetAs shown, it is waiting for the reverse shell on port 5555

– Downloading the infected file on the client.
Now from the Windows, we will download the infected file, where the perimeter antivirus should react and do not allow downloading.
hackingfortinethackingfortinet11830837_10153137243563160_817221665_n
As you can see, it is possible to completely download the infected file.

Gaining remote shell
Now what follows is run the file, and get the reverse shell.

I pause to explain the following.

Peculiar behavior
When executed the first time the infected file, the reverse shell was obtained, but after repeating the process several times, it was no longer possible, the UTM detect and block the reverse shell,but again, but I repeat, then gained 2 or 3 times the previously reverse shell.

Negative behavior Obtain the shell
hackingfortinethackingfortinethackingfortinethackingfortinet
Positive behavior block shell
As shown in previous screenshots, twice the attack could be completed (the shell was obtained) but then this was no longer possible.

hackingfortinetAs you can see, the handler can not get to complete the process of obtaining meterpreter session.

And obviously the reason was because the IPS detected the attack.

hackingfortinet

Abnormal behavior Obtein the shell
We made the analysis of the packages, we could see that the shell was blocked, not at the time when Windows send the package handler, if not when, returned back to Windows (incoming packet) and at that moment, it was detected by IPS.

Because of this, we changed our configuration in file infected to send the shell to VPS Linux and this was the result :

hackingfortinetAs you can see after running the file, you may receive the connection in the VPS.

Conclusions

Juan Oliva

  • The Tests in the side of pentester were of such Gray box, not known the type of configuration in the UTM but but yes , the IP address of targets.
  • The tests are very used by computer criminals, especially when performing combinations of techniques may be more likely to succeed.
  • My opinion It’s necessary implement additional systems to monitor attacks.
  • Must be generated in the UTM custom rules for each type of situation, in the case of fortinet, this link is important.

Alexis Torres

  • In the proof of AV engine in client side, only it was made with a type of payload, «meterpreter» that is denominated in the IPS signatures as «Shell reversing» , there isn’t unique payload kind, and the target in Windows(known signature).
  • We don’t use any kind of sophisticated technique as crypter, encoder, reassemble however we use a dynamic code injector to PE, to create a malicious executable, after that in the pictures, we can see that originate a communicate channel between evilServer and the target.
  • With my experience in security projects deployments for enterprises, there is a great dependability in UTMs about their security information because they can find “all defense in one” when the reality is the first line defense perimeter in some company.
  • In addition, there aren’t enough to have firmware updated and licenses paid, in first point,  we should assure that the configuration has a good practice because it can get a great impact without much effort to attacker 😀

Finally, tests have no intention to somehow discredit a particular brand, all the opposite, have the spirit carried out with other security appliance and other brands, and improve the security of bussines applications.

For example, personally pending testing by a product of the same brand, called FortiWeb, which is a much more specialized in web attacks protection.

Waiting the new tests !!

Saludos
Juan Oliva
@jroliva