Altres eines: netcat, hping, netstat, packettracer

De wikijoan
Salta a la navegació Salta a la cerca

PacketTracer

PacketTracer no és pròpiament un software de seguretat, sinó que és més genèric: simulació de xarxes (xarxes Cisco). Pot ser útil tenir-lo a mà, ni que sigui per dibuixar la nostra topologia de xarxa.

Es pot descarregar de la Cisco Networking Academy: (es necessita un compte de Cisco)

o bé cercar el paquet binari per la xarxa, per exemple:

Descarreguem l'arxiu PacketTracer53_i386_installer-deb.rar

$ chmod +x PacketTracer53_i386_installer-deb.bin
$ sudo sh PacketTracer53_i386_installer-deb.bin

Aplicacions > Internet > Cisco Packet Tracer o bé

$ /usr/local/PacketTracer5/packettracer

Tutorials:

Després de la instal.lació tenim una ajuda local:

  • file:///usr/local/PacketTracer5/help/default/index.htm

Hi ha un problema amb la font, que té un tamany molt gros. Es pot anar a Preferències, i elegir la font Arial per tot, però de totes maneres no s'arregla en algunes parts. Es pot solucionar seguint:

Una solució que es proposa i que m'ha funcionat.

$ sudo apt-get install ttf-mscorefonts-installer 

i tornar a obrir la sessió

netstat

# man netstat

NAME
       netstat  - Print network connections, routing tables, interface statis‐
       tics, masquerade connections, and multicast memberships
$ netstat --help
usage: netstat [-vWeenNcCF] [<Af>] -r         netstat {-V|--version|-h|--help}
       netstat [-vWnNcaeol] [<Socket> ...]
       netstat { [-vWeenNac] -i | [-cWnNe] -M | -s }

        -r, --route              display routing table
        -i, --interfaces         display interface table
        -g, --groups             display multicast group memberships
        -s, --statistics         display networking statistics (like SNMP)
        -M, --masquerade         display masqueraded connections

        -v, --verbose            be verbose
        -W, --wide               don't truncate IP addresses
        -n, --numeric            don't resolve names
        --numeric-hosts          don't resolve host names
        --numeric-ports          don't resolve port names
        --numeric-users          don't resolve user names
        -N, --symbolic           resolve hardware names
        -e, --extend             display other/more information
        -p, --programs           display PID/Program name for sockets
        -c, --continuous         continuous listing

        -l, --listening          display listening server sockets
        -a, --all, --listening   display all sockets (default: connected)
        -o, --timers             display timers
        -F, --fib                display Forwarding Information Base (default)
        -C, --cache              display routing cache instead of FIB

  <Socket>={-t|--tcp} {-u|--udp} {-w|--raw} {-x|--unix} --ax25 --ipx --netrom
  <AF>=Use '-6|-4' or '-A <af>' or '--<af>'; default: inet
  List of possible address families (which support routing):
    inet (DARPA Internet) inet6 (IPv6) ax25 (AMPR AX.25) 
    netrom (AMPR NET/ROM) ipx (Novell IPX) ddp (Appletalk DDP) 
    x25 (CCITT X.25) 

Exemples d'ús

segueixo:

netstat --tcp

Si volem mirar les connexions TCP. Ens mostra la llista de connexions TCP que tenen com a origen o destí la nostra màquina. En l'exemple es mostren connexions TCP cap a la nostra màquina i des de la nostra màquina. Per provar el SSH hem fet una connexió local ($ ssh joan@localhsot i una connexió remota: $ ssh joan@wiki.joanillo.org). El valor que es pot veure, 120.77.221.87, en realitat l'hem d'invertir per veure la ip púplica del servidor wiki.joanillo.org (fent $ ping wiki.joanillo.org obtenim 87.221.77.120). També podem veure com en la màquina de proves està instal.lat Dropbox i UbuntuOne (que són dos serveis diferents i similars que ens donen un espai d'emmagatzematge al núvol).

