的即时错误的是,在第一实施例时使用的字符串的字符串格式化%
,然后在封闭text
的结果,而第二个尝试使用字符串text
对象格式化。
更严重的问题是,你已经打开自己注入攻击通过直接格式化用户输入到SQL字符串,而不是单独传递它们。
它看起来像你正在使用Flask-SQLAlchemy。在这种情况下,写一个参数化查询并将参数传递给execute
。
db.engine.execute(
'insert into account values(?, ?, ?, PASSWORD(?), ?)',
(fname, lname, user_name, password, True)
)
db.engine.execute(
'select * from account where account.user_name = ? and account.password = PASSWORD(?) and account.active = ?,
(user_name, password, True)
)
参数化的概念与任何其他数据库驱动程序类似。
而不是依赖数据库来散列的口令,使用passlib
库是一个更强大的替代方案。它包含更强大的哈希,以及“贬低”哈希和升级存储值的能力。
from passlib.hash import pbkdf2_sha512
# when creating a user, generate the hash with passlib
# and don't use PASSWORD() in SQL
password = pbkdf2_sha512.encrypt('secret')
# example login
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
r = engine.execute('select * from account where account.name = ? and account.active = ?', (username, True))
if r:
user = r[0]
# verify the hash using passlib, not SQL
if pbkdf2_sha512.verify(password, user.password):
# active user, correct password, do the login
return 'good credentials'
# incorrect username or password
return 'bad credentials'
return render_template('login.html')
在通过这些哈希值,而不是调用SQL PASSWORD
。
您很容易受到SQL注入攻击。分别传递参数,而不是直接将它们格式化为SQL字符串。 – davidism