如何防止函数中的SQL注入?

时间:2018-08-17 06:29:13

标签: c# sql sql-injection sqlbindparameter

我正在做一个程序,可以添加和搜索数据库中的人员。所有功能现在都可以使用,但是我想防止SQL注入。有任何想法吗?感谢您的帮助!

这是搜索功能:

public static void SearchAll()          //Söka fram alla deltagare och visa det i rutan på skärmen.
{
    Form1.result = "";

    connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Carlo\Desktop\Projekt\Examensarbete 2018\AdminPanel\AdminPanel\employees.mdf;Integrated Security=True";

    sql = "SELECT * FROM [employee]";

    cnn = new SqlConnection(connectionString);

    cnn.Open();
    cmd = new SqlCommand(sql, cnn);
    reader = cmd.ExecuteReader();

    while (reader.Read())
    {
        Form1.result += "Email: " + reader.GetValue(1) + Environment.NewLine;
        Form1.result += "First name: " + reader.GetValue(2) + Environment.NewLine;
        Form1.result += "Last name: " + reader.GetValue(3) + Environment.NewLine;
        Form1.result += "Address: " + reader.GetValue(4) + Environment.NewLine;
        Form1.result += "Phonenumber: " + reader.GetValue(5) + Environment.NewLine;                               
        Form1.result += "Jobtitle: " + reader.GetValue(7) + Environment.NewLine;
        Form1.result += "Salary: " + reader.GetValue(6) + Environment.NewLine + Environment.NewLine;
    }
}

这是添加功能:

public static void Add(string AddEmail, string AddFistName, string AddLastName, string AddAddress, string AddPhonenumber, string AddJobTitle, string AddSalary, string checkboxChecker)     //Lägg til en deltagare funktionen.
{
    connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Carlo\Desktop\Projekt\Examensarbete 2018\AdminPanel\AdminPanel\employees.mdf;Integrated Security=True";
    using(var conn = new SqlConnection(connectionString))
    {
        var cmd = new SqlCommand("insert into Employee (Email, FirstName, LastName, Address, Phonenumber, Salary, JobTitle, GDPR,StartDate) VALUES ('" + AddEmail + "','" + AddFistName + "','" + AddLastName + "','" + AddAddress + "','" + AddPhonenumber + "', '" + AddJobTitle + "', '" + AddSalary + "', '" + checkboxChecker + "', GETDATE())", conn);
        conn.Open();
        cmd.ExecuteNonQuery();
    }
}

尝试此操作时,我得到System.NullReferenceException。我已经尝试解决此问题,但我找不到问题所在,就是“电子邮件”。

public static void LoginChecker(string email, string Password)          //Funktionen som kollar ifall man får logga in eller inte.
        {
            Form1.result = "";
            failedCounter = 3;
            connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Carlo\Desktop\Projekt\Examensarbete 2018\AdminPanel\AdminPanel\employees.mdf;Integrated Security=True";
            sql = "SELECT * FROM Login WHERE UserName = @email AND Password = @password ";
            cmd.Parameters.AddWithValue("@email", email);
            cmd.Parameters.AddWithValue("@password", Password); //the problem says to be here!!!!!!
            cnn = new SqlConnection(connectionString);

            cnn.Open();
            cmd = new SqlCommand(sql, cnn);
            reader = cmd.ExecuteReader();

            if (reader.Read() == true)                          //Om det finns ett inlogg med rätt email och lösenord så kommer man in.
            {
                Form1.Log = "Successful";
            }
            else                                               //Om det inte finns ett inlogg med det som skrivits in så kommer man inte in.
            {

                 Form1.Log = "Failed";

            }
        }

1 个答案:

答案 0 :(得分:0)

1。验证用户输入

如果输入仅包含ID或整数,请添加一些验证以仅接受数字。如果输入很复杂,则使用正则表达式模式来识别正确的输入。

示例视图:

<asp:TextBox ID="txtUserID" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvUserID" ControlToValidate="txtUserID" Display="Dynamic" runat="server" ErrorMessage="Required"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revUserID" runat="server" ErrorMessage="Numbers Only" ValidationExpression="[0-9]+" ControlToValidate="txtUserID"
Display="Dynamic">

2。参数化的SQL查询和存储过程

参数化查询在运行SQL查询之前会对参数进行适当的替换。通过参数化查询,它完全消除了“脏”输入更改查询含义的可能性,除了常规注入外,您还可以处理所有数据类型,数字(整数和浮点数),字符串(带有嵌入式引号),日期和时间(当不使用不变区域性调用.ToString()且您的客户端移动到具有非预期日期格式的计算机上时,没有格式问题或本地化问题)。

赞:

SqlCommand command = new SqlCommand("spDisplayUserByID", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@userID", SqlDbType.Int).Value = userID;

参考:https://www.codeproject.com/Articles/813965/Preventing-SQL-Injection-Attack-ASP-NET-Part-I