Python中的SQL注入漏洞识别

时间:2015-04-08 22:00:04

标签: python sql security sqlite sql-injection

我应该查看这段代码并确定哪些部分可能容易受到SQL注入,为什么并为它们添加修复。我一直在扫描代码,寻找那些参数太模糊的地方,但我找不到可能容易受到攻击的地方。如果任何人都可以快速浏览此代码并指出任何明显的漏洞,那将是非常好的。当用单引号输入时,程序真的喜欢给出错误消息。此代码是跟踪活动的程序的一部分。有3个输入字段,用户名,密码和活动名称。如果有人想要发布更多代码

#!/usr/bin/python3.4

import readline
import sqlite3

def audit(handle, event, obj=None):
  """Log an audit event."""
  if handle[2] is None:
    handle[2]=-1;
  if obj==None:
    handle[0].execute("insert into auditlog(userid, event)"
                  "  values({0}, '{1}')".format(handle[2],event))
  else:
    handle[0].execute("insert into auditlog(userid, event, object)"
                  "  values({0}, '{1}', {2})".format(str(handle[2]),
                                             event, obj))
  if handle[0].lastrowid is None:
    """On error, raise a SystemException"""
    handle[1].commit()
    handle[1].close()
    raise SystemError("Error creating audit log entry.",
                  handle[2],event,obj)
  handle[1].commit()

def register(cursor, connection, username, password):
  """Register a new user and return a connection to the database."""
  cursor.execute("insert into user(username, password)"
             "  values('{0}', '{1}')".format(username, password))
  userid=cursor.lastrowid;
  if userid>0:
    audit((cursor, connection, userid), "registered")
    connection.commit()
    print("Welcome, new user!")
    return (cursor, connection, userid)
  """If the user could not be registered, raise a SystemError."""
  audit((cursor, connection, 0), 
    "registeration error for {0}".format(username))
  connection.commit()
  connection.close()
  raise SystemError("Unknown error registering user",username)

def connect(username, password):
  """Attempt to log in as the specified user."""
  connection=sqlite3.connect('timelog.db')
  cursor=connection.cursor()
  """The database is created if necessary."""
  cursor.execute("create table if not exists user"
             "( id integer primary key,"
             "  username varchar(50) unique not null,"
     "  password char(40) not null,"
     "  created datetime default CURRENT_TIMESTAMP,"
     "  modified datetime default CURRENT_TIMESTAMP"
     ")")

1 个答案:

答案 0 :(得分:0)

例如,此语句易受SQL注入攻击:

cursor.execute("insert into user(username, password)"
         "  values('{0}', '{1}')".format(username, password))

我可以输入用户名:

test','secret');update user set password='';--

您应该使用参数化查询。使用SQLLite,您可以像这样调用sql:

cmd ="插入用户(用户名,密码值(?,?)" curs.execute(cmd,(用户名,密码))