Linux tips

From Grayhat cheatsheets
Jump to navigationJump to search

Named pipes[edit | edit source]

like normal pipes ( | ), but between two different terminals: In one terminal:

mkfifo pipe

cat < pipe

In another terminal:

ls -l > pipe1

And the first receives the output from the second


The ldd command shows what dynamic libraries an executable file uses. Can be used several times on the same file to check if an OS is using ASLR if a library is every time on a different address. ldd filename


============[edit | edit source]

dos2unix convierte entre formatos de archivos entre distintos OS, parece. ippsec lo usa una vez que vio en un script sherlock.ps1 que le salia unicode, y lo uso para que se convirtirera. lo hace en el video de la maquina bastard

If we find a .cap file and with wireshark we see protocol 802.11, it is wifi traffic, and the password can be cracked with aircrack-ng file.cap -w /path-to-dictionary/dictionary.txt

Executing "sudo -l" we are able to see if the current user can run commands and sudo, and if he can, whether he needs a password or not*************************** (ejemplos)

Compile with mingw:

i686-w64-mingw32-gcc 80.c -lws2_32 -o 80.exe

And run the executalbe

wine 646.exe 10.11.1.35


grep recursively to find a text in files in subdirectories:

grep -rl "string" /path

Grep for everything starting with "pass":

grep ^pass


Find files:

find /path -name program.c

======[edit | edit source]

en bash, si se quiere hacer fuzzing de un programa que espera un argumento usando python one line, se tiene que meter el argumento en $(), como en stack1 de protostar: ./stack1 $(python -c “print ‘a’*64+'dcba'”) grep de varias cosas a la vez. se puede usar egrep, o grep -E (extended grep ambos). and es .* searchsploit transaction | egrep -i microsoft.*ktm lo anterior busca los resultados que contengan microsoft y ktm, independientemente de las mayusculas ******************************+

Add a line at the beginning of a file (useful for big files that take a while to load in editors)

sed -i '1 i\newWord' rockyou.txt

Adds "newWord" to rockyou.txt

irb opens a ruby interactive console

rdesktop, to connect to a graphical session, if a windows machine allows that (port 3389)

rdesktop -u user -p password 192.168.1.100

Also, we can set the resolution of the remote desktop:

rdesktop -g 1000x600 192.168.1.100


Send GET requests with netcat:

nc -nv 192.168.1.100 8080

(UNKNOWN) [10.11.1.145] 8080 (http-alt) open

GET /workorder/FileDownload.jsp?module=agent&&FILENAME=%20..\..\..\..\..\..\..\..\..\windows\repair\SAM

Host: 192.168.1.100

Connection: close

<enter>

In the guest request we don't pass host IP, that goes in Host. We should receive HTML code if everything went well

In an interactive Python terminal we can do interactively hexadecimal operations, writing all numbers with a format like 0x0bfff7sd. Hexadecimal is understood if the number is preceded by 0x.

If we have access to a very bad shell, which outputs text but we cannot scroll up, we can use sed. For example, to see from line 5 to line 8 of a file:

sed -n 5,8p file


Esto parece importante para jeff, poniendo mtu 900 Cambiar la MTU de una interfaz de red en Linux Para cambiar la MTU (tamaño máximo del paquete) de una interfaz de red en Linux existen dos metodos, el clasico con ifconfig y el que debe substituirlo, el comando ip. Vamos a verlos ambos y como hacer dichos cambios permanentes en sistemas RHEL, CentOS, Fedora y derivados. Para hacer el cambio con ifconfig es tan simple como lo siguiente: # ifconfig eth3 mtu 9000


ifconfig esta en /sbin/ifconfig. Si no funciona, puede que haga falta hacer export PATH=$PATH:/sbin

con nc se puede transmitir binarios al igual que archivos de texto

scp se puede usar para copiar archivos si tenemos cuenta ssh: scp ~/rebels.txt dvader@deathstar.com:~/revenge para copiar una carpeta entera scp -r dvader@deathstar.com:~/revenge ~/revenge mas info en https://kb.iu.edu/d/agye


cron jobs: With "crontab -l" crons are shown. The cron job "run-parts" that sometimes is present means "execute all scripts in the indicated folder", with the frequency given by the first symbols * (or numbers) in the first column of each row. Cron jobs can also be placed in /etc/cron.d and the cron daemon takes them into account and executes them when appropriate. The * symbols indicate once every time unit (minute, hour, day, month, etc). When * is divided by a number, the frequency is divided (for instance */5 in the first column means execute the job once every 5 minutes).

ps auxww is like ps aux, but doesn't crop long lines (sometimes we may miss the name of a process because of this).

When the ps command outputs processes between brackets [ and ], it is because it hasn't found the arguments with which that proces has been run.

