Parameterize all queries, format queries

This commit is contained in:
Arinerron 2018-11-09 22:29:32 -08:00
parent d5355fdc9e
commit 5aaf0f266a
No known key found for this signature in database
GPG Key ID: 99383627861C62F0
5 changed files with 40 additions and 40 deletions

View File

@ -132,7 +132,7 @@ class Core:
c = conn.cursor() c = conn.cursor()
t = (peerID, name, 'unknown', hashID, powID, 0) t = (peerID, name, 'unknown', hashID, powID, 0)
for i in c.execute("SELECT * FROM PEERS where id = ?;", (peerID,)): for i in c.execute("SELECT * FROM peers WHERE id = ?;", (peerID,)):
try: try:
if i[0] == peerID: if i[0] == peerID:
conn.close() conn.close()
@ -160,7 +160,7 @@ class Core:
# check if address is in database # check if address is in database
# this is safe to do because the address is validated above, but we strip some chars here too just in case # this is safe to do because the address is validated above, but we strip some chars here too just in case
address = address.replace('\'', '').replace(';', '').replace('"', '').replace('\\', '') address = address.replace('\'', '').replace(';', '').replace('"', '').replace('\\', '')
for i in c.execute("SELECT * FROM adders where address = ?;", (address,)): for i in c.execute("SELECT * FROM adders WHERE address = ?;", (address,)):
try: try:
if i[0] == address: if i[0] == address:
conn.close() conn.close()
@ -428,13 +428,13 @@ class Core:
return return
if randomOrder: if randomOrder:
payload = 'SELECT * FROM peers where trust >= %s ORDER BY RANDOM();' % (trust,) payload = 'SELECT * FROM peers WHERE trust >= ? ORDER BY RANDOM();'
else: else:
payload = 'SELECT * FROM peers where trust >= %s;' % (trust,) payload = 'SELECT * FROM peers WHERE trust >= ?;'
peerList = [] peerList = []
for i in c.execute(payload): for i in c.execute(payload, (trust,)):
try: try:
if len(i[0]) != 0: if len(i[0]) != 0:
if getPow: if getPow:
@ -480,7 +480,7 @@ class Core:
iterCount = 0 iterCount = 0
retVal = '' retVal = ''
for row in c.execute('SELECT * from peers where id=?;', command): for row in c.execute('SELECT * FROM peers WHERE id=?;', command):
for i in row: for i in row:
if iterCount == info: if iterCount == info:
retVal = i retVal = i
@ -631,10 +631,10 @@ class Core:
c = conn.cursor() c = conn.cursor()
date = int(self._utils.getEpoch()) date = int(self._utils.getEpoch())
execute = 'SELECT hash FROM hashes WHERE expire <= %s ORDER BY dateReceived;' % (date,) execute = 'SELECT hash FROM hashes WHERE expire <= ? ORDER BY dateReceived;'
rows = list() rows = list()
for row in c.execute(execute): for row in c.execute(execute, (date,)):
for i in row: for i in row:
rows.append(i) rows.append(i)
return rows return rows

View File