$ netstat --tcp
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
...
tcp        0      0 joan-laptop.local:57591 120.77.221.87.dynam:ssh ESTABLISHED
tcp       38      0 joan-laptop.local:39507 one-ubuntu-com.am:https CLOSE_WAIT 
tcp       38      0 joan-laptop.local:47725 couchdb-one-ubunt:https CLOSE_WAIT 
tcp        0      0 joan-laptop.local:59616 sjc-not2.sjc.dropbo:www ESTABLISHED
tcp6       0      0 localhost:47449         localhost:ssh           ESTABLISHED
tcp6       0      0 localhost:ssh           localhost:47449         ESTABLISHED
...

i la mateixa informació sense la resolució de noms:

$ netstat --tcp --numeric
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
...
tcp        0      0 192.168.1.131:57591     87.221.77.120:22        ESTABLISHED
tcp       38      0 192.168.1.131:39507     91.189.89.219:443       CLOSE_WAIT 
tcp       38      0 192.168.1.131:47725     91.189.89.212:443       CLOSE_WAIT 
tcp        0      0 192.168.1.131:59616     199.47.217.144:80       ESTABLISHED
tcp6       0      0 ::1:47449               ::1:22                  ESTABLISHED
tcp6       0      0 ::1:22                  ::1:47449               ESTABLISHED
...

netstat --tcp --listening --programs

Si volem veure els ports TCP pels quals la màquina està escoltant, utilitzarem les opcions netstat --tcp --listening. Si afegim --programs indica en la última columna, si ho sap fer, quin és el procés que està escoltant pel port especificat. Veiem que la màquina està escoltant en els ports ports 80 (www), 443 (https), 23 (telnet), 22 (ssh), i 3306 (mysql); (per veure el número dels ports, opció --numeric)

~ netstat --tcp --listening --programs
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 localhost:42217         *:*                     LISTEN      1833/beam       
tcp        0      0 localhost:mysql         *:*                     LISTEN      -               
tcp        0      0 *:38000                 *:*                     LISTEN      11347/PacketTracer5
tcp        0      0 *:ssh                   *:*                     LISTEN      -               
tcp        0      0 localhost:ipp           *:*                     LISTEN      -               
tcp        0      0 *:telnet                *:*                     LISTEN      -               
tcp        0      0 *:39000                 *:*                     LISTEN      11347/PacketTracer5
tcp        0      0 localhost:36251         *:*                     LISTEN      1921/ssl_esock  
tcp        0      0 *:17500                 *:*                     LISTEN      10039/dropbox   
tcp6       0      0 [::]:www                [::]:*                  LISTEN      -               
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN      -               
tcp6       0      0 localhost:ipp           [::]:*                  LISTEN      -               
tcp6       0      0 [::]:https              [::]:*                  LISTEN      - 

netstat --route

Ens mostra la taula de routing:

# netstat --route

Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
192.168.1.0     *               255.255.255.0   U         0 0          0 eth1
link-local      *               255.255.0.0     U         0 0          0 eth1
default         192.168.1.1     0.0.0.0         UG        0 0          0 eth1

netstat -lt

i ara només miro les connexions que estan escoltant pel port TCP.

# netstat -lt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 localhost:42217         *:*                     LISTEN     
tcp        0      0 localhost:mysql         *:*                     LISTEN     
tcp        0      0 *:38000                 *:*                     LISTEN     
tcp        0      0 *:ssh                   *:*                     LISTEN     
tcp        0      0 localhost:ipp           *:*                     LISTEN     
tcp        0      0 *:telnet                *:*                     LISTEN     
tcp        0      0 *:39000                 *:*                     LISTEN     
tcp        0      0 localhost:36251         *:*                     LISTEN     
tcp        0      0 *:17500                 *:*                     LISTEN     
tcp6       0      0 [::]:www                [::]:*                  LISTEN     
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN     
tcp6       0      0 localhost:ipp           [::]:*                  LISTEN     
tcp6       0      0 [::]:https              [::]:*                  LISTEN