If virtualbox stops working and is unable to load virtual machines and the host gets unresponsive to keyboard or mouse, it may be due to having boot the computer with with a kernel different from that which virtualbox is expecting (typically because of a kernel update). The following has worked in ubuntu: dpkg-reconfigure virtualbox-dkms

Or we can boot the host selecting the older kernel.


If for some reason we cannot use cat or other commands to read files and the shell is not interactive, so we cannot use commands such as less, more or vim, we can still use grep: grep '[a-zA-Z0-9]' /etc/passwd


The sticky bit is used for directories permissions, when it is a t insted of an x. When assigned to a directory, it means that the elements in that directory can only be renamed or deleted by the owner of that element, the owner of the directory containing it, or root, even if the group members or others have write permissions. drwxrwxrwt Sticky bit is given to a directory with chmod +x directory

In the passwd file, users with things such as /bin/false or /usr/sbin/nologin, cannot log in to the machine with a shell, so we can rule out these candidate users straight away if we want to perform password attacks, etc.

Not only with a user ID uid=0 are we root. We are also root with euid=0 (effective user ID)

The sudo command can be used to run commands as a certain user, not only root, with the option -u. This can be useful for lateral privilege escalation: sudo -u user1 commmand


If we are going to modify a script called by cron, to add something that helps us with privilege escalation, always save first a copy of the original script, it is easy to screw up and lose the original contents, which may be suspicious. If something gets deleted, it is easy to create the original one.

If we can modify the /etc/sudoers file, after the line which says "root ALL=(ALL) ALL" we can write in a new line "user1 ALL=(ALL) NOPASSWD: ALL", or "ALL ALL=(ALL) NOPASSWD: ALL" so that user1 (or every user) can run every command without a password with sudo privileges.

If a program executes a certain command or script through

/usr/bin/env, it means that it is going to look for that command in the different directories in $PATH. We can create a script, make it executable, call it with the same name as the program that should be legitimally executed, but with our own code and the program will by called by the OS with the privileges that the legit program would have. It happens in exploit exercises' nebula, level 01. We can give to our own program permissions SUID, and add to the PATH the folder where we place it, before any other folder, with:

export PATH=/our_own_folder/:$PATH We would idealy know this call to /usr/bin/env is present in the original script, but we can try it anyway to see if we are lucky, or grep for /usr/bin/env recursively where there are promising files.

If we are trying to open a terminal application which requires colors and we get this error: Error opening terminal: xterm-256color we can fix it with export TERM=xterm This happens in Vulnhub's kioptrix3


To be able to edit files in vim in a remote shell and avoid strange behavior, we need to make sure that both terminals, the remote and the local one, have the same number of rows and columns. We need to do in our kali machine: stty size

It will give us 2 numbers, our rows and columns. Then in the remote shell, from bash, and outside vim, we need to do stty rows x cols y being x and y the two numbers we got in our kali machine.


When we create a symbolic link, we need to specify the whole path to the original file, and to the link, relative paths don't work as expected.

If we have some interactive program running on the terminal, and we want to execute some other program without closing the interactive one, we can send it to the background with ctrl-z, execute what we need on bash, and then bring again the first program to the foreground with fg. Don't be surprised if some running program stops or something when sent to the background.

There may be cron jobs in /var/spool/cron

For Buffer Overflows: if we are passing input to a program when it is running, it is not the same to write it when it is running, and waiting for input, than to export some string (typically fuzzing) with printf or a python print command, and pass that to the program with pipe, for example: python -c "print 'whatever'" | program

This is specially important when passing values in hexadecimal. This happens in exploit exercises' Protostar.


readelf is a command to view information of binary files.


