Atacando servicios web

50

description

Los servicios web están comenzando a tener gran acogida como parte de implementaciones tipo BPM, aunque aún no se entienden del todo ya que no son tan "visibles" como las aplicaciones web tradicionales. Aprovechemos eso para atacarlo!

Transcript of Atacando servicios web

Page 1: Atacando servicios web
Page 2: Atacando servicios web

ATACANDO SERVICIOS WEB

ATACANDO SERVICIOS WEB

Page 3: Atacando servicios web

ATACANDO SERVICIOS WEBWHOAMI?

• Oscar Martínez Ruiz de Castilla• Trabajo en Seguridad Informática• Con más de 9 años de experiencia en el campo de

Tecnologías de la Información

• Ingeniero en la especialidad de Ingeniería Electrónica - PUCP• Magister en Ciencias de la Computación – PUCP• Hobbies: Aparte de hacking, XBOX! (PES 2013, Darksiders II)

Que hago?• Muchos años defendiendo• Últimamente atacando (network / web apliccation

penetration tester)

“Los sistemas de seguridad tienen que ganar siempre, al atacante le basta con ganar sólo una vez”.

Page 4: Atacando servicios web

ATACANDO SERVICIOS WEBWHOAMI?

Contactos (corregir, aportar, etc)• [email protected]• fiery-owl.blogspot.com• @oscar_mrdc

Certificaciones• EC Council Certified Ethical Hacker v7 (C|EH)• Mile2 Secure Web Application Engineer (C)SWAE)• Mile 2 Digital Forensics Examiner (C)DFE)• Microsoft Certified Systems Administrator (MCSA)

Page 5: Atacando servicios web

ATACANDO SERVICIOS WEB

Page 6: Atacando servicios web

•DISCLAIMER

• Todo el contenido de esta charla es resultado de investigación con fines didácticos y educativos. El autor no se hace responsable por el uso del conocimiento contenido en la siguiente presentación. La información contenida debe ser utilizada únicamente para fines éticos y con la debida autorización.

• Todo descubrimiento realizado, ha sido y será usado de forma legal. La audiencia debe asumir todo lo que se exponga hoy, como “falso” y “sin fundamento” hasta que lo compruebe personalmente. Limahack no es el autor directo de ninguno de los descubrimientos expuestos, ni de las herramientas demostradas, ni los conoce.

• Todas las opiniones vertidas durante esta presentación son exclusivas del expositor, Limahack no es responsable de ninguna de las opiniones vertidas.

Page 7: Atacando servicios web

ATACANDO SERVICIOS WEBDISCLAIMER!

Buena intención? Curiosidad? DELITO?LEY QUE INCORPORA LOS DELITOS INFORMÁTICOS AL CÓDIGO PENALhttp://www.ongei.gob.pe/normas/1887/NORMA_1887_Ley%2027309.pdf

Page 8: Atacando servicios web

ATACANDO SERVICIOS WEBDISCLAIMER!

AUTORIZADO POR ESCRITOSABER USAR LAS HERRAMIENTAS

Ambientes de prueba:• DVWA http://www.dvwa.co.uk/• Gruyere http://google-gruyere.appspot.com/• Webgoat https://www.owasp.org/index.php/Proyecto_WebGoat_OWASP

Page 9: Atacando servicios web

ATACANDO SERVICIOS WEBMOTIVACIÓN

BPM + SOA Wikipedia:SOALa arquitectura orientada a servicios de cliente (en inglés Service Oriented Architecture), es un concepto de arquitectura de software que define la utilización de servicios para dar soporte a los requisitos del negocio.Permite la creación de sistemas de información altamente escalables que reflejan el negocio de la organización, a su vez brinda una forma bien definida de exposición e invocación de servicios (comúnmente pero no exclusivamente servicios web), lo cual facilita la interacción entre diferentes sistemas propios o de terceros. Mobile applications?

Page 10: Atacando servicios web

ATACANDO SERVICIOS WEBREFERENCIAS

