Am I protected against SQL injections? - c#

I have been attacked on my last few questions here for writing code that is open to injections. I am looking for honest help to make sure I am finally doing this the safest and correct way. Please give me any tips to make this as secure as possible.
using (SqlConnection conn = new SqlConnection(""))
{
try
{
SqlCommand cmd = new SqlCommand(#"INSERT dbo.Table (FullName, Category, Street, City, State, Zip, PhoneDay, PhoneEven, Email, Employer, Description, UserName,
UserStreet, UserCity, UserState, UserZip, UserPhoneDay, UserPhoneEven, UserEmail, SubmitDate)
VALUES (#f1, #f2, #f3, #f4, #f5, #f6, #f7, #f8, #f9, #f10, #f11, #f12, #f13, #f14, #f15, #f16, #f17, #f18, #f19, #f20)", conn);
conn.Open();
cmd.Parameters.Add("#f1", SqlDbType.NVarChar, 100).Value = NameTxtBox.Text;
cmd.Parameters.Add("#f2", SqlDbType.NVarChar, 100).Value = HeroicList.SelectedValue;
cmd.Parameters.Add("#f3", SqlDbType.NVarChar, 100).Value = StreetTxtBox.Text;
cmd.Parameters.Add("#f4", SqlDbType.NVarChar, 100).Value = CityTxtBox.Text;
cmd.Parameters.Add("#f5", SqlDbType.NVarChar, 100).Value = StateTxtBox.Text;
cmd.Parameters.Add("#f6", SqlDbType.NVarChar, 100).Value = ZipTxtBox.Text;
cmd.Parameters.Add("#f7", SqlDbType.NVarChar, 100).Value = PhoneDayTxtBox.Text;
cmd.Parameters.Add("#f8", SqlDbType.NVarChar, 100).Value = PhoneEvenTxtBox.Text;
cmd.Parameters.Add("#f9", SqlDbType.NVarChar, 100).Value = EmailTxtBox.Text;
cmd.Parameters.Add("#f10", SqlDbType.NVarChar, 100).Value = EmpTxtBox.Text;
cmd.Parameters.Add("#f11", SqlDbType.NVarChar, 100).Value = WhyTxtBox.Text;
cmd.Parameters.Add("#f12", SqlDbType.NVarChar, 100).Value = UserNameTxtBox.Text;
cmd.Parameters.Add("#f13", SqlDbType.NVarChar, 100).Value = UserStreetTxtBox.Text;
cmd.Parameters.Add("#f14", SqlDbType.NVarChar, 100).Value = UserCityTxtBox.Text;
cmd.Parameters.Add("#f15", SqlDbType.NVarChar, 100).Value = UserStateTxtBox.Text;
cmd.Parameters.Add("#f16", SqlDbType.NVarChar, 100).Value = UserZipTxtBox.Text;
cmd.Parameters.Add("#f17", SqlDbType.NVarChar, 100).Value = UserPhoneDayTxtBox.Text;
cmd.Parameters.Add("#f18", SqlDbType.NVarChar, 100).Value = UserPhoneEvenTxtBox.Text;
cmd.Parameters.Add("#f19", SqlDbType.NVarChar, 100).Value = UserEmailTxtBox.Text;
cmd.Parameters.Add("#f20", SqlDbType.DateTime).Value = DateTime.Now.ToString();
cmd.ExecuteNonQuery();
messageLabel.Text = "Your submission has been sent!";
messageLabel.Visible = true;
}
catch (System.Data.SqlClient.SqlException ex)
{
messageLabel.Text = ex.Message;
messageLabel.Visible = true;
}
}

You're protected with respect to insertion, yes. Using your code, it doesn't matter what the user puts in any of the textboxes (or what they put in any other sort of response they can cook up) nothing will happen beyond their data being stuck into fields of a new row of the given table, exactly as the strings were given to you.
The only way (that comes to mind) that someone could maliciously inject code would depend on how you use the data once it's in the database. If you go and, for example, take a field from this table and stick it in a LiteralControl without escaping anything and show it to other users then someone could stick in nasty JavaScript code that they run on another person's machine, for example. That would be a "cross site scripting" attack. To prevent that you need to make sure that any user-inputted data is sanitized before being displayed.

Related

Syntax error near: When connecting to mysql database

I've read on a lot of threads, but none of them is actually working, thats why I'm asking a new question.
Well, so I'm trying to insert values into my MySQL database but I'm getting the error.
MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near 'Desc, Detectors, DetectorNos,
Question1, Question2, SpecialPrec, OfficerSign, Of' at line 1'
And I can't find where the problem is. I've been trying for hours without any result, even read all throught a hundred of times but still no luck. So I need someone else to take a look.
public string detector = "";
public string questions = "";
public string question2 = "";
public string capOrCheif = "";
private void btn_send_Click(object sender, EventArgs e)
{
if(cbox_detectors_yes.Checked == true)
{
detector = "Yes";
}
if(cbox_yes1.Checked == true && cbox_yes3.Checked == true && cbox_yes4.Checked == true && cbox_yes5.Checked == true && cbox_yes6.Checked == true && cbox_yes7.Checked == true)
{
questions = "Yes";
}
if(cbox_yes2.Checked == true)
{
question2 = "Yes";
}
if(cbox_cheif.Checked == true)
{
capOrCheif = "Cheif Engineer";
}
else if(cbox_captain.Checked == true)
{
capOrCheif = "Captain";
}
else if(cbox_na2.Checked == true)
{
question2 = "N/A";
}
else if(cbox_detectors_na.Checked == true)
{
detector = "N/A";
}
string constring = "Server = **; Database = **; User Id = **; Password = ***; Sslmode = none;";
string Query = "INSERT INTO tbl_permit (Username, Ship, Date, TimeFrom, TimeTo, Location, Desc, Detectors, DetectorNos, Question1, Question2, SpecialPrec, OfficerSign, OfficerName, OfficerPos, CheifSign, CheifName, CaptainSign, CaptainName, PrecAddedBy, PrecBox) values(#Username, #Ship, #Date, #TimeFrom, #TimeTo, #Location, #Desc, #Detectors, #DetectorNos, #Question1, #Question2, #SpecialPrec, #OfficerSign, #OfficerName, #OfficerPos, #CheifSign, #CheifName, #CaptainSign, #CaptainName, #PrecAddedBy, #PrecBox);";
MySqlConnection con = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, con);
cmdDatabase.Parameters.Add("#Username", MySqlDbType.VarChar, 50).Value = login.username;
cmdDatabase.Parameters.Add("#Ship", MySqlDbType.VarChar, 50).Value = txtbox_ship.Text;
cmdDatabase.Parameters.Add("#Date", MySqlDbType.VarChar, 50).Value = txtbox_date.Text;
cmdDatabase.Parameters.Add("#TimeFrom", MySqlDbType.VarChar, 50).Value = txtbox_timeFrom.Text;
cmdDatabase.Parameters.Add("#TimeTo", MySqlDbType.VarChar, 50).Value = txtbox_timeTo.Text;
cmdDatabase.Parameters.Add("#Location", MySqlDbType.VarChar, 50).Value = txtbox_location;
cmdDatabase.Parameters.Add("#Desc", MySqlDbType.VarChar, 50).Value = txtbox_work_desc.Text;
cmdDatabase.Parameters.Add("#Detectors", MySqlDbType.VarChar, 50).Value = detector;
cmdDatabase.Parameters.Add("#DetectorNos", MySqlDbType.VarChar, 50).Value = txtbox_detector_desc.Text;
cmdDatabase.Parameters.Add("#Question1", MySqlDbType.VarChar, 50).Value = questions;
cmdDatabase.Parameters.Add("#Question2", MySqlDbType.VarChar, 50).Value = question2;
cmdDatabase.Parameters.Add("#SpecialPrec", MySqlDbType.VarChar, 50).Value = txtbox_precautions.Text;
cmdDatabase.Parameters.Add("#OfficerSign", MySqlDbType.VarChar, 50).Value = txtbox_officer_sign.Text;
cmdDatabase.Parameters.Add("#OfficerName", MySqlDbType.VarChar, 50).Value = txtbox_officer_name.Text;
cmdDatabase.Parameters.Add("#OfficerPos", MySqlDbType.VarChar, 50).Value = txtbox_officer_pos.Text;
cmdDatabase.Parameters.Add("#CheifSign", MySqlDbType.VarChar, 50).Value = txtbox_cheif_sign.Text;
cmdDatabase.Parameters.Add("#CheifName", MySqlDbType.VarChar, 50).Value = txtbox_cheif_name.Text;
cmdDatabase.Parameters.Add("#CaptainSign", MySqlDbType.VarChar, 50).Value = txtbox_captain_sign.Text;
cmdDatabase.Parameters.Add("#CaptainName", MySqlDbType.VarChar, 50).Value = txtbox_captain_name.Text;
cmdDatabase.Parameters.Add("#PrecAddedBy", MySqlDbType.VarChar, 50).Value = capOrCheif;
cmdDatabase.Parameters.Add("#PrecBox", MySqlDbType.VarChar, 50).Value = txtbox_restrictions.Text;
MySqlDataReader myReader;
if (cbox_read.Checked == true)
{
con.Open();
myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
}
MessageBox.Show("Hot Work Permit Form has been sent to the Cheif Engineer");
}
else
{
MessageBox.Show("You have to read it through and accept it!");
}
}
DATE is not a reserved word, despite the comment above. You can get a list of reserved words here: https://dev.mysql.com/doc/refman/8.0/en/keywords.html
That page lists keywords, but only a subset of those are reserved, indicated by the (R) annotation in the list.
The error message tells you which word caused the parser to become confused:
...check the manual that corresponds to your MySQL server version for the right syntax to use near 'Desc, Detectors, ...
It got confused on the word DESC. Syntax errors in MySQL always show you the portion of the query starting at the point where it got confused.
DESC is the reserved word causing a problem in this case. DESC has the (R) annotation in the keywords list I linked to.
You should delimit identifiers that conflict with reserved words:
string Query = "INSERT INTO tbl_permit (... Location, `Desc`, Detectors, ...