traceroute

És equivalent al tracert de Windows

# apt-get install traceroute

Traceroute intenta traçar la ruta que un paquet IP fa per arribar a un host d'Internet. Per fer-ho va enviant paquets de prova amb un temps de vida curts (small live-to-live, TTL), i escolta la resposta ICMP (la resposta del ping).

El servidor des d'on es fa la prova està en una ADSL domèstica, i el servidor wiki.joanillo.org també està en una ADSL domèstica. Totes dues ADSL són de Jazztel.

# traceroute wiki.joanillo.org
traceroute to wiki.joanillo.org (87.221.77.120), 30 hops max, 60 byte packets
 1  192.168.1.1 (192.168.1.1)  1.393 ms  1.677 ms  1.797 ms
 2  1.98.19.95.dynamic.jazztel.es (95.19.98.1)  48.758 ms  50.605 ms  52.135 ms
 3  10.255.137.254 (10.255.137.254)  54.104 ms  55.446 ms  56.361 ms
 4  * * *
 5  120.77.221.87.dynamic.jazztel.es (87.221.77.120)  93.663 ms  95.872 ms  97.162 ms
 If there is no response within a 5.0 seconds (default),
an "*" (asterisk) is printed for that probe.

netcat

Netcat està considerada la navalla suïssa de TCP/IP. És una de les eines de xarxa més útils.