OWASP Testing Guide v3https://www.owasp.org/index.php/Testing_for_Web_Services A Web Services Security Testing FrameworkColin Wong / Daniel Grzelak

WS-Attacks.org projecthttp://clawslab.nds.rub.de/projects_WS-Attacks.html Don’t Drop the SOAP: Real World Web Service Testing for Web HackersTom Eston / Joshua Abraham / Kevin Johnson Cracking the Foundation: Attacking WCF Web ServicesBrian Holyfield Security for Web Services and Services-Oriented ArchitecturesElisa Bertino / Lorenzo Martino / Federica Pazi / Anna Squicciarini

Improving Web Services SecurityMicrosoft

Page 11: Atacando servicios web

ATACANDO SERVICIOS WEBQUE ES UN SERVICIO WEB?

Wikipedia:Un servicio web (en inglés, Web service) es una Tecnologia que utiliza un conjunto de protocolos y estándares que sirven para intercambiar datos entre aplicaciones. Distintas aplicaciones de software desarrolladas en lenguajes de programación diferentes, y ejecutadas sobre cualquier plataforma, pueden utilizar los servicios web para intercambiar datos en redes de ordenadores como Internet.

Web Service

Web Service

InteroperabilidadCualquier lenguaje

Cualquier plataforma

JavaJBoss

.NETIIS

Page 12: Atacando servicios web

ATACANDO SERVICIOS WEB

Page 13: Atacando servicios web

ATACANDO SERVICIOS WEB

Page 14: Atacando servicios web

ATACANDO SERVICIOS WEBQUE ES UN SERVICIO WEB?

Aplicación web (la consume directamente una persona) - HTTP

Base de Datos

Web Application

Usuarios

File Server

LDAP

SMTP

Page 15: Atacando servicios web

ATACANDO SERVICIOS WEBQUE ES UN SERVICIO WEB?

Web Services (la consume otra aplicación)

Los “clientes” de un servicio web son otras aplicaciones.

Base de Datos

Web Application

Usuarios

File Server

LDAP

SMTP

Web Services

Web Application

Page 16: Atacando servicios web

ATACANDO SERVICIOS WEBQUE ES UN SERVICIO WEB?

Web Services (la consume otra aplicación)

Expuestos erróneamente, se “asume” que sólo son consumidos por otra aplicación)

Sólo se implementan controles en la aplicación web, NO! En el web service)

Creadas para exponer aplicaciones antiguas que son fácilmente vulneradas, una vez están fuera de nuestro segmento de red privado.

Base de Datos

Web Application

Usuarios

File Server

LDAP

SMTP

Web Services

Web Application

Page 17: Atacando servicios web

ATACANDO SERVICIOS WEB

HACKING WEB SERVICES

Page 18: Atacando servicios web

ATACANDO SERVICIOS WEB

1. Atacar la infraestructura (Administración)

No lo veremos aquí (Nosotros atacaremos directamente el Servicio Web).Atacar directamente el servidor.Atacar JBoss, Glassfish, IIS, Axis, etc. http://alguienenlafisi.blogspot.com/2011/12/hacking-web-services-parte-iii_27.html

Nota: Si controlo el servidor? gameover! Para que preocuparse con los web services!

Page 19: Atacando servicios web

ATACANDO SERVICIOS WEBFIREWALL Y APLICACIONES/SERVICIOS WEB

Page 20: Atacando servicios web

ATACANDO SERVICIOS WEB

2. WSDL Disclosure - “Confidentiality” || WS INFORMATION GATHERING (OWASP-WS-001)

WSDL Google Hacking attack - WSDL Enumeration attack (WSDL Scanning)

WSDL: son las siglas de Web Services Description Language, un formato XML que se utiliza para describir servicios Web.

WSDL describe la interfaz pública de los servicios Web. Está basado en XML y describe la forma de comunicación, es decir, los requisitos del protocolo y los formatos de los mensajes necesarios para interactuar con los servicios listados en su catálogo. Las operaciones y mensajes que soporta se describen en abstracto y se ligan después al protocolo concreto de red y al formato del mensaje.

