I have a string that arrives from the user, and is then inserted into a large CSS block using a CSS parser.
CSS escaping can be done with \C
(where C is a character), \HexOfC
(with a space) or \6DigitHexOfC
.
Generally, all characters can be escaped safely, and CSS would still run as expected. The following works:
div {
background: \23 f66;
}
<div>Test</div>
However, I still want the CSS properties to be as "clean" as possible, because I want, for example, to be able to view URLs and rules cleanly with the inspector.
There are characters which are obviously bad. {};\*
should all be escaped because they can be used to break from the current rule. I am managing a whitelist (everything gets escaped, except for what's allowed) of characters (as opposed to a blacklist where everything is allowed, except for what's not). The whitelisted characters I currently have is
'#', ',', '.', '(', ')', '-', '%', '+', '=', '/', ' ', ':', '\'', '"', '\n', '\r'
Are there dangerous characters here? Anything that can be used to break out of a rule and affect the rest of the CSS block. Are there characters which aren't here which would get unneededly escaped? (Alphanumeric characters are not escaped by default).
CSS escapes. CSS represents escaped characters in a different way. Escapes start with a backslash followed by the hexadecimal number that represents the character's hexadecimal Unicode code point value. If there is a following character that is not in the range A–F, a–f or 0–9, that is all you need.
> and < is a character entity reference for the > and < character in HTML. It is not possible to use the less than (<) or greater than (>) signs in your file, because the browser will mix them with tags. for these difficulties you can use entity names( > ) and entity numbers( < ).
In this context, escaping means to replace them with HTML character entities. For example, < can be replaced with < . Another character entity that's occasionally useful is (the non-breaking space).
Instead of sanitizing input, you could simply allow elements to be transfered.
Basically a client generated structur file:
[
MyDiv: { # Key
background: "#FFFFFF" # Element
}
]
In this case you just have to create a File.
Dummy Code:
StringBuilder sb = new StringBuilder();
foreach(String key: structure.getKeys()) {
final List<Element> e = structure.getElements(key);
sb.append(".") // This may be changed of course
.append(key) // ID or class based on type above
.append("{")
// Append Elements
.append("}");
}
Generating Elements should be easy.
Each element is just
S := element-key : element-value;
Then you'd be able to whitelist special commands too.
If you wish to keep sanitizing, take a look here: http://www.w3.org/TR/CSS21/grammar.html#scanner
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With