@ -22,11 +22,11 @@ class OnionrBlackList:
def __init__(self, coreInst): def __init__(self, coreInst):
self.blacklistDB = coreInst.dataDir + 'blacklist.db' self.blacklistDB = coreInst.dataDir + 'blacklist.db'
self._core = coreInst self._core = coreInst
if not os.path.exists(self.blacklistDB): if not os.path.exists(self.blacklistDB):
self.generateDB() self.generateDB()
return return
def inBlacklist(self, data): def inBlacklist(self, data):
hashed = self._core._utils.bytesToStr(self._core._crypto.sha3Hash(data)) hashed = self._core._utils.bytesToStr(self._core._crypto.sha3Hash(data))
retData = False retData = False
@ -34,22 +34,22 @@ class OnionrBlackList:
raise Exception("Hashed data is not alpha numeric") raise Exception("Hashed data is not alpha numeric")
if len(hashed) > 64: if len(hashed) > 64:
raise Exception("Hashed data is too large") raise Exception("Hashed data is too large")
for i in self._dbExecute("select * from blacklist where hash='%s'" % (hashed,)): for i in self._dbExecute("SELECT * FROM blacklist WHERE hash = ?", (hashed,)):
retData = True # this only executes if an entry is present by that hash retData = True # this only executes if an entry is present by that hash
break break
return retData return retData
def _dbExecute(self, toExec): def _dbExecute(self, toExec, params = ()):
conn = sqlite3.connect(self.blacklistDB) conn = sqlite3.connect(self.blacklistDB)
c = conn.cursor() c = conn.cursor()
retData = c.execute(toExec) retData = c.execute(toExec, params)
conn.commit() conn.commit()
return retData return retData
def deleteBeforeDate(self, date): def deleteBeforeDate(self, date):
# TODO, delete blacklist entries before date # TODO, delete blacklist entries before date
return return
def deleteExpired(self, dataType=0): def deleteExpired(self, dataType=0):
'''Delete expired entries''' '''Delete expired entries'''
deleteList = [] deleteList = []
@ -60,13 +60,13 @@ class OnionrBlackList:
except AttributeError: except AttributeError:
raise TypeError("dataType must be int") raise TypeError("dataType must be int")
for i in self._dbExecute('select * from blacklist where dataType=%s' % (dataType,)): for i in self._dbExecute('SELECT * FROM blacklist WHERE dataType = ?', (dataType,)):
if i[1] == dataType: if i[1] == dataType:
if (curTime - i[2]) >= i[3]: if (curTime - i[2]) >= i[3]:
deleteList.append(i[0]) deleteList.append(i[0])
for thing in deleteList: for thing in deleteList:
self._dbExecute("delete from blacklist where hash='%s'" % (thing,)) self._dbExecute("DELETE FROM blacklist WHERE hash = ?", (thing,))
def generateDB(self): def generateDB(self):
self._dbExecute('''CREATE TABLE blacklist( self._dbExecute('''CREATE TABLE blacklist(
@ -77,12 +77,12 @@ class OnionrBlackList:
); );
''') ''')
return return
def clearDB(self): def clearDB(self):
self._dbExecute('''delete from blacklist;);''') self._dbExecute('''DELETE FROM blacklist;);''')
def getList(self): def getList(self):
data = self._dbExecute('select * from blacklist') data = self._dbExecute('SELECT * FROM blacklist')
myList = [] myList = []
for i in data: for i in data:
myList.append(i[0]) myList.append(i[0])
@ -113,4 +113,4 @@ class OnionrBlackList:
return return
insert = (hashed,) insert = (hashed,)
blacklistDate = self._core._utils.getEpoch() blacklistDate = self._core._utils.getEpoch()
self._dbExecute("insert into blacklist (hash, dataType, blacklistDate, expire) VALUES('%s', %s, %s, %s);" % (hashed, dataType, blacklistDate, expire)) self._dbExecute("INSERT INTO blacklist (hash, dataType, blacklistDate, expire) VALUES(?, ?, ?, ?);", (str(hashed), dataType, blacklistDate, expire))

View File

@ -78,7 +78,7 @@ class DaemonTools:
for bHash in self.daemon._core.getExpiredBlocks(): for bHash in self.daemon._core.getExpiredBlocks():
self.daemon._core._blacklist.addToDB(bHash) self.daemon._core._blacklist.addToDB(bHash)
self.daemon._core.removeBlock(bHash) self.daemon._core.removeBlock(bHash)
self.daemon.decrementThreadCount('cleanOldBlocks') self.daemon.decrementThreadCount('cleanOldBlocks')
def cleanKeys(self): def cleanKeys(self):
@ -87,7 +87,7 @@ class DaemonTools:
c = conn.cursor() c = conn.cursor()
time = self.daemon._core._utils.getEpoch() time = self.daemon._core._utils.getEpoch()
deleteKeys = [] deleteKeys = []
for entry in c.execute("SELECT * FROM forwardKeys where expire <= ?", (time,)): for entry in c.execute("SELECT * FROM forwardKeys WHERE expire <= ?", (time,)):
logger.info(entry[1]) logger.info(entry[1])
deleteKeys.append(entry[1]) deleteKeys.append(entry[1])

