欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SQL注入的简单例子

程序员文章站 2022-05-15 09:18:34
...

直接在SQL查询语句拼接查询参数

def getUsers(user_id):
    conn = psycopg2.connect("dbname='demo1' user='postgres' host='127.0.0.1' password='admin'")
    cur = conn.cursor()
    if user_id == None:
        str = 'select distinct * from company'
    else:
        str = 'select distinct * from company where id=%s' % user_id
    print str
    res = cur.execute(str)
    res = cur.fetchall()
    conn.close()
    return res

SQL注入的简单例子
破坏者输入:‘1’ OR ‘1’ = '1’将查询出该表的所有数据!
最后的SQL语句:

select distinct * from company where id='1' OR '1' = '1'

where条件实际结果变成了False or True,成功盗取该表所有数据!

一种解决示例:使用列表/元组传入参数

def getUsers(user_id):
    conn = psycopg2.connect("dbname='demo1' user='postgres' host='127.0.0.1' password='admin'")
    cur = conn.cursor()
    if user_id == None:
        str = 'select distinct * from company'
    else:
        str = 'select distinct * from company where id=%s'
    print str
    res = cur.execute(str, [user_id])	# 使用参数替换直接拼接
    res = cur.fetchall()
    conn.close()
    return res

SQL注入的简单例子
实际使用记得try处理一下异常