Inserting multiple Values into Microsoft SQL Server via C#

I have a database made up of 2 (more, actually, but only 2 im working with) tables.
The Material table consists solely of the material-number and the description
DPMatNr
DPBezeichnung
The Eigenschaften table is there to hold the properties of the materials.
It uses the columns:
EigenschaftenBezeichnerID
Wert (value)
My problem is: each entry in the Material table needs to have multiple entries in the Eigenschaften table.
For example:
"Material":
DPMatNr = 001,
DPBezeichnung = "Description"
"Eigenschaften":
EigenschaftenBezeichnerID = 1,
Wert = "A4"
EigenschaftenBezeichnerID = 3,
Wert = "80" and so on.
My code currently looks like this:
public static void InsertData(string connectionstring, string matnummer, string bezeichnung, string format, string grammatur, string gewicht, string eform, string kuvertierung, string altkuvert)
{
string query = #"Insert INTO dbo.Material (DPMatNr, DPBezeichnung)
VALUES (#matnummer, #bezeichnung)";
string query2 = #"Insert INTO dbo.Eigenschaften
(EigenschaftenBezeichnerID, Wert)
VALUES (#1, #format, #2, #grammatur, #3, #gewicht,
#4, #eform, #5, #kuvertierung,
#6, #altkuvert)";
using (SqlConnection cn = new SqlConnection(connectionstring))
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.Add("#matnummer", SqlDbType.VarChar, 50).Value = matnummer;
cmd.Parameters.Add("#bezeichnung", SqlDbType.VarChar, 50).Value = bezeichnung;
cn.Open();
cmd.ExecuteNonQuery();
using (SqlCommand cmd2 = new SqlCommand(query2, cn))
{
cmd2.Parameters.Add("#1", SqlDbType.Int).Value = 1;
cmd2.Parameters.Add("#format", SqlDbType.VarChar, 50).Value = format;
cmd2.Parameters.Add("#2", SqlDbType.Int).Value = 2;
cmd2.Parameters.Add("#grammatur", SqlDbType.VarChar, 50).Value = grammatur;
cmd2.Parameters.Add("#3", SqlDbType.Int).Value = 3;
cmd2.Parameters.Add("#gewicht", SqlDbType.VarChar, 50).Value = gewicht;
cmd2.Parameters.Add("#4", SqlDbType.Int).Value = 4;
cmd2.Parameters.Add("#eform", SqlDbType.VarChar, 50).Value = eform;
cmd2.Parameters.Add("#5", SqlDbType.Int).Value = 5;
cmd2.Parameters.Add("#kuvertierung", SqlDbType.VarChar, 50).Value = kuvertierung;
cmd2.Parameters.Add("#6", SqlDbType.Int).Value = 6;
cmd2.Parameters.Add("#altkuvert", SqlDbType.VarChar, 50).Value = altkuvert;
cmd2.ExecuteNonQuery();
}
cn.Close();
}
}
Now I currently get an error that says:
System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 'dbo.Material' with unique index 'IX_MatNrUnique'
What am I doing wrong?
The Problem here is, that for every "Eigenschaft" you insert into the table you also try to create an entry in the "Material" table. But since every material should only be inserted once (therefore the primary key) you get the error.
Edit:
You could adjust your method like the following:
public static void InsertData(string connectionstring, string matnummer, string bezeichnung, string format, string grammatur, string gewicht, string eform, string kuvertierung, string altkuvert)
{
string check = "Select COUNT(*) FROM dbo.Material where DPMatNr = #matnummer";
string query = "Insert INTO dbo.Material (DPMatNr, DPBezeichnung)" + "VALUES (#matnummer, #bezeichnung)";
string query2 = "Insert INTO dbo.Eigenschaften (EigenschaftenBezeichnerID, Wert)" + "VALUES (#1, #format, #2, #grammatur, #3, #gewicht, #4, #eform, #5, #kuvertierung, #6, #altkuvert)";
using (SqlConnection cn = new SqlConnection(connectionstring))
using (SqlCommand chkCom = new SqlCommand(check, cn))
{
cn.Open();
chkCom.Parameters.Add("#matnummer", SqlDbType.VarChar, 50).Value = matnummer;
int? matCnt = chkCom.ExecuteScalar() as int?;
if (matCnt == 0 || matCnt == null)
{
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.Add("#matnummer", SqlDbType.VarChar, 50).Value = matnummer;
cmd.Parameters.Add("#bezeichnung", SqlDbType.VarChar, 50).Value = bezeichnung;
cmd.ExecuteNonQuery();
}
}
using (SqlCommand cmd2 = new SqlCommand(query2, cn))
{
cmd2.Parameters.Add("#1", SqlDbType.Int).Value = 1;
cmd2.Parameters.Add("#format", SqlDbType.VarChar, 50).Value = format;
cmd2.Parameters.Add("#2", SqlDbType.Int).Value = 2;
cmd2.Parameters.Add("#grammatur", SqlDbType.VarChar, 50).Value = grammatur;
cmd2.Parameters.Add("#3", SqlDbType.Int).Value = 3;
cmd2.Parameters.Add("#gewicht", SqlDbType.VarChar, 50).Value = gewicht;
cmd2.Parameters.Add("#4", SqlDbType.Int).Value = 4;
cmd2.Parameters.Add("#eform", SqlDbType.VarChar, 50).Value = eform;
cmd2.Parameters.Add("#5", SqlDbType.Int).Value = 5;
cmd2.Parameters.Add("#kuvertierung", SqlDbType.VarChar, 50).Value = kuvertierung;
cmd2.Parameters.Add("#6", SqlDbType.Int).Value = 6;
cmd2.Parameters.Add("#altkuvert", SqlDbType.VarChar, 50).Value = altkuvert;
cmd2.ExecuteNonQuery();
}
cn.Close();
}
}