View File

@ -40,7 +40,7 @@ class OnionrUser:
self.trust = self._core.getPeerInfo(self.publicKey, 'trust') self.trust = self._core.getPeerInfo(self.publicKey, 'trust')
return return
def setTrust(self, newTrust): def setTrust(self, newTrust):
'''Set the peers trust. 0 = not trusted, 1 = friend, 2 = ultimate''' '''Set the peers trust. 0 = not trusted, 1 = friend, 2 = ultimate'''
self._core.setPeerInfo(self.publicKey, 'trust', newTrust) self._core.setPeerInfo(self.publicKey, 'trust', newTrust)
@ -49,7 +49,7 @@ class OnionrUser:
if self._core.getPeerInfo(self.publicKey, 'trust') == 1: if self._core.getPeerInfo(self.publicKey, 'trust') == 1:
return True return True
return False return False
def getName(self): def getName(self):
retData = 'anonymous' retData = 'anonymous'
name = self._core.getPeerInfo(self.publicKey, 'name') name = self._core.getPeerInfo(self.publicKey, 'name')
@ -63,11 +63,11 @@ class OnionrUser:
def encrypt(self, data): def encrypt(self, data):
encrypted = coreInst._crypto.pubKeyEncrypt(data, self.publicKey, encodedData=True) encrypted = coreInst._crypto.pubKeyEncrypt(data, self.publicKey, encodedData=True)
return encrypted return encrypted
def decrypt(self, data, anonymous=True): def decrypt(self, data, anonymous=True):
decrypted = coreInst._crypto.pubKeyDecrypt(data, self.publicKey, encodedData=True) decrypted = coreInst._crypto.pubKeyDecrypt(data, self.publicKey, encodedData=True)
return decrypted return decrypted
def forwardEncrypt(self, data): def forwardEncrypt(self, data):
retData = '' retData = ''
forwardKey = self._getLatestForwardKey() forwardKey = self._getLatestForwardKey()
@ -78,7 +78,7 @@ class OnionrUser:
raise onionrexceptions.InvalidPubkey("No valid forward key available for this user") raise onionrexceptions.InvalidPubkey("No valid forward key available for this user")
#self.generateForwardKey() #self.generateForwardKey()
return (retData, forwardKey) return (retData, forwardKey)
def forwardDecrypt(self, encrypted): def forwardDecrypt(self, encrypted):
retData = "" retData = ""
#logger.error(self.publicKey) #logger.error(self.publicKey)
@ -101,19 +101,19 @@ class OnionrUser:
conn = sqlite3.connect(self._core.peerDB, timeout=10) conn = sqlite3.connect(self._core.peerDB, timeout=10)
c = conn.cursor() c = conn.cursor()
for row in c.execute("SELECT forwardKey FROM forwardKeys WHERE peerKey = ? order by date desc", (self.publicKey,)): for row in c.execute("SELECT forwardKey FROM forwardKeys WHERE peerKey = ? ORDER BY date DESC", (self.publicKey,)):
key = row[0] key = row[0]
break break
conn.commit() conn.commit()
conn.close() conn.close()
return key return key
def _getForwardKeys(self): def _getForwardKeys(self):
conn = sqlite3.connect(self._core.peerDB, timeout=10) conn = sqlite3.connect(self._core.peerDB, timeout=10)
c = conn.cursor() c = conn.cursor()
keyList = [] keyList = []
for row in c.execute("SELECT forwardKey FROM forwardKeys WHERE peerKey = ? order by date desc", (self.publicKey,)): for row in c.execute("SELECT forwardKey FROM forwardKeys WHERE peerKey = ? ORDER BY date DESC", (self.publicKey,)):
key = row[0] key = row[0]
keyList.append(key) keyList.append(key)
@ -150,7 +150,7 @@ class OnionrUser:
pubkey = self._core._utils.bytesToStr(pubkey) pubkey = self._core._utils.bytesToStr(pubkey)
command = (pubkey,) command = (pubkey,)
keyList = [] # list of tuples containing pub, private for peer keyList = [] # list of tuples containing pub, private for peer
for result in c.execute("SELECT * FROM myForwardKeys where peer=?", command): for result in c.execute("SELECT * FROM myForwardKeys WHERE peer=?", command):
keyList.append((result[1], result[2])) keyList.append((result[1], result[2]))
if len(keyList) == 0: if len(keyList) == 0:
if genNew: if genNew:
@ -173,7 +173,7 @@ class OnionrUser:
conn.commit() conn.commit()
conn.close() conn.close()
return return
def findAndSetID(self): def findAndSetID(self):
'''Find any info about the user from existing blocks and cache it to their DB entry''' '''Find any info about the user from existing blocks and cache it to their DB entry'''
infoBlocks = [] infoBlocks = []
@ -186,4 +186,4 @@ class OnionrUser:
logger.info('%s is now using the name %s.' % (self.publicKey, self._core._utils.escapeAnsi(newName))) logger.info('%s is now using the name %s.' % (self.publicKey, self._core._utils.escapeAnsi(newName)))
self._core.setPeerInfo(self.publicKey, 'name', newName) self._core.setPeerInfo(self.publicKey, 'name', newName)
else: else:
raise onionrexceptions.InvalidPubkey raise onionrexceptions.InvalidPubkey