Page 21: Atacando servicios web

ATACANDO SERVICIOS WEB

Page 22: Atacando servicios web

ATACANDO SERVICIOS WEB

Page 23: Atacando servicios web

ATACANDO SERVICIOS WEB

Se puede realizar de dos maneras:WSDL Google Hacking attackMediante funciones de búsqueda en google (google dork).inurl:wsdl site:example.comProbablemente, muchos de estos no debieron estar publicados, ni accedidos públicamente. WSDL Enumeration attackSe asume que ya se tiene la ruta de un archivo WSDL. En base a esta, se trata de conocer nuevos métodos y/o interfaces del servicio web.También es conocido como WSDL Scanning.

Page 24: Atacando servicios web

ATACANDO SERVICIOS WEB

Page 25: Atacando servicios web

ATACANDO SERVICIOS WEB

Algunas URLs:[transport]://[machine or domain][:optional port]/[optional uri]http://<webservice-host>:<port>/<servicename>http://<webservice-host>:<port>/<servicename>.wsdlhttp://<webservice-host>:<port>/<servicename>?wsdlhttp://<webservice-host>:<port>/<servicename>.aspx?wsdlen lugar de extension .aspx podemos usar extensiones .ascx, .asmx, .ashx, .jws,.svc en lugar de poner “wsdl”, podemos poder “disco”http://<webservice-host>:<port>/<servicename.dll>?wsdlhttp://<webservice-host>:<port>/<servicename.exe>?wsdlhttp://<webservice-host>:<port>/<servicename.php>?wsdlhttp://<webservice-host>:<port>/<servicename.pl>?wsdl Para Apache Axis podemos tratar con:http://<webservice-host>:<port>/axis/services/<servicename>?wsdlhttp://<webservice-host>:<port>/axis/services/<service-name>

Page 26: Atacando servicios web

ATACANDO SERVICIOS WEBTIPOS DE WEB SERVICES

El A,B,C

ADRESS (Donde encuentro el servicio?)Direccion única[transport]://[machine or domain][:optional port]/[optional uri]

BINDING (Como hablo con el servicio?)Protocolo de Transporte / Codificación / Seguridad

CONTRACT (Que puedo hacer con el servicio?)Metodos expuestos

Autenticación, Autorización?

Page 27: Atacando servicios web

ATACANDO SERVICIOS WEB

http://192.168.56.101/webgoat/services/SoapRequest?WSDLWebgoat: Create SOAP Request (1 y 2)

WSDL es una fuente valiosa de información! (para los buenos, pero también para los malos)

Desafortunadamente, la única protección de algunos servicios web, es que están “ocultos”.

Page 28: Atacando servicios web

ATACANDO SERVICIOS WEBTIPOS DE WEB SERVICES

TRANSPORT PROTOCOLSNET.TCPHTTP/HTTPSNAMED PIPES (IPC)PEER TO PEER (P2P)MESSAGE QUEUING (MSMQ) ENCODING FORMATSTEXT (SOAP, XML, JAVASCRIPT)BINARYMTOM

SEGURIDADNONETRANSPORTMESSAGE

AUTENTICACIONTransporte:NoneBasicNTLMWindowsCertificate

Mensaje:NoneWindowsUsernameCertificateIssue Token

BINDING? Protocolo de Transporte / Codificación / Seguridad(Como hablo con el servicio?)

Page 29: Atacando servicios web

ATACANDO SERVICIOS WEB

Page 30: Atacando servicios web

ATACANDO SERVICIOS WEB

TRANSPORT PROTOCOL: HTTPENCODING: SOAPSEGURIDAD: NONEAUTENTICACION: NONE

WCFBASICHTTPBINDING

Page 31: Atacando servicios web

ATACANDO SERVICIOS WEB

HERRAMIENTAS

Depende del binding!

Page 32: Atacando servicios web

ATACANDO SERVICIOS WEBHERRAMIENTAS

Configurar SoapUI + Burp

Page 33: Atacando servicios web