Binary ninja seems like a cool program for debuggin, but it is not free. It creates cool graphs of how some functions relate to others, but something similar can be achieved with radare (Ippsec does this in his Hackthebox's Charon video): r2 supershell aaa afl #analyze function list v # for visualization p # Hitting p several times we cycle through different views (panes) V # Graphic mode. Hitting v we cycle through different functions. g # With the previous we set ourselves in main, and g is "go", it shows the connection of the different functions to this graph. We can get the same as all the previous commands directly with

> s sym.main #and press enter twice

To execute commands from standard input, that is to pass the result of a command as argument to another through a pipe, we need to do it like this: find / -perm -5000 2>/dev/null | xargs ls -la

To set the file creation permission we use a mask: umask 000 This is subtracted from 777 to create the permissions of new files. It is rounded to the lower value.


If we are using wireshark to view some pcap file, we need to be careful to make sure no display filters are being applied, it may be hiding something essential, like happens in Vulnhub's Troll.


ftp puede abrir conexiones a otro puerto de nuestro cliente. se usa port x,x,x,x,x,x, siendo las 4 primeras x la ip nuestra y las dos segundas, el puerto, expresado en 2 bytes hex, de forma que al poner juntos los dos y se convierta, de el puerto en decimal. mirar http://searchenterprisewan.techtarget.com/tip/Understanding-the-FTP-PORT-command. esto aparece en troll, aunque no llega a hacer falta, pero lo que pasa es que al escuchar en el segundo puerto llega ahi el output del comando que se mande al puerto 21, y se cierra el listener

en passwd file, despues de grupo va GECOS en la 5º posicion, es para poner info para identificar o dar mas info de que es ese user. despues va el home directory, y por ultimo la shell. estas cosas se añaden con useradd y distintas opciones, -c, -e, -s (comment, expiration, shell)

epoch: numero de dias desde jan 1 1970, se usa en shadow

groupadd para crear grupos

su -u user1: para shell de como user1

para leer un archivo llamado - hay que usar cat ./-

al crear un user, solo pertenece por defecto a un grupo del mismo nombre que el user

en shadow, si la pass sale como ! es que aun no se ha asignado, acaba de crearse el user

mostrar archivos recursivamente de subdirectorios: ls -laR

decodificar un string en base64: cat xxx.txt | base64 --decode

chgrp es para cambiar el group owner de un archivo (todos los que pertenecen al grupo tienen permisos de grupo). es como chown pero para el grupo

/etc/skel: los contenidos de la carpeta skeleton se copian a las home directory de los usuarios que se crean nuevos

chage -l user: da settings de contraseña del user

passwd -l user: bloquea la pass de la cuenta de user. con passwd -u user se desbloqua. con -e se puede dar fecha de expiracion a la contraseña

groupadd para añadir grupos. se puede añadir nombres de users en /etc/groups al final de la linea correspondiente, separados por coma, y con id se ve que nuestro user ahora esta en otro grupo. tambien se puede usar usermod, pero hay que tener cuidado con las optiones (normalmente -a para append, y añadir users al grupo): usermod -aG account laura

para evitar errores de permission denied al hacer grep para buscar algo como los archivos de cierto tamaño o owner: ls -laR 2>/dev/null | grep bla lo importante es poner lo primero el dev null, si no los errores se transmiten al grep

se puede usar el comando tr para shiftear cada letra de un string por la misma cantidad. por ej, para cambiar cada letra 13 posiciones (como la funcion rot13, que aplicada 2 veces devuelve lo mismo al haber 26 letras): cat data.txt | tr '[A-Za-z]' '[N-ZA-Mn-za-m]' (se indica los dos rangos, el inicial y la correspondecia final de como hay que shiftear)


con shift-av pag o shift re-pag se hace scroll en las tty de linux de solo texto

en el archivo /etc/hosts se hace como DNS de forma local, se asigna ips a dominios. es util en game of thrones, aunque no entiendo bien por que, algo por atras debe estar checkeando que se accede al dominio y no a la IP, buscando por la IP a la carpeta que queremos de winterfell lleva a un decoy

archivo /var/log/auth.log -> contine info de todas las autenticaciones, tipo su, sudo, ssh, etc

xxd -r -p (la p no entiendo bien que hace, pero para com80 de vulnhub hizo falta) sirve para convertir un hexdump en binario. ojo, no poder ejecutar el binario (porque falten librerias, etc), no quiere decir que no podamos ver que strings hay dentro, etc. para poder hacer xxd hay que haber quitado los numeros de lineas en la primera columna, y el ascii dump, y cualquier posible cabecera. puede que el hexdump original de ascii distintos que el hexdump al binario recuperado con xxd. para recuperar un hexdump de 8 columnas para pasar a xxd: cat a.hex | awk -F " " '{print $2 $3 $4 $5 $6 $7 $8 $9}' > b.txt; xxd -r -p b.txt > c.exe

strace: para seguir la pista a como se hace llamadas al sistema

binwalk tambien vale para ver cosas ocultas o ejecutables en un binario. en nineveh ippsec hace binwalk -Me nineveh.png para extraer cosas que forman parte de una imagen

privesc con wildcards: algunos archivos a los que se puede pasar wildcards pueden ser engañados, creando archivos con nombres que realmente se interpretan como argumentos para los comandos. mirar articulo: https://www.defensecode.com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt

si podemos ejecutar comandos individuales como otro user con sudo -l user, se puede crear un python pty y ejecutarlo como ese user para tener shell completa

si hay algun cron que ejecuta scripts, asegurarnos de que esta con chmod +x lo que queramos que se ejecute, como en bashed de hackthebox

para ejecutar comandos como otro user: sudo -u user1 comando. Para ejecutar una shell como ese otro user: sudo -u user1 bash. Esto se usa en bashed de hackthebox

si en kvm, para instalar xp por ejemplo, pide un archivo del disco a mita de la instalacion, en vista>detalles y en cdrom buscar la iso, con eso ya se entero y siguio la instlacion ok