C# can't insert into Data Source

Here is my code:
try
{
SqlCommand cmd2 = new SqlCommand(#"INSERT INTO Clienti (parola,nume,prenume,adresa,email,kcal_zilnice) VALUES (#Parola,#Nume,#Prenume,#Adresa,#Email,2000)", conn);
cmd2.Prepare();
cmd2.Parameters.AddWithValue("#Parola", passBox.Text);
cmd2.Parameters.Add("#Nume", SqlDbType.VarChar, 50).Value = nameBox.Text;
cmd2.Parameters.Add("#Prenume", SqlDbType.VarChar, 50).Value = pnameBox.Text;
cmd2.Parameters.Add("#Adresa", SqlDbType.VarChar, 100).Value = adressBox.Text;
cmd2.Parameters.Add("#Email", SqlDbType.VarChar, 100).Value = emailBox.Text;
cmd2.ExecuteNonQuery();
}
catch (SqlException exception)
{
MessageBox.Show("Failed! " + exception.Message);
}
MessageBox.Show("User Created!");
I don't know what am I doing wrong here. I even tried to replace #Parola with 'abc' but it does not work. I don't get any error message. Every time I get "User Created", but when I look into the DB I get all the fields NULL(no records where created).
So, for anyone that has the same problem Prepare() solved it.
Use Add() for params and specify The SqlDbType. Prepare() will not work with AddWithValue().
At the end do Prepare() and then ExecuteNonQuery().

I want to Insert RadioButton Value in SQL Database using Classes

I created a Class name EmployeeDAta write this code here and i want to Insert Radiobutton value in SQL Database
public static void AddEmployee(Employee employee)
{
string connString = ConfigurationManager.ConnectionStrings["Employee"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
using (conn)
{
SqlCommand cmd = new SqlCommand("ADDEMPLOYEE", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar, 50).Value = employee.Name;
cmd.Parameters.Add("#FName", SqlDbType.NVarChar, 50).Value = employee.Fname;
cmd.Parameters.Add("#Address", SqlDbType.NVarChar, 50).Value = employee.Address;
cmd.Parameters.Add("#Email", SqlDbType.NVarChar, 50).Value = employee.Email;
cmd.Parameters.Add("#Mobile", SqlDbType.NVarChar, 50).Value = employee.Mobile;
cmd.Parameters.Add("#Pincode", SqlDbType.NVarChar, 50).Value = employee.Pincode;
cmd.Parameters.AddWithValue("#VB", SqlDbType.Bit).Value = employee.VB;
cmd.Parameters.AddWithValue("#ASP", SqlDbType.Bit).Value = employee.ASP;
cmd.Parameters.AddWithValue("#Gender", SqlDbType.Int).Value = employee.Gender;
conn.Open();
cmd.ExecuteNonQuery();
}
}
add a parameter to your stored procedure call:
cmd.Parameters.AddWithValue("#ValueOfRadioButtonr", SqlDbType.Int).Value = MyRadioButton.Value;
In the stored procedure on the database, make sure you handle the extra parameter.

Standard for database connection - try/catch?

I am new to coding in Visual Studio and C#. I have my connection to my db working, and I can insert/update/delete just fine. But what if the database cannot connect one day? What kind of precautions should be coded? I think maybe a try/catch?
For example I have this code:
using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString))
{
sqlConn.Open();
//Insert text into db
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.Connection = sqlConn;
sqlCmd.CommandType = System.Data.CommandType.Text;
sqlCmd.CommandText = string.Format("INSERT INTO Person(Name, Location, City, State) VALUES (#Name, #Location, #City, #State)");
sqlCmd.Parameters.Add("#EventName", SqlDbType.NVarChar, 255).Value = name;
sqlCmd.Parameters.Add("#Location", SqlDbType.NVarChar, 255).Value = location;
sqlCmd.Parameters.Add("#City", SqlDbType.NVarChar, 30).Value = city;
sqlCmd.Parameters.Add("#State", SqlDbType.NVarChar, 2).Value = state;
sqlCmd.ExecuteNonQuery();
}
}
}
Should that code be under try? What should be under the catch? Is there any other standard to catch if a database cannot connect or if some unexpected error occurs? Thank you.

Categories

Resources