ATACANDO SERVICIOS WEBHERRAMIENTAS

WcfTestClient + Burp (o la que Uds. quieran)C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\WcfTestClient.exe

Page 34: Atacando servicios web

ATACANDO SERVICIOS WEBHERRAMIENTAS

Programar Cliente (lenguaje que quieran?):

Page 35: Atacando servicios web

ATACANDO SERVICIOS WEB

3. TESTING WSDL (OWASP-WS-002)Revisar el archivo WSDL del servicio web para encontrar los puntos de entrada y probar incovando las operaciones que no son usadas en un requerimiento SOAP estándar (operaciones escondidas). Probar si es que el WS entrega información confidencial.

Webgoat: WSDL Scanning1. En el Browser2. En SOAPUIhttp://192.168.56.101/webgoat/services/WSDLScanning?WSDL

Page 36: Atacando servicios web

ATACANDO SERVICIOS WEB

SOAP:SOAP (siglas de Simple Object Access Protocol) es un protocolo estándar que define cómo dos objetos en diferentes procesos pueden comunicarse por medio de intercambio de datos XML

Page 37: Atacando servicios web

ATACANDO SERVICIOS WEBSubtítulo tamaño 18 ARIAL

Page 38: Atacando servicios web

ATACANDO SERVICIOS WEB

4. XML CONTENT-LEVEL TESTING (OWASP-WS-004) Esto se logra, alterando los mensajes SOAP para que cumplan nuestro cometido.

Abarca ataques al web services y a todo a lo cual él se conecta y está detrás (web servers, databases, application servers, operating systems, etc).

Page 39: Atacando servicios web

ATACANDO SERVICIOS WEB

NOTA

Muchas de las técnicas de hacking (pentesting) de aplicaciones web, aplican también para servicios web.

Las vulnerabilidades en servicios web son similares a las vulnerabilidades en aplicaciones web (SQL injection, information disclosure, etc), pero los servicios web también tienen vulnerabilidades únicas (por ejemplo, vulnerabilidades relacionadas al XML parser).

Page 40: Atacando servicios web

ATACANDO SERVICIOS WEB

Parecido?

SpoofingSpoofed requests: Attacker spoofs a request from a legitimate clientSpoofed responses: Attacker spoofs a response from the server TamperingMan-in-the-middle attack: Attacker inserts themselves into the communication path between communicating parties and impersonates each to the otherInjection attack: Attacker supplies malicious input that is directly used in calls to an external or underlying systemInsertion of malicious software: Attacker manages to execute or place malicious software on the system RepudiationDenying a web service transaction: Attacker exploits inadequate logging to deny the occurrence of a transactionReplay attack: Attacker captures and replays a valid web method request to the server

Page 41: Atacando servicios web

ATACANDO SERVICIOS WEB

Parecido?

Information DisclosureEavesdropping on communication paths: An attacker on the communication path captures passing network trafficInformation leaked by verbose error messages: Attacker induces error conditions to extract platform and implementation detailsUnauthorised access to services or data: Attacker bypasses access control mechanisms or uses a service that wasnot meant to be running Denial of ServiceDeplete computer or network resources: Attacker floods the system with junk traffic or valid requests to overwhelm computers, routers, capacity etc.Exploit a programming or implementation flaw: Attacker finds and exploits a flaw in implementation that causes the system to hang or crashCorruption of data to prevent normal operation of the web service: An attacker corrupts application data by exploiting a vulnerability or using unauthorised functionality

Page 42: Atacando servicios web

ATACANDO SERVICIOS WEB

Parecido?

Elevation of PrivilegeRemote execution of code or software: An attacker exploits a buffer overflow vulnerability to access or executecommands on the target host with higher privileges than authorisedAdministrative interfaces or functions available: Attacker is able to access administrative interfaces or functions bybypassing access control mechanisms

Webgoat:Web Service SQL Injection - SOAPUI

Page 43: Atacando servicios web

ATACANDO SERVICIOS WEB

