locked
Cross site scripting RRS feed

  • Question

  • User34108037 posted

    I am working on fixing cross site scripting in my website. I have a telerik editor control in my webform.

    While saving editor content, am encoding the html content and then I have to decode only the valid tags before displaying in the browser(As Microsoft recommendation). for example.

    If i am giving the following input.

    <p>test</p>
    <p style='color:red'>test1</p><script>alert('1');</script>

    My encoded content will be

    &lt;p&gt;test&lt;/p&gt;
    &lt;p style='color:red'&gt;test1&lt;/p&gt;&lt;script&gt;alert('1');&lt;/script&gt;

    Before displaying this content in my browser, I have to decode the valid tags again, ie paragraph tag in this case. so that script tag wont execute in my browser. Below is the expected one.

    <p>test</p>
    <p style='color:red'>test1</p>&lt;script&gt;alert('1');&lt;/script&gt;

    But i can able to replace para tag easily if it dont have any attributes like below.

    "&lt;p&gt;" --> "<p>"

    "&lt;/p&gt;" --> "</p>" 

     i am struggling in replacing the paragraph tag if it have some attributes.  Can anyone help me to replace the below one.

    &lt;p style='color:red'&gt; --> <p style='color:red'>

    Suresh.

    Monday, August 12, 2013 8:39 AM

Answers

  • User-837620913 posted

    For something advanced like that, you should check out the Html Agility Pack: http://htmlagilitypack.codeplex.com/

    You can strip out script tags like this:

    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    doc.LoadHtml(yourHtmlStringHere);
    
    doc.DocumentNode.Descendants()
                    .Where(n => n.Name == "script")
                    .ToList()
                    .ForEach(n => n.Remove());

    You can easily replace instead of remove.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 12, 2013 3:17 PM