I've written a script to decrypt old passwords and accounts that I can't access because I can't access my old email (again because I can't remember the passwords haha).
import os
import sqlite3
import win32crypt
import sys
try:
path = sys.argv[1]
except IndexError:
for w in os.walk(os.getenv('USERPROFILE')):
if 'Chrome' in w[1]:
path = str(w[0]) + '/Chrome/User Data/Default/Login Data'
try:
print ('[+] Opening ' + path)
conn = sqlite3.connect(path)
cursor = conn.cursor()
except Exception as e:
print ('[-] %s' % (e))
sys.exit(1)
# Get the results
try:
cursor.execute('SELECT action_url, username_value, password_value FROM logins')
except Exception as e:
print ('[-] %s' % (e))
sys.exit(1)
data = cursor.fetchall()
Everything is fine up to here.
for result in data:
try:
password = win32crypt.CryptUnprotectData(result[2], None)
except Exception as e:
print('[-] %s' % (e))
pass
if password:
print("[+] URL: {} Username: {} Password: {}".format(result[0], result[1], password))
else: print("Unable to extract data")
I get this error: (-2146893813, 'CryptProtectData', 'Key not valid for use in specified state.')
Thanks to gilliduck for pointing out my typo!
I believe it's
CryptUnprotectData
not
CryptUnprotectEDData
Related
servlet2.py
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try:
connection = mysql.connector.connect(host='localhost',
database='*project',
user='*****',
password='*****',
)
print("Connection Established")
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print('Somethign is wrong with username or password')
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print('Database does not exist')
else:
print(e)
c = connection.cursor()
def insertSQL(user):
mySql_insert_query = "INSERT INTO python_project.test (Name) VALUES (?)", (user)
print("user:", user)
c.execute(mySql_insert_query)
print(c.rowcount, "Record inserted successfully into test table")
def username():
user = input("Please Enter Your Name: " )
insertSQL(user)
test_script.py
import servlet2
servlet2.username()
I was able to established connection to the database, however, once I enter name. It will fail to connect and prompt this error.
OperationalError: Lost connection to MySQL server at 'localhost:3306', system error: Connection not available.
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try:
connection = mysql.connector.connect(host='127.0.0.1',
database='python_project',
user='root',
password='catdog123',
)
print("Connection Established")
#cursor = connection.cursor()
#cursor.execute("""INSERT INTO test (Name) VALUES ('harry')""")
#connection.commit()
#cursor.close()
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print('Somethign is wrong with username or password')
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print('Database does not exist')
else:
print(e)
c = connection.cursor()
def insertSQL(user):
#mySql_insert_query = """INSERT INTO test (Name) VALUES (?)""", user
print("user:", user)
print(c.rowcount, "Record inserted successfully into test table")
c.execute("""INSERT INTO test (Name) VALUES ('{}')""".format(user))
connection.commit()
def username():
user = input("Please Enter Your Name:" )
insertSQL(user)
I manage to solve it by changing the insert statement VALUES to ('{}').format(user)
Hi there I have the following python code to connect to my SQL-Server DB
class CDBTools:
details = {
'server' : 'localhost',
'database' : 'MyDB',
'username' : 'me',
'password' : 'myPass'
}
conn = None
def __init__(self, server, database, username, password):
self.details["server"] = server
self.details["database"] = database
self.details["username"] = username
self.details["password"] = password
def connect_to_db(self):
connect_string = 'DRIVER={{FreeTDS}};SERVER={server}; DATABASE={database};UID={username};PWD={password}'.format(**self.details)
try:
self.conn = pyodbc.connect(connect_string, autocommit=True)
#print(connect_string)
#Logger.Log(self.conn, "info")
except pyodbc.Error as e:
print(e, "error")
def execute_select_query(self, query):
try:
curr = self.conn.cursor()
out = curr.execute(query).fetchall()
except pyodbc.IntegrityError as e:
out = []
print('ms-sql error: {0}'.format(e))
except pyodbc.OperationalError as err: #Something happend with db, so try again
out = []
print('ms-sql Operation Error: {0}'.format(err))
except AttributeError as err:
out = []
print('Connection to DB failed')
pass
try:
curr.close()
except:
print('Connection to DB failed')
return out
def execute_inset_query(self, query):
try:
database_cursor = self.conn.cursor()
database_cursor.execute(query)
except pyodbc.DataError as e:
print('ms-sql error: {0}'.format(e))
except pyodbc.IntegrityError as e:
print('ms-sql error: {0}'.format(e))
except pyodbc.OperationalError as err: #Something happend with db, so try again
print('ms-sql error: {0}'.format(e))
then in my main program I am trying this and it works just fine, until I disconnect the network
DBT = CDBTools("192.168.1.2\instance4", "my_db", "my_username", "my_passowrd")
DBT.connect_to_db()
while(True):
print("[{0}]: {1}".format(time.strftime("%H:%M:%S"), DBT.execute_select_query("SELECT Name FROM Persons WHERE ID='1'")))
When I disconnect the network I get no error, just time doesn't count anymore (of course because query is failing) but when I reconnect the network query never sucseeds anymore
so does anyone maybe know how I can modify execute_select_query and execute_inset_query so when connection to the db is restored it will start to work again :)
Thanks for Anwsering and Best Regards
Try this, it'll connect each time you use the with clause, and automatically disconnect when you leave it.
class CDBTools:
details = {
'server' : 'localhost',
'database' : 'MyDB',
'username' : 'me',
'password' : 'myPass'
}
conn = None
def __init__(self, server, database, username, password):
self.details["server"] = server
self.details["database"] = database
self.details["username"] = username
self.details["password"] = password
def connect_to_db(self):
connect_string = 'DRIVER={{FreeTDS}};SERVER={server}; DATABASE={database};UID={username};PWD={password}'.format(**self.details)
try:
conn = pyodbc.connect(connect_string, autocommit=True)
#print(connect_string)
#Logger.Log(self.conn, "info")
except pyodbc.Error as e:
print(e, "error")
return conn
def execute_select_query(self, conn, query):
try:
curr = conn.cursor()
out = curr.execute(query).fetchall()
except pyodbc.IntegrityError as e:
out = []
print('ms-sql error: {0}'.format(e))
except pyodbc.OperationalError as err: #Something happend with db, so try again
out = []
print('ms-sql Operation Error: {0}'.format(err))
except AttributeError as err:
out = []
print('Connection to DB failed')
pass
def execute_inset_query(self, conn, query):
try:
database_cursor = conn.cursor()
database_cursor.execute(query)
except pyodbc.DataError as e:
print('ms-sql error: {0}'.format(e))
except pyodbc.IntegrityError as e:
print('ms-sql error: {0}'.format(e))
except pyodbc.OperationalError as err: #Something happend with db, so try again
print('ms-sql error: {0}'.format(e))
then:
DBT = CDBTools("192.168.1.2\instance4", "my_db", "my_username", "my_passowrd")
while True:
with DBT.connect_to_db() as conn:
print("[{0}]: {1}".format(time.strftime("%H:%M:%S"), DBT.execute_select_query(conn, "SELECT Name FROM Persons WHERE ID='1'")))
I'd probably make a method to return the cursor rather than the connection. For example:
class CDBTools:
details = {
'server' : 'localhost',
'database' : 'MyDB',
'username' : 'me',
'password' : 'myPass'
}
conn = None
def __init__(self, server, database, username, password):
self.details["server"] = server
self.details["database"] = database
self.details["username"] = username
self.details["password"] = password
def get_cursor(self):
connect_string = 'DRIVER={{FreeTDS}};SERVER={server}; DATABASE={database};UID={username};PWD={password}'.format(**self.details)
try:
conn = pyodbc.connect(connect_string, autocommit=True)
#print(connect_string)
#Logger.Log(self.conn, "info")
except pyodbc.Error as e:
print(e, "error")
return conn.cursor()
DBT = CDBTools("192.168.1.2\instance4", "my_db", "my_username", "my_passowrd")
with DBT.get_cursor() as cursor:
cursor.execute("SELECT Name FROM Persons WHERE ID='1'")
for row in cursor.fetchall():
print(row)
Good luck!
I have a function I'm trying to execute which calls in 4 different variables:
def listdbtables(dbname, user, host, password):
try:
conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" % dbname, % user, % host, % password)
curs = conn.cursor()
b = curs.execute("\l")
print b
except psycopg2.DatabaseError, ex:
print "I am unable to connect the database: " + ex
sys.exit(1)
I am unable to read in the variables with my current setup, how do I call in the variables properly in the conn variables.
Edit: Here is the error I am seeing:
File "./pg_meta.py", line 35
conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" (% dbname, % user, % host, % password))
^
SyntaxError: invalid syntax
try this:
def listdbtables(dbname, user, host, password):
try:
conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" % (dbname, user, host,password,))
curs = conn.cursor()
b = curs.execute("\l")
print b
except psycopg2.DatabaseError, ex:
print "I am unable to connect the database: " + ex
sys.exit(1)
the format portion needs to be a tuple for multiple values. you should also consider using String.format
I think this is wrong syntax:
conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" % dbname, % user, % host, % password)
Change it to:
conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" %(dbname, user, host, password))
another way it to use .format():
conn = psycopg2.connect("dbname = {0} username = {1} host = {2} pass = {3}".format(dbname, user, host, password))
Your error is saying that you have incorrect syntax in your program. When using the % operator with multiple variables Python requires you to use parenthesis. Change your code to this instead:
conn = psycopg2.connect("dbname = %s username = %s host = %s pass = %s" % (dbname, % user, % host, % password))
However, the recommend way to format variables into strings in newer Python versions would be to use the .format() method, instead of old style string formatting with %:
conn = psycopg2.connect("dbname = {} username = {} host = {} pass = {}".format(
dbname, user, host, password)
)
Both methods have their advantageous and disadvantageous, so I encourage you to find which one works best for you. A good website to compare the two methods is pyformat.info.
I am running into an issue with parts of my code i have added my errors at the bottom. The issue is arising around the sqllite3.operationError part. i attempted removing it but when i do another error occurs for line 68 'def getpath():', i cant see why the errors are showing up any and all help is appreciated as always thanks. My code is generally for taking Login data out of my database and displaying in an csv file
import os
import sys
import sqlite3
try:
import win32crypt
except:
pass
import argparse
def args_parser():
parser = argparse.ArgumentParser(description="Retrieve Google Chrome Passwords")
parser.add_argument("--output", help="Output to csv file", action="store_true")
args = parser.parse_args()
if args.output:
csv(main())
else:
for data in main():
print (data)
def main():
info_list = []
path = getpath()
try:
connection = sqlite3.connect(path + "Login Data")
with connection:
cursor = connection.cursor()
v = cursor.execute('SELECT action_url, username_value, password_value FROM logins')
value = v.fetchall
for information in value:
if os.name == 'nt':
password = win32crypt.CryptUnprotectData(information[2], None, None, None, 0)[1]
if password:
info_list.append({
'origin_url': information[0],
'username': information[1],
'password': str(password)
})
except sqlite3.OperationalError as e:
e = str(e)
if (e == 'database is locked'):
print('[!] Make sure Google Chrome is not running in the background')
sys.exit(0)
elif (e == 'no such table: logins'):
print('[!] Something wrong with the database name')
sys.exit(0)
elif (e == 'unable to open database file'):
print('[!] Something wrong with the database path')
sys.exit(0)
else:
print (e)
sys.exit(0)
return info_list
def getpath():
if os.name == "nt":
# This is the Windows Path
PathName = os.getenv('localappdata') + '\\Google\\Chrome\\User Data\\Default\\'
if (os.path.isdir(PathName) == False):
print('[!] Chrome Doesn\'t exists')
sys.exit(0)
return PathName
def csv (info):
with open ('chromepass.csv', 'wb') as csv_file:
csv_file.write('origin_url,username,password \n' .encode('utf'))
for data in info:
csv_file.write(('%s, %s, %s \n' % (data['origin_url'], data['username'], data['password'])).encode('utf-8'))
print ("Data written to Chromepass.csv")
if __name__ == '__main__':
args_parser()
Errors
Traceback (most recent call last):
File "C:/Users/Lewis Collins/Python Project/ChromeDB's/ChromeSessionParser.py", line 90, in <module>
args_parser()
File "C:/Users/Lewis Collins/Python Project/ChromeDB's/ChromeSessionParser.py", line 19, in args_parser
for data in main():
File "C:/Users/Lewis Collins/Python Project/ChromeDB's/ChromeSessionParser.py", line 35, in main
for information in value:
TypeError: 'builtin_function_or_method' object is not iterable
Right way is:
except sqlite3.OperationalError as e:
And you main() should be like:
def main():
info_list = []
path = getpath()
try:
connection = sqlite3.connect(path + "Login Data")
with connection:
cursor = connection.cursor()
v = cursor.execute('SELECT action_url, username_value, password_value FROM logins')
value = v.fetchall
for information in value:
if os.name == 'nt':
password = win32crypt.CryptUnprotectData(information[2], None, None, None, 0)[1]
if password:
info_list.append({
'origin_url': information[0],
'username': information[1],
'password': str(password)
})
except sqlite3.OperationalError as e:
e = str(e)
if (e == 'database is locked'):
print '[!] Make sure Google Chrome is not running in the background'
sys.exit(0)
elif (e == 'no such table: logins'):
print '[!] Something wrong with the database name'
sys.exit(0)
elif (e == 'unable to open database file'):
print '[!] Something wrong with the database path'
sys.exit(0)
else:
print e
sys.exit(0)
return info_list
I am running a simple python script to log the accessed url using squid url_rewriter_program.
However every time it runs, rewriter crashes with broken pipe error at sys.stdout.flush().
Please suggest a specific solution.
python code is:
import sys
import os
import io
line = sys.stdin.readline()
fo=open("/home/linux/Desktop/foo1.txt","a")
fo.write(line)
fo.close()
sys.stdout.write("\n")
sys.stdout.flush()
This is a squid redirector file, written on python, can you get, or compare with your script:
Redirector:
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#-----------------------------------------------------------------------------
# Name: redirector_master.py
# Purpose: SiSCont checker cuote
#
# Author: Ernesto Licea Martin
#
# Created: 2011/11/24
# RCS-ID: $Id: redirector_master.py $
# Copyright: (c) 2011
# Licence: GPL
#-----------------------------------------------------------------------------
import sys, string, libSiSCont
__name__= "redirector_master"
query="SELECT accounts_proxyquotatype.name, accounts_proxyaccount.proxy_quota, accounts_proxyaccount.proxy_quota_extra, accounts_proxyaccount.proxy_active, accounts_proxyaccounttype.name FROM accounts_proxyaccount INNER JOIN accounts_proxyaccounttype INNER JOIN accounts_proxyquotatype ON (accounts_proxyaccount.proxy_quota_type_id = accounts_proxyquotatype.id) AND (accounts_proxyaccount.proxy_account_type_id = accounts_proxyaccounttype.id) WHERE accounts_proxyaccount.proxy_username=%s"
class RedirMaster:
def __init__(self):
obj = libSiSCont.ParceConf()
obj.parcecfgfile()
self.__listModules = obj.getModList()
self.__redirDicc = obj.getRedirectURL()
self.__penalURL = obj.getPenalizedURL()
self.__confDicc = obj.getConfParam()
self.__dbDicc = obj.getDBDicc()
self.__proxyDicc = obj.getProxyCacheParam()
self.__dbParam = []
def getProxyTypes(self):
db=libSiSCont.connectDB(dbDicc=self.__dbDicc)
c=db.cursor()
c.execute("SELECT accounts_proxy")
def run(self):
modules=[]
for mod in self.__listModules:
try:
m=__import__(mod)
modules.append(m)
except Exception, e:
libSiSCont.reportLogs("%s.run" %__name__, 'Unable to load redirector module %s; the error was: %s' % (mod,str(e)))
if len(modules) == 0:
libSiSCont.reportLogs("%s.run" %__name__, 'No usable redirector module found; switching to trasparent behavour')
while 1:
try:
data_redir=raw_input()
data_redir=data_redir.split()
url,ip_host,user,method,urlgroup = data_redir[0:5]
ip=ip_host.split("/")[0]
host_name=ip_host.split("/")[1]
uri = url
mode=""
#Don't check cache access
if string.find(url,"cache_object") == 0:
sys.stdout.write("%s%s\n" %(mode,uri))
sys.stdout.flush()
continue
db=libSiSCont.connectDB(dbDicc=self.__dbDicc)
c=db.cursor()
c.execute(query,user)
cuote_type,cuote, ext_cuote, active, acc_type = c.fetchall()[0]
self.__dbParam=[cuote_type,int(cuote), int(ext_cuote), active, acc_type]
for module in modules:
try:
uri = module.redir(url = url, ip = ip, host_name = host_name, user = user, method = method, urlgroup = urlgroup, redirDicc = self.__redirDicc, penalURL = self.__penalURL, confDicc = self.__confDicc, proxyDicc = self.__proxyDicc, dbParam = self.__dbParam)
except Exception, e:
libSiSCont.reportLogs("%s.run" %__name__, 'Error while running module: %s -- The error was: %s' % (module,str(e)))
if uri != url:
mode = "301:"
break
sys.stdout.write("%s%s\n" %(mode,uri))
sys.stdout.flush()
except Exception, e:
if not string.find('%s' % e,'EOF') >= 0:
sys.stdout.write('%s\n' % uri)
sys.stdout.flush()
libSiSCont.reportLogs("%s.run" %__name__, '%s: data received from parent: %s' % (str(e),string.join(data_redir)))
else:
sys.exit()
obj=RedirMaster()
obj.run()
Helper:
#!/usr/bin/env python
import sys, syslog, libSiSCont, string,crypt
__name__ = "Helper"
query = "SELECT accounts_proxyaccount.proxy_username FROM accounts_proxyaccount WHERE accounts_proxyaccount.proxy_username=%s AND accounts_proxyaccount.proxy_password=%s"
class BasicAuth:
def __init__(self):
obj = libSiSCont.ParceConf()
obj.parcecfgfile()
self.__dbDicc = obj.getDBDicc()
def run(self):
while 1:
try:
user_pass = string.split(raw_input())
user = user_pass[0].strip("\n")
passwd = user_pass[1].strip("\n")
crypt_passwd = crypt.crypt(passwd,user)
db = libSiSCont.connectDB(self.__dbDicc)
c = db.cursor()
c.execute(query,(user,crypt_passwd))
if c.fetchone() == None:
libSiSCont.reportLogs('%s.run' %__name__,'User Authentication Fail, user = %s password= %s, Access Denied' %(user,passwd) )
sys.stdout.write("ERR\n")
sys.stdout.flush()
else:
libSiSCont.reportLogs('%s.run' %__name__, 'User Authentication Success, user = %s, Access Granted' %user)
sys.stdout.write("OK\n")
sys.stdout.flush()
except Exception, e:
if not string.find("%s" %e, "EOF") >= 0:
sys.stdout.write("ERR\n")
sys.stdout.flush()
libSiSCont.reportLogs('%s.run' %__name__, 'Authenticator error, user will navigate without authentication: %s' %str(e))
else:
sys.exit()
obj = BasicAuth()
obj.run()
I hope help you ;-)