Diferente? TESTING WSDL XML STRUCTURAL TESTING XML CONTENT-LEVEL TESTING HTTP GET PARAMETERS/REST TESTING NAUGHTY SOAP ATTACHMENTS Replay Attack - “Access Control” || REPLAY TESTING Web Service Intermediario controlado por un atacantePassive WS-MITM - “Confidentiality” (Message Sniffing / Message Snopping)Active WS-MITM - "Integrity"Malicious Morphing (Message Tampering / Content Tampering / Message Alternation / Data Tampering / Falsified Message)Routing Detour XML Signature Wrapping - "Integrity" (XML Rewriting)XML Signature Wrapping - Simple Context XML Signature Wrapping - Optional ElementXML Signature Wrapping - Optional Element in Security Header

Page 44: Atacando servicios web

ATACANDO SERVICIOS WEB

Diferente? SOAPAction Spoofing - “Access Control”SOAPAction Spoofing - MITM AttackSOAPAction Spoofing - Bypass Attack Metadata Spoofing - "Integrity"WSDL Spoofing (WSDL Parameter Tampering)WS Security Policy Spoofing Attack ObfuscationXML InjectionXML Signature - Key Retrieval XSA (Cross Site Attack)XML Signature – XSLT Code ExecutionXpath Injection

Page 45: Atacando servicios web

ATACANDO SERVICIOS WEB

Diferente? Attacks primarily violating the security objective "Availability"BPEL Instantiation FloodingBPEL Indirect FloodingBPEL State Deviation BPEL Correlation Invalidation BPEL State Invalidation Coercive ParsingOversized XML DOS (Oversized XML attack) XML Extra Long Names (XML MegaTags / XML Jumbo Tag Names) XML Namespace Prefix Attack XML Oversized Attribute Content XML Oversized Attribute Count Reference Redirect Signature Redirect Encryption Redirect Recursive Cryptography (Oversized Cryptography / Cryptography DOS / XML Complexity Attack in Soap Header) Chained Cryptographic Keys aka Public Key DOS Nested Encrypted Blocks

Page 46: Atacando servicios web

ATACANDO SERVICIOS WEB

Diferente? Soap Array AttackSOAP Parameter DOS (Parameter Tampering)WS-Addressing spoofing WS-Addressing spoofing - Generic WS-Addressing spoofing - BPEL Rollback WS-Addressing spoofing - Middleware Hijacking XML Document Size Attack (Oversize payload attack / Jumbo payload Attack) Oversized SOAP Header Oversized SOAP Body Oversized SOAP Envelope XML Encryption - Transformation DOS XML Encryption - XSLT DOS XML Encryption - Xpath DOS XML External Entity DOSXML Entity Expansion XML Generic Entity Expansion XML Recursive Entity Expansion XML Remote Entity Expansion XML C14N Entity Expansion

Page 47: Atacando servicios web

ATACANDO SERVICIOS WEB

Diferente? XML Entity Reference AttackXML Flooding Distributed XML Flooding Single XML Flooding XML Signature - Key Retrieval DOSXML Signature – Transformation DOS XML Signature - C14N DOS XML Signature - XSLT DOS XML Signature - Xpath DOS

Webgoat:Web Service SAX Injection (parser) - Browser

Page 48: Atacando servicios web

ATACANDO SERVICIOS WEB

Hablando de números de tarjeta de crédito:Generalmente sale en los ejemplos por algo? Es sensible dicha información?

Han comprado en Saga Falabella?Han pagado con tarjeta?Han visto que en los recibos de caja aparecen los 16 digitos completos!?

La seguridad…Le importa a Saga Falabella? A los bancos? A Mastercard?

http://fiery-owl.blogspot.com/2012/11/ahora-quien-podra-defenderme.html

Hackspy:"NADA ES TAN IMPORTANTE, NI TAN URGENTE QUE NO PUEDA SER HECHO CON SEGURIDAD" Anónimo

Page 49: Atacando servicios web

Preguntas?

Page 50: Atacando servicios web

Gracias!

corregir, aportar, etc: [email protected]