XSS scripts to search in a text field

I have a text box that is used to search for data within the site. What my client wants

1) Enter text in the search field and click the search icon.

2) A request sent to the server using a web proxy tool such as "Burp"

3) Add parameter with script as

test<~script>confirm(123)<~/script> 

what is going on here

The XSS script entered by the helper is reflected in the response without input. Please see the image below, you will get an idea: -

! [enter image description here] [1]

Guys, let me know if you need more information related to this. Please help the guys, any help would be greatly appreciated. I want to stop the attack from the server side.

HTML and JS code: -

  <asp:TextBox ID="txtSearch" runat="server" class="txtfld-search" oncopy="return false" oncut="return false" onpaste="return false"></asp:TextBox> 

JS Code: -

 <script type="text/javascript"> $(document).ready(function () { $('#ctl00_topNavigation_txtSearch').keyup(function () { var $th = $(this); $th.val($th.val().replace(/[^.%a-zA-Z0-9 ]/g, function (str) { alert('Special characters not allowed except %'); return ''; })); }); }); 

Also see the code behind: -

 protected void btnSearch_Click(object sender, ImageClickEventArgs e) { Response.Redirect("search.aspx?tx=" + txtSearch.Text); } 

Also see code for the search part: -

 private void SearchResult() { DataTable dt; if (Session["Search"] == null) { ResXResourceReader reader = new ResXResourceReader(Server.MapPath("~/App_GlobalResources/Strings.en-US.resx")); IDictionaryEnumerator id = reader.GetEnumerator(); string sResourceFile = Server.MapPath("~/App_GlobalResources/Strings.en-US.resx"); XmlDocument xmlResource = new XmlDocument(); xmlResource.Load(sResourceFile); XmlNodeList elmData = xmlResource.SelectNodes("//root/data"); dt = new DataTable(); dt.Columns.Add(new DataColumn("ID", System.Type.GetType("System.String"))); dt.Columns.Add(new DataColumn("Title", System.Type.GetType("System.String"))); dt.Columns.Add(new DataColumn("Description", System.Type.GetType("System.String"))); dt.Columns.Add(new DataColumn("Url", System.Type.GetType("System.String"))); dt.Columns.Add(new DataColumn("Link", System.Type.GetType("System.String"))); foreach (XmlElement element in elmData) { DataRow dr = dt.NewRow(); dr["ID"] = element.GetAttribute("name"); //dr["Title"] = element.GetAttribute("name"); XmlNodeList sDescription = element.SelectNodes("value"); dr["Title"] = sDescription.Count > 0 ? sDescription.Item(0).InnerText : string.Empty; ; dr["Description"] = string.Empty; XmlNodeList sUrl = element.SelectNodes("comment"); if (sUrl.Count > 0) { Int32 sPgTitle = sUrl.Item(0).InnerText.LastIndexOf(".") + 1; if (sPgTitle > 0) { dr["Url"] = sUrl.Item(0).InnerText; //dr["Url"] = Request.Url.Host.ToLower() + "/rbank/" + sUrl.Item(0).InnerText; dr["Link"] = string.Empty; } else { dr["Link"] = sUrl.Item(0).InnerText; } dt.Rows.Add(dr); } } //foreach (DataRow dr in dt.Rows) //{ // DataRow[] rDesc = dt.Select("Link <> ''"); // for (int i = 0; i < rDesc.Length; i++) // { // DataRow[] rTitle = dt.Select("ID = '" + rDesc[i]["Link"] + "'"); // if (rTitle.Count() > 0) // { // rTitle[0]["Description"] = rDesc[i]["Title"]; // } // } //} DataRow[] drDelete = dt.Select("Link <> ''"); foreach (DataRow drCheck in drDelete) { dt.Rows.Remove(drCheck); } dt.TableName = "FilterValues"; reader.Close(); Session["Search"] = dt; } else { dt = Session["Search"] as DataTable; } DataView dv = new DataView(); dv.Table = dt; **dv.RowFilter = "Description LIKE ('%" + Request.QueryString["tx"].Trim().ToLower() + "%') or Title LIKE ('%" + Request.QueryString["tx"].Trim().ToLower() + "%')";** dv.Sort = "Title ASC"; dgrdPages.DataSource = dv; dgrdPages.DataBind(); lblSearchWords.Text = Request.QueryString["tx"].Trim(); lblFilesFound.Text = dv.Count.ToString(); } 

I found that dv.RowFilter can be set as some kind of SQL injection. I want to prevent this. Please, help.

+5
source share
5 answers

As mentioned by other friends, client code can be easily neglected. Therefore, we can translate what you did with javascript in C #, like this, with the addition of mine to remove extra spaces and merge them into one:

 if (Regex.IsMatch(txtSearch.Text, "[^a-zA-Z0-9 %]")) { //error Response.Redirect("Error.aspx?tx=It a Shame Dude!"); } else { //Remove multiple spaces String ClearSpaces = Regex.Replace(txtSearch.Text, @"\s+", " "); Response.Redirect("search?tx=" + HttpUtility.UrlEncode(ClearSpaces)); } 

Remember that regex comes from: this answer . And the regex to replace multiple spaces comes from this answer .

+2
source

There are several problems in your code: lack of input validation, lack of output coding, string filter injection and lack of understanding of the concept of client validation \ Javascript.

Let's discuss this one by one:

  • Lack of input validation . All attacks and problems that I mentioned above can be fixed using the correct input check. I mean the white list , not the black list . You should never look for special characters like apostrophe or LT \ GT, always check the positive whitelist , as it was in your Javascript, and look for valid values, not invalid ones. This is because an attacker can always outwit a programmer and encode his exploit in different ways. As others have mentioned, ValidateRequest performs some level of input validation, but can never be trusted as the only solution, as there are ways around it. Please do not try to search for various exploits, such as <script , as others have suggested, this can be easily circumvented (for example: <img onmouseover=alert(1)> instead of your payload) and is bad practice.
  • lack of encoding output . The reason your code is really vulnerable is the line:

     lblSearchWords.Text = Request.QueryString["tx"].Trim(); 

    You need HTMLEncode any values ​​that were created by the user before integrating them inside the labels. For instance:

     lblSearchWords.Text = HttpUtility.HtmlEncode(Request.QueryString["tx"].ToString()); 

    This ensures that any HTML-related characters are encoded to their unexecutable values.

  • String filter injection . This string is actually vulnerable to row-string injection, not SQL injection:

     dv.RowFilter = "Description LIKE ('%" + Request.QueryString["tx"].Trim().ToLower() + "%') or Title LIKE ('%" + Request.QueryString["tx"].Trim().ToLower() + "%')"; 

    As you probably know, the syntax is based on SQL, but in this case there is no database, only a string filtering mechanism that is vulnerable to injection attacks. This injection is a problem with a low degree of severity, since it does not allow an attacker to do much (not like executing a command in a real SQL injection), but if your end user cannot see all the rows of the table, this is a security problem. There are no parameterized queries, such as a mechanism to prevent injection here, for example, in SQL Injection, as I know, but providing a thorough input check mentioned in section 1 and the next section would also solve this problem.

    / li>
  • Insufficient understanding of client concept \ Javascript validation . Client-side validations of any kind are enjoyable and cannot be trusted . The one who showed you this method showed exactly the reason. Any client-side check can always easily bypass any proxy utility (Burp, Fiddler, Paros, etc.) and even use a debugger or browser plug-ins (press F12 to activate the Firefox Firebug debugger - one example of such a plugin that improves the debugger default). To trust only a client-side check, it looks like you are passing your house keys to a stranger asking him to check if someone is trying to suspiciously intervene or hide your keys under a welcome sign. You cannot trust this as your only defense. The only valid purpose of client-side validation is to prevent a trip to the server and improve user experience. You must implement the same whitelist based check you created in JS and in the server side code. Always remember: server-side validation β€” mandatory client-side validation β€” nice to have.

Hopes this helps.

+1
source

Like any value provided by the user, you need to avoid the value when it is presented on the page.

Refresh search.aspx to use HttpUtility.HtmlEncode(tx) anywhere the value passed as the tx parameter is emitted.

OWASP provides some good recommendations for protecting against XSS vulnerabilities like this. https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

0
source

If you are interested in ensuring the security of your site, it is best to check the correctness of the request on the page:

 <@ Page validateRequest="true" %> 

Follow the link if you want to enable it on your website:

http://msdn.microsoft.com/en-us/library/hh882339(v=vs.110).aspx

If you want to continue a more reliable verification, then encoding the data before displaying on the web page will be fine.

You can also download the Microsoft AntiXss library from http://www.microsoft.com/en-us/download/details.aspx?id=28589 . This will allow you to protect your site as well as for what you want.

Hope this helps.

0
source

It seems to me that you have two options. The first is to parse the dangerous search side in your jQuery code before sending this text input to the server. I'm not sure exactly what you were looking for, but I assume that you want the user to not send certain things in your search bar.

A good way to prevent this would be to search for certain things in their search. For example, you can wrap a function to send a search to the server in an if statement (sorry for the pseudo-code):

 if(txtinput.indexOf('<script>') === -1 && ...more checks...){ // send input to server } 

These if statements can be bound so that you can check for any XSS problems before sending them to the server. However, this approach is not very attractive in terms of system design. As you said, the best approach is to make this server side. I am not very familiar with the .NET backend, but based on the code you included, I assume that you can parse the txtSearch.text server. This will be similar to the answer above. In fact, you only redirect this link if their text input meets certain conditions.

Unfortunately, I'm not very good at parsing and validating in .NET, so I can't give you the code, but it should look something like this if you wrote the isValid function.

 if(isValid(txtSearch.txt)){ Response.Redirect("search.aspx?tx=" + txtSearch.Text); } else { // Send Error code in response } 

Hope this helps a bit!

-1
source

Source: https://habr.com/ru/post/1206779/


All Articles