En els repositoris hi ha diferents versions de netcat. Per fer la pràctica seguirem el binari netcat.traditional (http://ubuntuforums.org/showthread.php?t=828870)

# apt-get install netcat-traditional
# man netcat

NC(1)                     BSD General Commands Manual                    NC(1)

NAME
     nc — arbitrary TCP and UDP connections and listens

SYNOPSIS
     nc [-46DdhklnrStUuvzC] [-i interval] [-P proxy_username] [-p source_port]
        [-s source_ip_address] [-T ToS] [-w timeout] [-X proxy_protocol] [-x
        proxy_address[:port]] [hostname] [port[s]]

DESCRIPTION
     The nc (or netcat) utility is used for just about anything under the sun
     involving TCP or UDP.  It can open TCP connections, send UDP packets,
     listen on arbitrary TCP and UDP ports, do port scanning, and deal with
     both IPv4 and IPv6.  Unlike telnet(1), nc scripts nicely, and separates
     error messages onto standard error instead of sending them to standard
     output, as telnet(1) does with some.

     Common uses include:

           ·   simple TCP proxies
           ·   shell-script based HTTP clients and servers
           ·   network daemon testing
           ·   a SOCKS or HTTP ProxyCommand for ssh(1)
           ·   and much, much more

Ara bé, les opcions que veiem en netcat (nc) no coincideixen exactament amb les opcions que trobem a nc.traditional. Per exemple, a nc.traditional tenim l'opció -c:

# nc.traditional -h
[v1.10-38]
connect to somewhere:	nc [-options] hostname port[s] [ports] ... 
listen for inbound:	nc -l -p port [-options] [hostname] [port]
options:
	-c shell commands	as `-e'; use /bin/sh to exec [dangerous!!]
	-e filename		program to exec after connect [dangerous!!]
	-b			allow broadcasts
	-g gateway		source-routing hop point[s], up to 8
	-G num			source-routing pointer: 4, 8, 12, ...
	-h			this cruft
	-i secs			delay interval for lines sent, ports scanned
        -k                      set keepalive option on socket
	-l			listen mode, for inbound connects
	-n			numeric-only IP addresses, no DNS
	-o file			hex dump of traffic
	-p port			local port number
	-r			randomize local and remote ports
	-q secs			quit after EOF on stdin and delay of secs
	-s addr			local source address
	-T tos			set Type Of Service
	-t			answer TELNET negotiation
	-u			UDP mode
	-v			verbose [use twice to be more verbose]
	-w secs			timeout for connects and final net reads
	-z			zero-I/O mode [used for scanning]
port numbers can be individual or ranges: lo-hi [inclusive];
hyphens in port names must be backslash escaped (e.g. 'ftp\-data

CLIENT/SERVER MODEL

It is quite simple to build a very basic client/server model using nc. On one console, start nc listening on a specific port for a connection. For example:

# nc.traditional -l -p 1234

nc is now listening on port 1234 for a connection. On a second console (or a second machine), connect to the machine and port being listened on:

# nc.traditional 127.0.0.1 1234

There should now be a connection between the ports. Anything typed at the second console will be concatenated to the first, and vice-versa. After the connection has been set up, nc does not really care which side is being used as a server and which side is being used as a client. The connection may be terminated using an EOF (^D).

En el cas de què en la primera consola escrigui

# nc.traditional -l -p 1234 -e /bin/sh

significa que en la segona consola hauria de posar el nom d'un script, que s'executa en la primera consola.

HTTP Client

nota: fer:

# echo -e "GET /iesbalmes/wec/tenda/img/dish0.jpeg HTTP/1.0\r\n" | nc.traditional wiki.joanillo.org 80 > info.txt

i mirar el contingut del fitxer info.txt. Veuràs la capçalera de la petició http.

# echo -e "GET /kdist/finger_banner HTTP/1.0\r\n" | nc.traditional www.kernel.org 80

HTTP/1.1 200 OK
Date: Fri, 02 Dec 2011 09:51:05 GMT
Server: Apache/2.2.21 (Fedora)
Last-Modified: Wed, 31 Aug 2011 05:14:04 GMT
ETag: "1781eb0-3bd-4abc63261ff00"
Accept-Ranges: bytes
Content-Length: 957
Connection: close
Content-Type: text/plain; charset=UTF-8

The latest linux-next version of the Linux kernel is:         next-20110831
The latest linux-next version of the Linux kernel is:         next-20110831
The latest snapshot 3 version of the Linux kernel is:         3.1-rc4-git2
The latest mainline 3 version of the Linux kernel is:         3.1-rc4   
The latest stable 3.0 version of the Linux kernel is:         3.0.4     
The latest stable 2.6.39 version of the Linux kernel is:      2.6.39.4  
The latest stable 2.6.38 version of the Linux kernel is:      2.6.38.8  
The latest stable 2.6.37 version of the Linux kernel is:      2.6.37.6  
The latest longterm 2.6.35 version of the Linux kernel is:    2.6.35.14 
The latest longterm 2.6.34 version of the Linux kernel is:    2.6.34.10 
The latest longterm 2.6.33 version of the Linux kernel is:    2.6.33.19 
The latest longterm 2.6.32 version of the Linux kernel is:    2.6.32.46 
The latest longterm 2.6.27 version of the Linux kernel is:    2.6.27.59 

Port scanning

# nc.traditional -v -z www.kernel.org 80 21

pub2.kernel.org [149.20.4.69] 80 (www) open
pub2.kernel.org [149.20.4.69] 21 (ftp) open

o bé posem un rang de ports:

$ nc.traditional -v -z www.kernel.org 21-23

pub2.kernel.org [149.20.4.69] 22 (ssh) open
pub2.kernel.org [149.20.4.69] 21 (ftp) open

Chat

Podem fer una comunicació simple entre dues consoles:

# nc.traditional -lp 8080

i en una altra consola, el client el connectem al servidor (recorda que en comptes de localhost pots fer la prova entre màquines diferents, amb el teu company):

# nc.traditional localhost 8080
o bé
# nc.traditional <host> 8080

hping (hping3)

hping3 s'ha d'executar com a sudo.

# sudo apt-get install hping3
# man hping3

NAME
       hping3 - send (almost) arbitrary TCP/IP packets to network hosts

DESCRIPTION
       hping3  is  a  network tool able to send custom TCP/IP packets and to display target replies like ping program does
       with ICMP replies. hping3 handle fragmentation, arbitrary packets body and size and can be used in order to  trans‐
       fer  files  encapsulated  under  supported  protocols.  Using hping3 you are able to perform at least the following
       stuff:

        - Test firewall rules
        - Advanced port scanning
        - Test net performance using different protocols,
          packet size, TOS (type of service) and fragmentation.
        - Path MTU discovery
        - Transferring files between even really fascist firewall
          rules.
        - Traceroute-like under different protocols.
        - Firewalk-like usage.
        - Remote OS fingerprinting.
        - TCP/IP stack auditing.
        - A lot of others.

       It's also a good didactic tool to learn TCP/IP.  hping3 is developed and maintained by  antirez@invece.org  and  is
       licensed under GPL version 2. Development is open so you can send me patches, suggestion and affronts without inhi‐
       bitions.

# hping3 -h

Els exemples estan trets de:

Fem un ping al router: (-1 significa que enviem un paquet ICMP, igual que faria el ping normal)

# hping3 -c 3 -I eth1 -1 192.168.1.1

HPING 192.168.1.1 (eth1 192.168.1.1): icmp mode set, 28 headers + 0 data bytes
len=28 ip=192.168.1.1 ttl=64 id=55366 icmp_seq=0 rtt=1.2 ms
len=28 ip=192.168.1.1 ttl=64 id=55367 icmp_seq=1 rtt=0.9 ms
len=28 ip=192.168.1.1 ttl=64 id=55368 icmp_seq=2 rtt=1.0 ms

2n exemple:

# hping3 -c 1 -I eth1 -s 5678 -p 80 -S 192.168.1.1
HPING 192.168.1.1 (eth1 192.168.1.1): S set, 40 headers + 0 data bytes
len=44 ip=192.168.1.1 ttl=64 DF id=0 sport=80 flags=SA seq=0 win=5840 rtt=1.2 ms

--- 192.168.1.1 hping statistic ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 1.2/1.2/1.2 ms

Ara enviem la mateixa informació però pel port 89, que està tancat:

# hping3 -c 1 -I eth1 -s 5678 -p 89 -S 192.168.1.1
HPING 192.168.1.1 (eth1 192.168.1.1): S set, 40 headers + 0 data bytes
len=40 ip=192.168.1.1 ttl=64 DF id=0 sport=89 flags=RA seq=0 win=0 rtt=1.0 ms

--- 192.168.1.1 hping statistic ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 1.0/1.0/1.0 ms

Per veure la diferència entre les dues respostes ens hem de fixar en els flags que rebem: flags=SA en el primer cas, i flags=RA en el segon cas:

TCP OUTPUT FORMAT
       The standard TCP output format is the following:

       len=46 ip=192.168.1.1 flags=RA DF seq=0 ttl=255 id=0 win=0 rtt=0.4 ms

       len  is  the  size,  in bytes, of the data captured from the data link
       layer excluding the data link header size. This may not match  the  IP
       datagram size due to low level transport layer padding.

       ip is the source ip address.

       flags are the TCP flags, R for RESET, S for SYN, A for ACK, F for FIN,
       P for PUSH, U for URGENT, X for not standard 0x40, Y for not  standard
       0x80.

       If the reply contains DF the IP header has the don't fragment bit set.

       seq  is  the  sequence number of the packet, obtained using the source
       port for TCP/UDP packets, the sequence field for ICMP packets.

       id is the IP ID field.

       win is the TCP window size.

       rtt is the round trip time in milliseconds.

Com podem llegir a:

...
Si en la respuesta los flags son RA esto nos indicará que el puerto esta cerrado.
...

creat per Joan Quintana Compte, desembre 2011