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()
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:
if i[0] == peerID:
conn.close()
@ -160,7 +160,7 @@ class Core:
# 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
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:
if i[0] == address:
conn.close()
@ -428,13 +428,13 @@ class Core:
return
if randomOrder:
payload = 'SELECT * FROM peers where trust >= %s ORDER BY RANDOM();' % (trust,)
payload = 'SELECT * FROM peers WHERE trust >= ? ORDER BY RANDOM();'
else:
payload = 'SELECT * FROM peers where trust >= %s;' % (trust,)
payload = 'SELECT * FROM peers WHERE trust >= ?;'
peerList = []
for i in c.execute(payload):
for i in c.execute(payload, (trust,)):
try:
if len(i[0]) != 0:
if getPow:
@ -480,7 +480,7 @@ class Core:
iterCount = 0
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:
if iterCount == info:
retVal = i
@ -631,10 +631,10 @@ class Core:
c = conn.cursor()
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()
for row in c.execute(execute):
for row in c.execute(execute, (date,)):
for i in row:
rows.append(i)
return rows

View File

@ -22,11 +22,11 @@ class OnionrBlackList:
def __init__(self, coreInst):
self.blacklistDB = coreInst.dataDir + 'blacklist.db'
self._core = coreInst
if not os.path.exists(self.blacklistDB):
self.generateDB()
return
def inBlacklist(self, data):
hashed = self._core._utils.bytesToStr(self._core._crypto.sha3Hash(data))
retData = False
@ -34,22 +34,22 @@ class OnionrBlackList:
raise Exception("Hashed data is not alpha numeric")
if len(hashed) > 64:
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
break
return retData
def _dbExecute(self, toExec):
def _dbExecute(self, toExec, params = ()):
conn = sqlite3.connect(self.blacklistDB)
c = conn.cursor()
retData = c.execute(toExec)
retData = c.execute(toExec, params)
conn.commit()
return retData
def deleteBeforeDate(self, date):
# TODO, delete blacklist entries before date
return
def deleteExpired(self, dataType=0):
'''Delete expired entries'''
deleteList = []
@ -60,13 +60,13 @@ class OnionrBlackList:
except AttributeError:
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 (curTime - i[2]) >= i[3]:
deleteList.append(i[0])
for thing in deleteList:
self._dbExecute("delete from blacklist where hash='%s'" % (thing,))
self._dbExecute("DELETE FROM blacklist WHERE hash = ?", (thing,))
def generateDB(self):
self._dbExecute('''CREATE TABLE blacklist(
@ -77,12 +77,12 @@ class OnionrBlackList:
);
''')
return
def clearDB(self):
self._dbExecute('''delete from blacklist;);''')
self._dbExecute('''DELETE FROM blacklist;);''')
def getList(self):
data = self._dbExecute('select * from blacklist')
data = self._dbExecute('SELECT * FROM blacklist')
myList = []
for i in data:
myList.append(i[0])
@ -113,4 +113,4 @@ class OnionrBlackList:
return
insert = (hashed,)
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():
self.daemon._core._blacklist.addToDB(bHash)
self.daemon._core.removeBlock(bHash)
self.daemon.decrementThreadCount('cleanOldBlocks')
def cleanKeys(self):
@ -87,7 +87,7 @@ class DaemonTools:
c = conn.cursor()
time = self.daemon._core._utils.getEpoch()
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])
deleteKeys.append(entry[1])

View File

@ -40,7 +40,7 @@ class OnionrUser:
self.trust = self._core.getPeerInfo(self.publicKey, 'trust')
return
def setTrust(self, newTrust):
'''Set the peers trust. 0 = not trusted, 1 = friend, 2 = ultimate'''
self._core.setPeerInfo(self.publicKey, 'trust', newTrust)
@ -49,7 +49,7 @@ class OnionrUser:
if self._core.getPeerInfo(self.publicKey, 'trust') == 1:
return True
return False
def getName(self):
retData = 'anonymous'
name = self._core.getPeerInfo(self.publicKey, 'name')
@ -63,11 +63,11 @@ class OnionrUser:
def encrypt(self, data):
encrypted = coreInst._crypto.pubKeyEncrypt(data, self.publicKey, encodedData=True)
return encrypted
def decrypt(self, data, anonymous=True):
decrypted = coreInst._crypto.pubKeyDecrypt(data, self.publicKey, encodedData=True)
return decrypted
def forwardEncrypt(self, data):
retData = ''
forwardKey = self._getLatestForwardKey()
@ -78,7 +78,7 @@ class OnionrUser:
raise onionrexceptions.InvalidPubkey("No valid forward key available for this user")
#self.generateForwardKey()
return (retData, forwardKey)
def forwardDecrypt(self, encrypted):
retData = ""
#logger.error(self.publicKey)
@ -101,19 +101,19 @@ class OnionrUser:
conn = sqlite3.connect(self._core.peerDB, timeout=10)
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]
break
conn.commit()
conn.close()
return key
def _getForwardKeys(self):
conn = sqlite3.connect(self._core.peerDB, timeout=10)
c = conn.cursor()
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]
keyList.append(key)
@ -150,7 +150,7 @@ class OnionrUser:
pubkey = self._core._utils.bytesToStr(pubkey)
command = (pubkey,)
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]))
if len(keyList) == 0:
if genNew:
@ -173,7 +173,7 @@ class OnionrUser:
conn.commit()
conn.close()
return
def findAndSetID(self):
'''Find any info about the user from existing blocks and cache it to their DB entry'''
infoBlocks = []
@ -186,4 +186,4 @@ class OnionrUser:
logger.info('%s is now using the name %s.' % (self.publicKey, self._core._utils.escapeAnsi(newName)))
self._core.setPeerInfo(self.publicKey, 'name', newName)
else:
raise onionrexceptions.InvalidPubkey
raise onionrexceptions.InvalidPubkey

View File

@ -276,7 +276,7 @@ class OnionrUtils:
else:
logger.warn('FS not used for this encrypted block')
logger.info(myBlock.bmetadata)
try:
if len(blockType) <= 10:
self._core.updateBlockInfo(blockHash, 'dataType', blockType)
@ -328,7 +328,7 @@ class OnionrUtils:
c = conn.cursor()
if not self.validateHash(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:
conn.commit()
conn.close()
@ -402,7 +402,7 @@ class OnionrUtils:
logger.warn('Block is expired')
break
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)
nonce = self._core._utils.bytesToStr(self._core._crypto.sha3Hash(blockData))
try:
@ -488,7 +488,7 @@ class OnionrUtils:
retVal = False
if not idNoDomain.isalnum():
retVal = False
# Validate address is valid base32 (when capitalized and minus extension); v2/v3 onions and .b32.i2p use base32
try:
base64.b32decode(idNoDomain.upper().encode())
@ -510,7 +510,7 @@ class OnionrUtils:
c = conn.cursor()
command = (hash,)
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] != '':
retData = row[0]
return retData