View File

@ -276,7 +276,7 @@ class OnionrUtils:
else: else:
logger.warn('FS not used for this encrypted block') logger.warn('FS not used for this encrypted block')
logger.info(myBlock.bmetadata) logger.info(myBlock.bmetadata)
try: try:
if len(blockType) <= 10: if len(blockType) <= 10:
self._core.updateBlockInfo(blockHash, 'dataType', blockType) self._core.updateBlockInfo(blockHash, 'dataType', blockType)
@ -328,7 +328,7 @@ class OnionrUtils:
c = conn.cursor() c = conn.cursor()
if not self.validateHash(hash): if not self.validateHash(hash):
raise Exception("Invalid hash") raise Exception("Invalid hash")
for result in c.execute("SELECT COUNT() FROM hashes where hash='" + hash + "'"): for result in c.execute("SELECT COUNT() FROM hashes WHERE hash = ?", (hash,)):
if result[0] >= 1: if result[0] >= 1:
conn.commit() conn.commit()
conn.close() conn.close()
@ -402,7 +402,7 @@ class OnionrUtils:
logger.warn('Block is expired') logger.warn('Block is expired')
break break
else: else:
# if metadata loop gets no errors, it does not break, therefore metadata is valid # if metadata loop gets no errors, it does not break, therefore metadata is valid
# make sure we do not have another block with the same data content (prevent data duplication and replay attacks) # make sure we do not have another block with the same data content (prevent data duplication and replay attacks)
nonce = self._core._utils.bytesToStr(self._core._crypto.sha3Hash(blockData)) nonce = self._core._utils.bytesToStr(self._core._crypto.sha3Hash(blockData))
try: try:
@ -488,7 +488,7 @@ class OnionrUtils:
retVal = False retVal = False
if not idNoDomain.isalnum(): if not idNoDomain.isalnum():
retVal = False retVal = False
# Validate address is valid base32 (when capitalized and minus extension); v2/v3 onions and .b32.i2p use base32 # Validate address is valid base32 (when capitalized and minus extension); v2/v3 onions and .b32.i2p use base32
try: try:
base64.b32decode(idNoDomain.upper().encode()) base64.b32decode(idNoDomain.upper().encode())
@ -510,7 +510,7 @@ class OnionrUtils:
c = conn.cursor() c = conn.cursor()
command = (hash,) command = (hash,)
retData = '' retData = ''
for row in c.execute('SELECT ID FROM peers where hashID=?', command): for row in c.execute('SELECT id FROM peers WHERE hashID = ?', command):
if row[0] != '': if row[0] != '':
retData = row[0] retData = row[0]
return retData return retData