While submitting a form, in one of the fields i am inserting vulnerable characters like =cmd|'/C calc'!A0. So in security terms it is termed as CSV-injection in export functionality
I have written code like this for above error. but its not working
[WebMethod]
public static string SaveRecord(RRSOCSaving RRSOCSaving, string Indication)
{
string strReturnId = "";
string strAppURL = ConfigurationManager.AppSettings["AppUrl"].ToString();
string strmail_Content = "";
CommonDB commonObj = new CommonDB();
try
{
// Cross site scripting issue code tag..!!
if (commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_CODE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.CITY)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_1)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_2)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SUPERVISOR_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_NAME_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_MOBNO_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_MOBNO))
{
strReturnId = "Something went wrong due to malicious script attack..!!!";
}
else
{
if (RRSOCSaving.ROLE_ASSIGNED == "SLP State Head")
{
bool blnState1 = Array.Exists(RRSOCSaving.ASSIGNED_STATE.ToString().ToUpper().Split(','), element => element == (RRSOCSaving.STATE).ToString().ToUpper());
if (blnState1)
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
}
else
{
strReturnId = "User can add data for " + RRSOCSaving.ASSIGNED_STATE + " only";
}
}
else if (RRSOCSaving.ROLE_ASSIGNED == "NHQ Admin")
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
//strReturnId = "Record Saved Succesfully";
}
}
// strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving);
}
catch (Exception)
{
throw;
}
return strReturnId;
}
public bool HackerTextExistOrNot(string Text)
{
bool flgValid = false;
Regex htmltags = new Regex(#"<.*?>");
Match chkMatch = htmltags.Match(Text);
if (chkMatch.Success)
{
flgValid = true;
}
return flgValid;
}
Please suggest how to stop this error.
Your HackerTextExistOrNot method is checking for the existance of html tags.
You should however check if the text is starting with one of the formular triggering characters.
To protect yourself against the injection attack ensure that none of the given text begins with any of the following characters:
Equals to ("=")
Plus ("+")
Minus ("-")
At ("#")
So you can check like this:
var attackChars = new char[]{'=','+','-','#'};
if(attackChars.Contains(text[0])
{
}
Related
I have an if statement in a web service call that is always returning false. I want it to return an error message if there isn't the words "VERTICALPALLETS", or "PALLETLABELS" in it. Even if this field has those words in it, it is still returning an error. The query is not the correct one I am using in my application. Any help is much appreciated.
public bool ValidateDevice(string DeviceID, string sVersion, out string MachineID, out string MachineName, out string Plant, out string Printer1, out string Printer2, out string WrapStation, out string Location, out string sMessage)
{
MachineID = "";
MachineName = "";
Plant = "";
Printer1 = "";
Printer2 = "";
Plant = "";
WrapStation = "";
Location = "";
sMessage = "";
bool bTest = CheckVersion(sVersion, out sMessage);
if (bTest == false)
{
sMessage = "You do not meet the minimum version requirements. Contact MIS.";
return false;
}
try
{
SqlConnection connection = new SqlConnection(capmSADPConnectionString);
connection.Open();
string queryString = "select * from DATABASE";
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.Clear();
command.Parameters.AddWithValue("#DEVICEID", DeviceID);
command.Parameters.AddWithValue("#APPID", "VTP");
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows == false)
{
email myEmail = new email();
myEmail.SendErrorEmail("No Application Settings for VTP Device ID - " + DeviceID, "VTPError", "VTP Device Settings Error");
sMessage = "Could not find application settings for this device. Please enter settings.";
return false;
}
reader.Read();
MachineID = reader.GetValue(0).ToString();
MachineName = reader.GetValue(1).ToString();
Plant = reader.GetValue(2).ToString();
Location = reader.GetValue(3).ToString();
Printer1 = reader.GetValue(4).ToString();
Printer2 = reader.GetValue(5).ToString();
WrapStation = reader.GetValue(6).ToString();
reader.Close();
reader = null;
command = null;
connection.Close();
connection = null;
if ((Location.ToUpper().Contains("VERTICALPALLETS") == false) || (Location.ToUpper().Contains("PALLETLABELS") == false))
{
sMessage = "Please enter correct location in Application Setup and try again.";
return false;
}
return true;
}
catch (Exception e)
{
sMessage = "Unable to retrieve Application Settings for VTP. Please reopen the application.";
return false;
}
return true;
}
The problem here is with the structure of your if statement:
if ((Location.ToUpper().Contains("VERTICALPALLETS") == false) || (Location.ToUpper().Contains("PALLETLABELS") == false))
{
sMessage = "Please enter correct location in Application Setup and try again.";
return false;
}
You are saying:
If the location does not contain 'VERTICALPALLETS'
Or Else
If the location does not contain 'PALLETLABELS'
This will always be true unless the location contains both bits of text!
You need to change the Or Else to And Also (so || to &&) and therefore your code will work as expected.
Use AND
if ((Location.ToUpper().Contains("VERTICALPALLETS") == false) && (Location.ToUpper().Contains("PALLETLABELS") == false))
Alternative solution which is simpler to read.
if (!(Location.ToUpper().Contains("VERTICALPALLETS") || Location.ToUpper().Contains("PALLETLABELS"))
Sounds like the problem is that you'll always be looking for a "false" or "false" condition unless you are looking for a location that contains both VERTICALPALLETS PALLETLABELS
I suggest you try something like
if (! ( condtion1 || condition2) )
return message
This line
if ((Location.ToUpper().Contains("VERTICALPALLETS") == false) || (Location.ToUpper().Contains("PALLETLABELS") == false))
checks whether Location.ToUpper() does not contain "VERTICALPALLETS" or Location.ToUpper() does not contain "PALLETLABELS". If Location.ToUpper() does not happen to contain both, then the condition is true. You instead wanted to check whether Location.ToUpper() contains either of them:
if ((Location.ToUpper().Contains("VERTICALPALLETS") == false) && (Location.ToUpper().Contains("PALLETLABELS") == false))
{
//...
}
also, it does not makes much sense to calculate ToUpper several times, let's calculate it only once:
String upperLocation = Location.ToUpper();
if ((Location.ToUpper().Contains("VERTICALPALLETS") == false) && (Location.ToUpper().Contains("PALLETLABELS") == false))
{
//...
}
How to re enter a string in text box if string doesn't match?
code I'm trying is but it stucks in loop and does not allow me to enter string again in textbox.
Can anybody guide me how to do this
the code is:
public void userpass()
{
int us = 0; //for user pass
string readText2 = File.ReadAllText(pathuser);
using (StreamReader sr2 = new StreamReader(pathuser))
{
string usernam = username.Text;
string line;
string[] lines = new String[500];
while ((line = sr2.ReadLine()) != null )
{
lines[us] = line;
if (lines[us] == usernam && usernam != "")
{
check = 1;
MessageBox.Show(usernam);
Form2 f2 = new Form2();
this.Hide();
break;
}
us++;
}
if (lines[us-1] != usernam && usernam != null)
{
this.DialogResult = DialogResult.None;
DialogResult result = new DialogResult();
result = MessageBox.Show("Invalid Username or Password?", "Retry", MessageBoxButtons.OK);
if (result == DialogResult.OK)
{
username.Clear();
}
}
}
Okay so i think your problem is mostly checking if the value exist in the file. You can use this function to check if it exist or not and then you can do what you need :
public bool findValueInFile(string filePath, string value)
{
//Get all lines from the txt file
string[] lines = File.ReadAllLines(filePath);
//Go thru all the lines
foreach(string line in lines)
{
//If we find the line we're looking for
if (line.Equals(value))
{
return true;
}
}
//If we haven't found anything return false
return false;
}
After calling this function depending on the return you can show a messagebox or do something else :
if(findValueInFile(yourPath, yourValue))
{
// We found the value
}
else
{
// We didn't find the value
}
I have a signup page that have many filed. Many of them should filled by user.
I use RequiredFieldValidator and RegularExpressionValidator for validate in client side.
Should I validate them in server side? How?
I wrote this code. I use many if and else if. Is this correct?
CaptchaControl1.ValidateCaptcha(txtSecureImg.Text);
if (CaptchaControl1.UserValidated)
{
if (txtFName.Text != string.Empty && txtLName.Text != string.Empty && txtUserName.Text != string.Empty && txtEmail.Text != string.Empty && txtPass.Text != string.Empty && txtCPass.Text != string.Empty && txtSecureImg.Text != string.Empty)
{
if (RegEx.EmailValidate(txtEmail.Text) == 1 && RegEx.PasswordValidate(txtPass.Text) == 1 && RegEx.UserName(txtUserName.Text) == 1)
{
try
{
// insert in database
}
catch (Exception)
{
lblMsg.Text = "Error";
}
}
else if(RegEx.EmailValidate(txtEmail.Text) == 0)
{
EmailRegularExpression.Visible = true;
}
else if(RegEx.PasswordValidate(txtPass.Text) == 0)
{
passRegularExpression.Visible = true;
}
else if(RegEx.UserName(txtUserName.Text) == 0)
{
UnameRegularExpression.Visible = true;
}
}
else if(txtFName.Text == string.Empty)
{
RequiredFieldValidator1.Visible = true;
}
// continue like above for another filed
}
else
{
lblMsg.Text = "Please insert Secure Image";
}
And :
public static int EmailValidate(string Mail)
{
int i = 0;
Regex regExEmail = new Regex(#"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*");
if (regExEmail.IsMatch(Mail))
i = 1;
return i;
}
I'm assuming this is Web Forms...
The validation is run automatically. You can just use the Page.IsValid property: msdn
You'll still need to manually check the captcha field though.
CaptchaControl1.ValidateCaptcha(txtSecureImg.Text);
if (CaptchaControl1.UserValidated && Page.IsValid)
{
// Insert in db.
}
Since you use those validators, then you don't need to validate form in server side again like your codes.
But you should call Page.Validate()and then check page with Page.IsValid method.
from here
example
I have a gridview object that I am using to bind to a datasource. Upon the selectedIndexChanging event of the gridview, I would like to bring the data shown in the gridview into the textboxes on the form. However, when the data contains alphanumeric characters such as &'"", the data from the grid is showing ;amp, #S etc. and all other weird characters whenever I enter an alphanumeric character. Is there a way to prevent these characters from popping up in the textboxes when taking data from the grid?
The code that I have so far:
protected void grdActions_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedRow1 = grdActions.SelectedRow.RowIndex;
hdnIndexNo.Value = grdActions.Rows[selectedRow1].Cells[1].Text;
ddlActionType.SelectedValue = grdActions.Rows[selectedRow1].Cells[3].Text;
if (grdActions.Rows[selectedRow1].Cells[4].Text == null || grdActions.Rows[selectedRow1].Cells[4].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[4].Text == " ")
{
txtDetails.Text = string.Empty;
}
else
{
txtDetails.Text = grdActions.Rows[selectedRow1].Cells[4].Text;
}
if (grdActions.Rows[selectedRow1].Cells[5].Text == null || grdActions.Rows[selectedRow1].Cells[5].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[5].Text == " ")
{
txtCompletedDate.Text = string.Empty;
}
else
{
txtCompletedDate.Text = Convert.ToDateTime(grdActions.Rows[selectedRow1].Cells[5].Text).ToString("dd-MMM-yyyy");
}
ddlActionOwner.SelectedValue = grdActions.Rows[selectedRow1].Cells[7].Text;
if (grdActions.Rows[selectedRow1].Cells[8].Text == null || grdActions.Rows[selectedRow1].Cells[8].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[8].Text == " ")
{
txtAssignedTo.Text = string.Empty;
}
else
{
txtAssignedTo.Text = grdActions.Rows[selectedRow1].Cells[8].Text;
}
if (grdActions.Rows[selectedRow1].Cells[9].Text == null || grdActions.Rows[selectedRow1].Cells[9].Text == string.Empty || grdActions.Rows[selectedRow1].Cells[9].Text == " ")
{
lblComments.Visible = false;
txtComments.Visible = false;
}
else
{
lblComments.Visible = true;
txtComments.Visible = true;
txtComments.Text = grdActions.Rows[selectedRow1].Cells[9].Text;
}
I used the Server.HTMLDecode() when transferring the data fromthe gridview to the textboxes. This ensured that all special characters were removed before it was sent back to the textboxes on the form
I am working on a website. I have to find the value of user can't change password property of a user. I get this link
http://msdn.microsoft.com/en-us/library/aa746448(v=vs.85).aspx[^]
according to which I have to find "ntSecurityDescriptor" value of that user. They are using DirectoryEntry class to find that but in my case I am using LdapConnection class.
If I use entry class I was not able to make connectivity with server So that I change it to LdapConnection class. Now I don't know how to find value.
I find my solution.
SearchResponse response = (SearchResponse)connection.SendRequest(request);
DirectoryAttribute attribute = response.Entries[0].Attributes["ntSecurityDescriptor"];
if (attribute != null)
{
const string PASSWORD_GUID = "{ab721a53-1e2f-11d0-9819-00aa0040529b}";
const int ADS_ACETYPE_ACCESS_DENIED_OBJECT = 6;
bool fEveryone = false;
bool fSelf = false;
ActiveDs.ADsSecurityUtility secUtility = new ActiveDs.ADsSecurityUtility();
ActiveDs.IADsSecurityDescriptor sd = (IADsSecurityDescriptor)secUtility.ConvertSecurityDescriptor((byte[])attribute[0], (int)ADS_SD_FORMAT_ENUM.ADS_SD_FORMAT_RAW, (int)ADS_SD_FORMAT_ENUM.ADS_SD_FORMAT_IID);
ActiveDs.IADsAccessControlList acl = (ActiveDs.IADsAccessControlList)sd.DiscretionaryAcl;
foreach (ActiveDs.IADsAccessControlEntry ace in acl)
{
if ((ace.ObjectType != null) && (ace.ObjectType.ToUpper() == PASSWORD_GUID.ToUpper()))
{
if ((ace.Trustee == "Everyone") && (ace.AceType == ADS_ACETYPE_ACCESS_DENIED_OBJECT))
{
fEveryone = true;
}
if ((ace.Trustee == #"NT AUTHORITY\SELF") && (ace.AceType == ADS_ACETYPE_ACCESS_DENIED_OBJECT))
{
fSelf = true;
}
break;
}
}
if (fEveryone || fSelf)
{
return Global.RequestContants.CANT_CHANGE_PASSWORD;
}
else
{
return string.Empty;
}
}