Escaping
Text from a user must never be put into HTML, a URL, JavaScript, JSON, XML, a regular expression or SQL as it is. Each place has its own special characters and its own encoder. This lesson shows the tool for each place and the attack that it stops.
What you will learn#
- why text must be encoded for the place where it goes,
- HTML:
WebUtility.HtmlEncodeandHtmlEncoder, - URLs:
UrlEncoder, - JavaScript:
JavaScriptEncoder, - JSON:
JsonEncodedText, - XML:
XElementescapes for you, - regular expressions:
Regex.Escape, - SQL: parameters, never joined text.
The rule#
A text has no meaning by itself; the place gives it one. <b> is just letters in a text file and a command in an HTML page. If the text of a visitor reaches a place without being encoded, the visitor can write commands for that place: a script that runs in other people's browsers (cross-site scripting), SQL that reads your whole database (SQL injection). The defense is always the same: encode for the place where the text goes, with a tool that knows that place.
| Place | Danger | Tool |
|---|---|---|
| HTML | <, >, &, quotes | WebUtility.HtmlEncode, HtmlEncoder |
| URL | &, =, space, non-ASCII | UrlEncoder |
| JavaScript string | quotes, </script> | JavaScriptEncoder |
| JSON | quotes, new lines | JsonEncodedText, or a JSON class |
| XML | <, & | XElement |
| regular expression | . + * ( ) [ ] | Regex.Escape |
| SQL | ' and everything else | parameters |
The program#
# escaping - the right encoding for the right place (HTML, URL, JavaScript, JSON, XML, regular expressions and SQL)
load "dotnet.ring"
using {
"System"
"System.Net"
"System.Text.Encodings.Web"
"System.Text.Json"
"System.Text.RegularExpressions"
"System.Xml.Linq"
"RingDotNet.Data"
}
func main
# A text from a user can contain characters that mean something in the place where you put it. The rule: ENCODE FOR THE PLACE.
cText = "<script>alert('x & y')</script>"
# 1. HTML: < > & and quotes become entities, so the browser shows the text and does not run it. WebUtility is the quick tool;
# HtmlEncoder (System.Text.Encodings.Web) is the stricter one used by ASP.NET.
? "1. text : " + cText
? " WebUtility.HtmlEncode : " + new WebUtility().HtmlEncode(cText)
? " HtmlEncoder : " + new HtmlEncoder().Default.Encode(cText)
? " and back (HtmlDecode) : " + new WebUtility().HtmlDecode("<b> & "q" é")
# 2. A page made with and without encoding: the first one lets the visitor run a script
cName = "Ann<img src=x onerror=alert(1)>"
? nl + "2. unsafe page: <h1>Hello " + cName + "</h1>"
? " safe page : <h1>Hello " + new WebUtility().HtmlEncode(cName) + "</h1>"
# 3. URL: spaces, &, =, / and non-ASCII letters become %XX. Encode each VALUE of a query string, never the whole address.
? nl + "3. a query value: q=" + new UrlEncoder().Default.Encode("rock & roll/é")
# 4. JavaScript: a text inside a script string: quotes and < become \uXXXX, so "</script>" can not end the script early
? nl + "4. JavaScript string: '" + new JavaScriptEncoder().Default.Encode('say "hi" <b>') + "'"
# 5. JSON: quotes, new lines and tabs get a backslash. JsonEncodedText does it; better, let a JSON class write the whole document.
cJsonText = 'line one' + nl + 'tab' + char(9) + 'a "quote"'
? nl + "5. JSON string: " + new JsonEncodedText().Encode(cJsonText).ToString()
# 6. XML: XElement escapes for you. Never build XML by adding strings.
oNote = new XElement("note",cText)
? nl + "6. XML element: " + oNote.ToString()
# 7. Regular expressions: characters like + . * ( ) have a meaning. Regex.Escape makes a text that matches ITSELF.
cLiteral = "1+1=2 (a.b)*"
cPattern = new Regex("x").Escape(cLiteral)
? nl + "7. the pattern for the literal text: " + cPattern + "; it matches the text: " + yesNo(new Regex(cPattern).IsMatch("so 1+1=2 (a.b)* is true"))
# 8. SQL: NEVER join user text into a SQL statement. A parameter is sent separately from the SQL, so it can never become SQL.
aSchema = [["People",[["Id","int",1],["Name","string",0]]]]
oDb = new RingDatabase("Data Source=:memory:",aSchema)
oDb.insert("People",[["Name","Ann"]])
oDb.insert("People",[["Name","Bob"]])
cAttack = "x' OR '1'='1"
aWithParameter = oDb.where("People","Name = {0}",[cAttack])
? nl + "8. the attack text '" + cAttack + "' as a parameter finds " + len(aWithParameter) + " rows (it is only a name that nobody has)"
? " the same text joined into the SQL would be: SELECT ... WHERE Name = '" + cAttack + "' -> every row"
oDb.close()
func yesNo lValue
if lValue
return "yes"
ok
return "no"1. text : <script>alert('x & y')</script>
WebUtility.HtmlEncode : <script>alert('x & y')</script>
HtmlEncoder : <script>alert('x & y')</script>
and back (HtmlDecode) : <b> & "q" é
2. unsafe page: <h1>Hello Ann<img src=x onerror=alert(1)></h1>
safe page : <h1>Hello Ann<img src=x onerror=alert(1)></h1>
3. a query value: q=rock%20%26%20roll%2F%C3%A9
4. JavaScript string: 'say \u0022hi\u0022 \u003Cb\u003E'
5. JSON string: line one\ntab\ta \u0022quote\u0022
6. XML element: <note><script>alert('x & y')</script></note>
7. the pattern for the literal text: 1\+1=2\ \(a\.b\)\*; it matches the text: yes
8. the attack text 'x' OR '1'='1' as a parameter finds 0 rows (it is only a name that nobody has)
the same text joined into the SQL would be: SELECT ... WHERE Name = 'x' OR '1'='1' -> every rowHow it works#
HTML#
HtmlEncode replaces <, >, & and quotes by entities (<, &, …). The browser then shows <script> instead of running it. Step 2 puts the same name into a page twice: without encoding, the onerror handler would run in the visitor's browser. HtmlEncoder.Default.Encode (namespace System.Text.Encodings.Web) is the stricter encoder that ASP.NET uses; the two differ in details such as ' against '. HtmlDecode reverses the encoding.
URL, JavaScript, JSON#
UrlEncoder turns space, &, / and non-ASCII letters into %XX; encode each value, not the whole address (the tutorial URLs and encodings). JavaScriptEncoder writes quotes and < as \u0022 and \u003C, so a text inside a script cannot close the string or the script tag. JsonEncodedText.Encode gives \n, \t and \u0022; for a whole document build a JsonObject (the tutorial JSON as a tree) and let it write the text.
XML#
XElement stores the text and writes it with the correct escapes (<script>) when you call ToString() (the tutorial XML in depth). Never build XML by joining strings.
Regular expressions#
A user who searches for 1+1=2 (a.b)* means those characters, not a pattern. Regex.Escape puts a backslash in front of each special character, and the escaped pattern matches the text itself. (The instance new Regex("x") is only used to reach the static method.)
SQL#
oDb.where("People","Name = {0}",[cAttack]) sends the text as a parameter: the database receives the statement and the value separately, so the value can never become part of the statement. The attack text x' OR '1'='1 finds no rows. If you had written "Name = '" + cAttack + "'", the statement would read Name = 'x' OR '1'='1' and return every row. This is the most important line of the lesson: never join user text into SQL.
Encoding is for output. It does not replace checking input (a number must be a number, a name must have a sensible length) and it does not make a text safe for a different place: HTML-encoded text is not URL-safe. Encode at the moment you put the text into the place, and only once.
What you learned#
- text is encoded for the place,
WebUtility,HtmlEncoder,UrlEncoder,JavaScriptEncoder,JsonEncodedText,Regex.Escape,XElementescapes by itself,- SQL parameters stop injection.
Exercises#
- Make the tiny web site of the tutorial A small web site safe: where does it show a visitor's text?
- Write a function
link(cText, cAddress)that builds<a href="…">…</a>with the right encoding for the address and for the text. - Search a text file for a phrase that the user types, using
Regex.Escape. - Try the attack text
'; DROP TABLE People; --as a parameter and check that the table is still there.