Comandos Utiles Adm

Comandos utiles para la administracion y diagnostico de sistemas.
Nota: Solo documento los que me han parecido curiosos. (Omito los Obbios)

-Pegar texto en una Virtualbox

Ejs:

    VBoxManage controlvm "livecd" keyboardputstring "sudo apt-get install -y pcscd pcsc-tools libccid" 
    VBoxManage controlvm "FreeDOS" keyboardputfile "/Users/socratis/Desktop/cmd.txt"
    VBoxManage controlvm "livecd" keyboardputscancode 1c 9c
    
    VBoxManage controlvm "livecd" keyboardputstring wget https://www.dnielectronico.es/descargas/distribuciones_linux/libpkcs11-dnie_1.5.0_amd64.deb
    VBoxManage controlvm "livecd" keyboardputscancode 1c 9c
    
    VBoxManage controlvm "livecd" keyboardputstring sudo gdebi libpkcs11-dnie_1.5.0_amd64.deb
    VBoxManage controlvm "livecd" keyboardputscancode 1c 9c
    



strace depuracion de programas

strace echo hola 2>&1

    em50l@jejo.es$ strace echo hola 2>&1 
    execve("/bin/echo", ["echo", "hola"], 0x7ffc0c6b6ea8 /* 50 vars */) = 0
    brk(NULL)                               = 0x55905a1b2000
    access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
    access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
    openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
    fstat(3, {st_mode=S_IFREG|0644, st_size=110722, ...}) = 0
    mmap(NULL, 110722, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f70f1425000
    close(3)                                = 0
    

strace echo hola 2>&1 |grep open ver llamadas al sistema.

    em50l@jejo.es$ strace echo hola 2>&1 |grep open
    openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
    openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
    openat(AT_FDCWD, "/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3
    

strace ping 8.8.8.8 -c 1 2>&1 | grep write

    em50l@jejo.es$ strace echo hola 2>&1 
    write(1, "PING 8.8.8.8 (8.8.8.8) 56(84) by"..., 99PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
    write(1, "\n", 1
    write(1, "--- 8.8.8.8 ping statistics ---\n"..., 145--- 8.8.8.8 ping statistics ---
    



Informacion del sistema operativo (Linux)

    cat /etc/os-release
    lsb_release -a
    hostnamectl
    uname -r
    



Ver que librerias usa un programa.

ldd $(which socat)

    root@ne:~# ldd $(which socat)
        linux-vdso.so.1 (0x00007fff7d157000)
        libwrap.so.0 => /lib/x86_64-linux-gnu/libwrap.so.0 (0x00007efc3c1f7000)
        libutil.so.1 => /lib/x86_64-linux-gnu/libutil.so.1 (0x00007efc3bff4000)
        libssl.so.1.0.0 => /usr/lib/x86_64-linux-gnu/libssl.so.1.0.0 (0x00007efc3bd92000)
        libcrypto.so.1.0.0 => /usr/lib/x86_64-linux-gnu/libcrypto.so.1.0.0 (0x00007efc3b995000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007efc3b5ea000)
        libnsl.so.1 => /lib/x86_64-linux-gnu/libnsl.so.1 (0x00007efc3b3d1000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007efc3b1cd000)
        /lib64/ld-linux-x86-64.so.2 (0x0000557ac76f7000)
    



Monitorear paquetes entrantes(http/https).

tcpdump -vnnl -s128 "ip and inbound and (dst port 80 or dstport 443)"

    tcpdump -vnnl -s128 "ip and inbound and (dst port 80 or dst port 443)"
    
    tcpdump: listening on venet0, link-type LINUX_SLL (Linux cooked), capture size 128 bytes
    12:33:56.3 IP (tos 0x0, ttl 64, id 40879, offset 0, flags [DF], proto TCP (6), length 52)
        1.2.3.4.46344 > 192.168.2.16.80: Flags [.], cksum 0x6199 (correct),  length 0
    
    12:33:56.4 IP (tos 0x0, ttl 64, id 40880, offset 0, flags [DF], proto TCP (6), length 177)
        1.2.3.4.46344 > 192.168.2.16.80: Flags [P.], seq 0:125, ack 1,HTTP, length: 125
        GET / HTTP/1.1
        Host: test.jejo.es
        User-Agent: curl/7.58.0
    

Mas detallado y paquetes >64: tcpdump -vvv "ip and inbound and (dst port 80 or dst port 443)"
Ojo esto no captura paquetes fragmentados pero simplifica la salida. (limpia protocolo tcp/ip) y deja solo http

    tcpdump -vvv "ip and inbound and (dst port 80 or dst port 443) and greater 64"
    
    13:00:28.2 IP (tos 0x0, ttl 64, id 2, offset 0, flags [DF], proto TCP (6), length 177)
        1.2.3.4.5536 > test.jejo.es.http: Flags [P.], cksum(correct), seq 4:9, ack 5, win 115, HTTP, length: 125
        GET / HTTP/1.1
        Host: test.jejo.es
        User-Agent: curl/7.58.0
        Accept: */*
        X-Forwarded-For: 139.47.19.179
        Connection: close
    
    

Aqui se puede ver que mi servidor esta detras de un proxy




Socat redirigir trafico interno (127.0.0.1) por un puerto externo.

En este ejemplo redirijo el trafico de hugo hacia el exterior socat -v -d -d -d TCP-LISTEN:8080,fork,reuseaddr tcp:127.0.0.1:1313

Si quieres que el trafico solo salga por una interfaz especifica ej VPN. tienes que añadir bind=
socat -v -d -d -d TCP-LISTEN:1313,fork,reuseaddr,bind=10.0.8.5 tcp:127.0.0.1:1313




Desviar http a https con socat

Sirve para redirigir una conexion http a una https. util para clientes que no soportan https.

(socat TCP-LISTEN:80,fork,reuseaddr ssl:127.0.0.1:443,verify=0 &)&




Comprobar/depurar una conexion http

Lado cliente

curl -sv test.jejo.es |head -5

    curl -sv test.jejo.es |head -5
    
    *   Trying 1.2.3.4...
    * TCP_NODELAY set
    * Connected to test.jejo.es (1.2.3.4) port 80 (#0)
    > GET / HTTP/1.1
    > Host: test.jejo.es
    > User-Agent: curl/7.58.0
    > Accept: */*
    > 
    * HTTP 1.0, assume close after body
    < HTTP/1.0 503 Service Unavailable
    < Cache-Control: no-cache
    < Connection: close
    < Content-Type: text/html
    < 
    * Closing connection 0
    503 Service Unavailable
    No server is available to handle this request.
    

Para https: curl -ksv https://test.jejo.es |head -5

    curl -ksv https://test.jejo.es |head -5
    
    *   Trying 1.2.3.4...
    * TCP_NODELAY set
    * connect to 1.2.3.4 port 443 failed: Conexión rehusada
    * Failed to connect to test.jejo.es port 443: Conexión rehusada
    * Closing connection 0
    



Lado servidor

tcpdump -vvv -s256 "ip and (port 80 or port 443) and greater 64"
La primera puede generar mucho ruido si hay consultas http a otros servidores (ya que monitores todo el trafico al 80)
tcpdump -lnnA -s256 "(inbound and dst port 80)or(outbound and src port 80)"

    tcpdump -vvv -s256 "ip and (port 80 or port 443) and greater 64"
    
    
    13:12:10.931508 IP (tos 0x0, ttl 64, id 36051, offset 0, flags [DF], proto TCP (6), length 177)
        1.2.3.4.3706 > test.jejo.es.http: Flags [P.], cksum (correct), HTTP, length: 125
        GET / HTTP/1.1
        Host: test.jejo.es
        User-Agent: curl/7.58.0
        Accept: */*
        X-Forwarded-For: 139.47.19.179
        Connection: close
        
    13:12:10.932376 IP (tos 0x0, ttl 64, id 10130, offset 0, flags [DF], proto TCP (6), length 1151)
        test.jejo.es.http > 1.2.3.4.3706: Flags [FP.],  HTTP, length: 1099
        HTTP/1.1 200 OK
        Server: nginx/1.6.2
        Date: Sun, 13 Oct 2019 17:12:10 GMT
        Content-Type: text/html
        Content-Length: 867
        Last-Modified: Sun, 13 Oct 2019 11:26:43 GMT
        Connection: close
        
    



Lado servidor Comprobar redireccion proxy inverso

Muy util para comprobar si las cabeceras http llegan bien.
tcpdump -vvv -s256 "ip and (port 80 or port 443) and greater 64" paquetes entrantes
tcpdump -vvX -s512 -i lo "inbound and dst port 1880 and greater 128"paquetes redirigidos a lo por el reverse proxy
nota: a veces no pilla el primer paquete y hay que repetir la peticion. nota: solo funciona bien con peticiones https

tcpdump -vvX -i lo "inbound and dst port 1880 and greater 128"

tcpdump: listening on lo, link-type EN10MB (Ethernet), capture size 262144 bytes
13:55:53.929313 IP (tos 0x0, ttl 64, id 14737, offset 0, flags [DF], proto TCP (6), length 243)
    localhost.localdomain.38636 > localhost.localdomain.1880: Flags [P.], cksum 0xfee7 (incorrect -> 0xf103), seq 1496830100:1496830291, ack 2848851738, win 512, options [nop,nop,TS val 3747735836 ecr 3747735836], length 191
    0x0000:  4500 00f3 3991 4000 4006 0272 7f00 0001  E...9.@.@..r....
    0x0010:  7f00 0001 96ec 0758 5937 d094 a9ce 071a  .......XY7......
    0x0020:  8018 0200 fee7 0000 0101 080a df61 e91c  .............a..
    0x0030:  df61 e91c 4745 5420 2f20 4854 5450 2f31  .a..GET./.HTTP/1
    0x0040:  2e30 0d0a 486f 7374 3a20 7573 2e6a 656a  .0..Host:.us.jej
    0x0050:  6f2e 6573 0d0a 582d 5265 616c 2d49 503a  o.es..X-Real-IP:
    0x0060:  2031 3034 2e31 3631 2e37 392e 3938 0d0a  .104.161.79.98..
    0x0070:  582d 466f 7277 6172 6465 642d 466f 723a  X-Forwarded-For:
    0x0080:  2031 3339 2e34 372e 3139 2e31 3739 2c20  .139.47.19.179,.
    0x0090:  3130 342e 3136 312e 3739 2e39 380d 0a58  104.161.79.98..X
    0x00a0:  2d46 6f72 7761 7264 6564 2d50 726f 746f  -Forwarded-Proto
    0x00b0:  3a20 6874 7470 0d0a 436f 6e6e 6563 7469  :.http..Connecti
    0x00c0:  6f6e 3a20 636c 6f73 650d 0a55 7365 722d  on:.close..User-
    0x00d0:  4167 656e 743a 2063 7572 6c2f 372e 3538  Agent:.curl/7.58
    0x00e0:  2e30 0d0a 4163 6365 7074 3a20 2a2f 2a0d  .0..Accept:.*/*.
    0x00f0:  0a0d 0a                                  ...



Comprobar/simular conexiones TCP/IP (socket), UDP

Cuando sospechamos que un cortafuegos,proxy,router… nos esta bloqueando conexionnes.
Lo es hacer una prueba sencilla de conexion.

nc -v 1.2.3.4 5678 lanza una conexion saliente TCP a la ip 1.2.3.4 por el puerto 5678

jejo@em50l:~$ nc -v 1.2.3.4 5678
Connection to 1.2.3.4 5678 port [tcp/*] succeeded!


Ej voy a comprobar una conexion TCP contra un servidor https:

jejo@em50l:~$ nc -v jejo.es 443
Connection to jejo.es 443 port [tcp/https] succeeded!

GET /
<html><head><title>400 Bad Request</title></head><body>
<h2>HTTPS is required</h2>
<p>This is an SSL protected page, please use the HTTPS scheme 
instead of the plain HTTP scheme to access this URL.<br />
Powered By LiteSpeed Web Server

Para ver respueste tendre que hacer GET / <intro><intro> pero como es un puerto https vere un error. Pero se que el servidor esta activo.


jejo@em50l:~$ nc -v jejo.es 443
nc: connect to ne.jejo.es port 443 (tcp) failed: Connection refused

Aqui la conexion TCP es rechazada. Se que hay Servidor a la escucha pero me devuelbe NACK


jejo@em50l:~$ nc -v jejo.es 1443
nc: connect to jejo.es port 443 (tcp) failed: Connection timed out

Aqui o no se establece conexion TCP o el paquete TCP/SYN (solicitud de establecimiento conexion) es ignorado. No se establece Conexion o se ignora TCP/SYN



Para recibir conexiones: nc -v -l 1443`

jejo@em50l:~$ nc -v -l 1443
Listening on [0.0.0.0] (family 0, port 1443)
Connection from localhost 50764 received!

En cuanto alguien se conecte veremos una linea estilo:
Connection from ip_origen puerto_origen received!

https://ubidots.com/blog/how-to-simulate-a-tcpudp-client-using-netcat/




Escanear un puerto especifico.

A veces un nmap no debuelve nada si los host no responden al ping:
Por lo que hay que activar -Pn
https://nmap.org/book/man-port-scanning-techniques.html
nmap -sT -Pn -p5900 10.0.8.1-8 -T2 --open

jejo@em50l:~$ sudo nmap -Pn -p5900 10.0.8.1-16 --open

Starting Nmap 7.60 ( https://nmap.org ) at 2019-12-15 14:46 CET
Nmap scan report for 10.0.8.7
Host is up (0.16s latency).

PORT     STATE SERVICE
5900/tcp open  vnc

Nmap done: 16 IP addresses (16 hosts up) scanned in 3.44 seconds

Nota: El comando anterior no detecta bien sin privilegios de root (sobre todo en redes de latencia alta)



Se arregla con -sT -T2 Pero es mucho mas lento nmap -sT -Pn -p5900 10.0.8.1-8 -T2 --open

jejo@medion:~$ nmap -sT -Pn -p5900 10.0.8.1-8 -T2 --open

Starting Nmap 7.60 ( https://nmap.org ) at 2019-12-15 14:58 CET
Nmap scan report for 10.0.8.7
Host is up (0.16s latency).

PORT     STATE SERVICE
5900/tcp open  vnc

Nmap done: 8 IP addresses (8 hosts up) scanned in 10.59 seconds






lanzar una aplicacion sin acceso a internet

unshare -r -n remarkable 

Mas formas: https://unix.stackexchange.com/questions/68956/block-network-access-of-a-process * firejail * proxifi * iptables * a local proxy (like “tinyproxy”, “privoxy”,…) that limits access to the internet? (Just use ACLs) * ej: https://www.binarytides.com/proxify-applications-with-tsocks-and-proxychains-on-ubuntu/




Lanzar una aplicacion controlando su acceso a internet

jejo@medion:~/Descargas$ sudo apt-get install proxychains
Leyendo lista de paquetes... Hecho
...
...
...
Se necesita descargar 19,6 kB de archivos.
Se utilizarán 69,6 kB de espacio de disco adicional después de esta operación.
¿Desea continuar? [S/n] S
y con solo 69kB controlas el acceso a internet de una app.
jejo@medion:~/Descargas$ proxychains remarkable
ProxyChains-3.1 (http://proxychains.sf.net)
*Spellchecking not enabled.
*To enable spellchecking install pygtkspellcheck
*https://pypi.python.org/pypi/pygtkspellcheck/
|DNS-request| remarkableapp.github.io 
|S-chain|-<>-127.0.0.1:8080-<--timeout
|DNS-response|: remarkableapp.github.io does not exist
Warning: Remarkable could not connect to the internet to check for updates
|DNS-request| cdnjs.cloudflare.com 
|DNS-request| cdnjs.cloudflare.com 
|DNS-request| cdn.mathjax.org 
|S-chain|-<>-127.0.0.1:8080-<--timeout
|S-chain|-<>-127.0.0.1:8080-<--timeout
|DNS-response|: cdnjs.cloudflare.com does not exist
|DNS-response|: cdn.mathjax.org does not exist
|S-chain|-<>-127.0.0.1:8080-<--timeout
|DNS-response|: cdnjs.cloudflare.com does not exist

https://www.binarytides.com/proxify-applications-with-tsocks-and-proxychains-on-ubuntu/




Servidor WEB en python

Aqui esta la salida del servidor web en el que se ven las 4 peticiones que han entrado.
python3 -m http.server 80

root@serv1:/etc/letsencrypt/live# python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 ...
127.0.0.1 - - [08/Dec/2019 13:02:40] code 404, message File not found
127.0.0.1 - - [08/Dec/2019 13:02:40] "GET /.well-known/acme-challenge/ HTTP/1.1" 404 -
192.168.1.105 - - [08/Dec/2019 13:01:13] code 404, message File not found
192.168.1.105 - - [08/Dec/2019 13:01:13] "GET /.well-known/acme-challenge/ HTTP/1.1" 404 -
10.8.0.2 - - [08/Dec/2019 13:06:12] code 404, message File not found
10.8.0.2 - - [08/Dec/2019 13:06:12] "GET /.well-known/acme-challenge/ HTTP/1.1" 404 -



HTTP/HTTPS proxy in a single python script

https://github.com/inaz2/proxy2




NAT Router desde linea de comandos

https://how-to.fandom.com/wiki/How_to_set_up_a_NAT_router_on_a_Linux-based_computer Hago Nat desde eth0:0 saliendo por wifi (wlan0)

root@kali:~# ifconfig eth0:0 192.168.6.1 255.255.255.0
SIOCSIFADDR: Argumento inválido
root@kali:~# ip a |grep global
    inet 169.254.164.143/16 brd 169.254.255.255 scope global eth0
    inet 192.168.6.1/24 brd 192.168.6.255 scope global eth0:0
    inet 192.168.43.39/24 brd 192.168.43.255 scope global dynamic noprefixroute wlan0
    inet 10.8.0.6/24 brd 10.8.0.255 scope global tun0
root@kali:~# modprobe iptable_nat
root@kali:~# echo 1 > /proc/sys/net/ipv4/ip_forward
root@kali:~# iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
root@kali:~# iptables -A FORWARD -i eth0:0 -j ACCEPT

Para el DNS:
root@kali:~# sudo apt-get install dnsmasq
Leyendo lista de paquetes... Hecho
...
...
root@kali:~# /etc/init.d/dnsmasq start
Starting dnsmasq (via systemctl): dnsmasq.service.
root@kali:~# netstat -putln
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:53              0.0.0.0:*               LISTEN      27056/dnsmasq       
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      507/sshd            
tcp6       0      0 :::53                   :::*                    LISTEN      27056/dnsmasq       
tcp6       0      0 :::22                   :::*                    LISTEN      507/sshd            
udp        0      0 0.0.0.0:53              0.0.0.0:*                           27056/dnsmasq       
udp6       0      0 :::53                   :::*                                27056/dnsmasq       
root@kali:~# 



Varios

airodump-ng wlan0
iw phy phy0
iw phy
nmcli con up "miwifi"&
reboot
sh wifi.sh 
nmcli con up X30&
ifconfig wlan0 down
ip link set wlan0 down
iw dev wlan0 interface add mon0 type monitor
iw dev
ifconfig wlan0 up

iwlist 
iwlist wlan0
iw phy
iw phy phy0 info


scapy