-1

Im doing a program who can add and search for persons from a database. all the functions works right now but i want to prevent SQL injections. any ideas? Thankful for help!

This is the search function:

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;
    }
}

This is the add function:

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();
    }
}

I get System.NullReferenceException when im trying this. i have tryied to fix it but i cant find the problem the problem says to be with the "email".

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";

            }
        }
Dharman
  • 30,962
  • 25
  • 85
  • 135
Carlo Goretti
  • 47
  • 1
  • 10
  • also use parameters, i wrote a reusable method for this task: https://stackoverflow.com/a/51303994/5718868 – Jonathan Applebaum Aug 17 '18 at 06:35
  • The [tag:visual-studio] tag says *"DO NOT use this tag on questions regarding code which merely happened to be written in Visual Studio"*, so you should remove that. Given the sample code, you should add a [tag:sql-server] tag. – Richardissimo Aug 17 '18 at 07:24
  • Other tips: SqlCommand and SqlDataReader are both IDisposable, so each should be in a `using` block. (And similarly, the first sample of code doesn't put the SqlConnection in a `using` block.) – Richardissimo Aug 17 '18 at 07:26
  • You are on a good way, just fix your null reference exception and continue. – nvoigt Aug 17 '18 at 08:08
  • ye but thats the problem! i dont know how to fix that, do you know? – Carlo Goretti Aug 17 '18 at 08:15
  • 1
    Read the duplicate. It has nothing to do with SQL injections, it's a basic C# programming thing. I could point you to the thing to change in your code, but you will encounter this time and again when programming, so its better to learn how to solve it on your own. The duplicate link has a good explanation how to do that. – nvoigt Aug 17 '18 at 08:18
  • honestly if you cant help me with this one, im never going to solve this because i dont know the problem.. pls help this time. – Carlo Goretti Aug 17 '18 at 09:09
  • 1
    Please see [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) – glennsl Aug 17 '18 at 14:32
  • Now the question has been edited, I'd suggest also reading [can we stop using AddWithValue](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) – Richardissimo Aug 18 '18 at 05:29

1 Answers1

0

1. Validate user input

If your input takes only ids or integers, add some validations for accept only numbers. If inputs are complicated, then use the regex patterns to identify the correct inputs.

Example view:

<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. Parameterized SQL query & Stored Procedure

Parameterized queries do proper substitution of arguments prior to running the SQL query. It completely removes the possibility of "dirty" input changing the meaning of your query, with parameterized queries, in addition to general injection, you get all the data types handled, numbers (int and float), strings (with embedded quotes), dates and times (no formatting problems or localization issues when .ToString() is not called with the invariant culture and your client moves to a machine with and unexpected date format).

Like:

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

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

Sameeksha Kumari
  • 1,158
  • 2
  • 16
  • 21