Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SecurityElement.IsValidText returns true on "&" ... why?

Tags:

c#

xml

asp.net

I have a TextBox that is eventually saved in a xml node. I am using the SecurityElement.Escape(string2Escape) to escape the invalid characters before saving the xml.

Problem: I tried using the IsValidText to test if i need to run the escape method, but it returns ''' and '&' as valid but then when you save the xml the system barfs because they are, in fact, not valid. It seems to only return false on '<' or '>'.

Simple solution, remove the check, but my question is why would this be the case?

The following is my failing code:

private string EscapeXML(string nodeText)
{
    if (!SecurityElement.IsValidText(nodeText))
    {
        return SecurityElement.Escape(nodeText);
    }
    return nodeText;
}
like image 657
lgados Avatar asked Feb 16 '11 15:02

lgados


2 Answers

Here's what I got from Reflector. enter image description hereenter image description here

This can explain why it's behaving the way it's behaving. I don't see any method in SecurityElement that does what your are looking for but it is simple enough to implement one yourself, maybe as an extension method.

like image 152
Bala R Avatar answered Oct 24 '22 17:10

Bala R


The SecurityElement constructor is apparently already doing some escaping on its own (including the "&" character), so the IsValidText seems to be only checking for the characters the constructor is not already taking care of. As a consequence, it doesn't look safe to use the SecurityElement's IsValidText/Escape combo, unless you're using SecurityElement to build the whole xml.

I'll try to explain better with an example:

using System;
using System.Diagnostics;
using System.Security;

class MainClass
{
    public static void Main (string[] args)
    {
        // the SecurityElement constructor escapes the & all by itself 
        var xmlRoot =
            new SecurityElement("test","test &");

        // the & is escaped without SecurityElement.Escape 
        Console.WriteLine (xmlRoot.ToString());

        // this would throw an exception (the SecurityElement constructor
        // apparently can't escape < or >'s
        // var xmlRoot2 =
        //    new SecurityElement("test",@"test & > """);

        // so this text needs to be escaped before construction 
        var xmlRoot3 =
            new SecurityElement("test",EscapeXML(@"test & > """));
        Console.WriteLine (xmlRoot3.ToString());

    }

    private static string EscapeXML(string nodeText)
    {
        return (SecurityElement.IsValidText(nodeText))?
            nodeText :
            SecurityElement.Escape(nodeText);
    }
}
like image 44
Paolo Falabella Avatar answered Oct 24 '22 18:10

Paolo Falabella