-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathHtmlValidator.cs
499 lines (421 loc) · 19.6 KB
/
HtmlValidator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.RegularExpressions;
using GalleryServerPro.Business.Interfaces;
namespace GalleryServerPro.Business
{
/// <summary>
/// Provides functionality for validating and cleaning HTML.
/// </summary>
public class HtmlValidator : IHtmlValidator
{
#region Private Fields
private static readonly Regex _jsAttributeRegex = new Regex("javascript:", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
private static readonly Regex _scriptTag = new Regex("<script[\\w\\W]*?</script>", RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
private static readonly TagRegex _startTag = new TagRegex();
private static readonly EndTagRegex _endTag = new EndTagRegex();
private static readonly TextRegex _innerContentRegEx = new TextRegex();
private readonly string _originalHtml;
private string _dirtyHtml;
private readonly StringBuilder _cleanHtml;
private readonly string[] _allowedTags;
private readonly string[] _allowedAttributes;
private readonly bool _allowJavascript;
private bool _invalidJavascriptDetected;
private readonly List<string> _invalidHtmlTags = new List<string>();
private readonly List<string> _invalidHtmlAttributes = new List<string>();
private bool _validateHasExecuted;
#endregion
#region Properties
/// <summary>
/// Gets the list of HTML tags found in the user-entered input that are not allowed. This property is set after
/// the <see cref="Validate"/> method is invoked. Guaranteed to not be null.
/// </summary>
/// <value>
/// The list of HTML tags found in the user-entered input that are not allowed.
/// </value>
public List<string> InvalidHtmlTags
{
get { return this._invalidHtmlTags; }
}
/// <summary>
/// Gets the list of HTML attributes found in the user-entered input that are not allowed. This property is set after
/// the <see cref="Validate"/> method is invoked. Guaranteed to not be null.
/// </summary>
/// <value>
/// The list of HTML attributes found in the user-entered input that are not allowed.
/// </value>
public List<string> InvalidHtmlAttributes
{
get { return this._invalidHtmlAttributes; }
}
/// <summary>
/// Gets a value indicating whether invalid javascript was detected in the HTML. This property is set after
/// the <see cref="Validate"/> method is invoked. Returns <c>true</c> only when the configuration setting
/// allowUserEnteredJavascript is <c>false</c> and either a script tag or the string "javascript:" is detected.
/// </summary>
/// <value>
/// <c>true</c> if invalid javascript is detected; otherwise, <c>false</c>.
/// </value>
public bool InvalidJavascriptDetected
{
get { return this._invalidJavascriptDetected; }
}
/// <summary>
/// Gets a value indicating whether any invalid HTML tags, attributes, or javascript was found in the HTML.
/// </summary>
/// <value>
/// <c>true</c> if invalid HTML tags, attributes, or javascript was found; otherwise, <c>false</c>.
/// </value>
public bool IsValid
{
get
{
if (!this._validateHasExecuted)
throw new InvalidOperationException("You must call the Validate method before accessing the IsValid property.");
if (this._allowJavascript)
return ((this.InvalidHtmlTags.Count == 0) && (this.InvalidHtmlAttributes.Count == 0));
else
return ((this.InvalidHtmlTags.Count == 0) && (this.InvalidHtmlAttributes.Count == 0) && !this._invalidJavascriptDetected);
}
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="HtmlValidator"/> class.
/// </summary>
/// <param name="html">The text to be cleaned. May be null.</param>
/// <param name="allowedHtmlTags">The HTML tags that are allowed in <paramref name="html"/>. May be null.</param>
/// <param name="allowedHtmlAttributes">The HTML attributes that are allowed in <paramref name="html"/>. May be null.</param>
/// <param name="allowJavascript">If set to <c>true</c> allow script tag and the string "javascript:". Note that
/// if the script tag is not a member of <paramref name="allowedHtmlTags"/> it will be removed even if this
/// parameter is <c>true</c>.</param>
private HtmlValidator(string html, string[] allowedHtmlTags, string[] allowedHtmlAttributes, bool allowJavascript)
{
#region Validation
if (html == null)
html = String.Empty;
if (allowedHtmlTags == null)
allowedHtmlTags = new string[0];
if (allowedHtmlAttributes == null)
allowedHtmlAttributes = new string[0];
#endregion
this._originalHtml = html;
this._allowedTags = allowedHtmlTags;
this._allowedAttributes = allowedHtmlAttributes;
this._allowJavascript = allowJavascript;
this._cleanHtml = new StringBuilder(this._originalHtml.Length);
}
#endregion
#region Public Methods
/// <summary>
/// Evaluates the HTML for invalid tags, attributes, and javascript. After executing this method the <see cref="IsValid"/>
/// property can be checked. If this property is <c>true</c>, the properties <see cref="InvalidHtmlTags"/>,
/// <see cref="InvalidHtmlAttributes"/>, and <see cref="InvalidJavascriptDetected"/> can be inspected for details.
/// </summary>
public void Validate()
{
this._invalidHtmlTags.Clear();
this._invalidHtmlAttributes.Clear();
Clean();
_validateHasExecuted = true;
}
#endregion
#region Public Static Methods
/// <summary>
/// Initializes a new instance of the <see cref="HtmlValidator"/> class with the specified parameters.
/// </summary>
/// <param name="html">The text to be cleaned.</param>
/// <param name="galleryId">The gallery ID. This is used to look up the appropriate configuration values for the gallery.</param>
/// <returns>Returns an instance of <see cref="HtmlValidator"/>.</returns>
public static IHtmlValidator Create(string html, int galleryId)
{
IGallerySettings gallerySetting = Factory.LoadGallerySetting(galleryId);
return new HtmlValidator(html, gallerySetting.AllowedHtmlTags, gallerySetting.AllowedHtmlAttributes, gallerySetting.AllowUserEnteredJavascript);
}
/// <summary>
/// Removes potentially dangerous HTML and Javascript in <paramref name="html"/>. If the configuration
/// setting <see cref="IGallerySettings.AllowUserEnteredHtml" /> is true, then the input is cleaned so that all
/// HTML tags that are not in a predefined list are HTML-encoded and invalid HTML attributes are deleted. If
/// <see cref="IGallerySettings.AllowUserEnteredHtml" /> is false, then all HTML tags are deleted. If the setting
/// <see cref="IGallerySettings.AllowUserEnteredJavascript" /> is true, then script tags and the text "javascript:"
/// is allowed. Note that if script is not in the list of valid HTML tags defined in <see cref="IGallerySettings.AllowedHtmlTags" />,
/// it will be deleted even when <see cref="IGallerySettings.AllowUserEnteredJavascript" /> is true. When the setting
/// is false, all script tags and instances of the text "javascript:" are deleted.
/// </summary>
/// <param name="html">The string containing the HTML tags.</param>
/// <param name="galleryId">The gallery ID. This is used to look up the appropriate configuration values for the gallery.</param>
/// <returns>
/// Returns a string with potentially dangerous HTML tags deleted.
/// </returns>
public static string Clean(string html, int galleryId)
{
IGallerySettings gallerySetting = Factory.LoadGallerySetting(galleryId);
if (gallerySetting.AllowUserEnteredHtml)
{
HtmlValidator scrubber = new HtmlValidator(html, gallerySetting.AllowedHtmlTags, gallerySetting.AllowedHtmlAttributes, gallerySetting.AllowUserEnteredJavascript);
return scrubber.Clean();
}
else
{
// HTML not allowed. Pass in empty variables for the valid tags and attributes.
HtmlValidator scrubber = new HtmlValidator(html, null, null, gallerySetting.AllowUserEnteredJavascript);
return scrubber.Clean();
}
}
/// <summary>
/// Remove all HTML tags and javascript from the specified string. If <paramref name="escapeQuotes"/> is <c>true</c>, then all
/// apostrophes and quotation marks are replaced with " and ' so that the string can be specified in HTML
/// attributes such as title tags.
/// </summary>
/// <param name="html">The string containing HTML tags to remove.</param>
/// <param name="escapeQuotes">When true, all apostrophes and quotation marks are replaced with " and '.</param>
/// <returns>Returns a string with all HTML tags removed, including the brackets.</returns>
public static string RemoveHtml(string html, bool escapeQuotes)
{
HtmlValidator scrubber = new HtmlValidator(html, null, null, false);
string cleanHtml = scrubber.Clean();
if (escapeQuotes)
{
cleanHtml = cleanHtml.Replace("\"", """);
cleanHtml = cleanHtml.Replace("'", "'");
}
return cleanHtml;
}
#endregion
#region Private Functions
/// <summary>
/// Remove invalid HTML tags, attributes, and javascript from the HTML.
/// </summary>
/// <returns>Returns a string consisting of clean HTML.</returns>
private string Clean()
{
int dirtyHtmlIndex = 0;
bool foundFirstTag = false;
if (this._allowJavascript)
this._dirtyHtml = this._originalHtml;
else
this._dirtyHtml = DeleteScriptTags(this._originalHtml);
while (dirtyHtmlIndex < this._dirtyHtml.Length)
{
// Look for start tag and process if we find it.
Match tagMatch = _startTag.Match(this._dirtyHtml, dirtyHtmlIndex);
if (tagMatch.Success)
{
foundFirstTag = true;
// Increment our index the length of the tag.
dirtyHtmlIndex = tagMatch.Index + tagMatch.Length;
// Process the start tag. The method might increment our index if there is content after this tag.
dirtyHtmlIndex = this.ProcessStartTag(tagMatch, dirtyHtmlIndex);
continue;
}
// Look for end tag and process if we find it.
tagMatch = _endTag.Match(this._dirtyHtml, dirtyHtmlIndex);
if (tagMatch.Success)
{
// Increment our index the length of the tag.
dirtyHtmlIndex = tagMatch.Index + tagMatch.Length;
// Process the end tag. The method might increment our index if their is content after this tag.
dirtyHtmlIndex = this.ProcessEndTag(tagMatch, dirtyHtmlIndex);
continue;
}
if (!foundFirstTag)
{
// We haven't encountered an HTML tag yet, so append the current character.
this._cleanHtml.Append(this._dirtyHtml.Substring(dirtyHtmlIndex, 1));
}
dirtyHtmlIndex++;
}
return this._cleanHtml.ToString();
}
/// <summary>
/// Scrub the specified <paramref name="tagMatch"/> of invalid HTML tags, attributes, and javascript. The tag will be
/// either a starting tag (e.g. <p>) or a single tag (e.g. <br />).
/// </summary>
/// <param name="tagMatch">A <see cref="Match"/> resulting from passing a string containing HTML to an instance of
/// <see cref="TagRegex"/>.</param>
/// <param name="index">The position within the original HTML where the <paramref name="tagMatch"/> ends.</param>
/// <returns>The position within the original HTML after the <paramref name="tagMatch"/> and any text that occurs
/// after it. It can be used by the calling code for looking for the next match.</returns>
private int ProcessStartTag(Match tagMatch, int index)
{
string tagName = tagMatch.Groups["tagname"].Value.ToLowerInvariant();
if (Array.IndexOf<string>(this._allowedTags, tagName) >= 0)
{
// This tag is valid. Clean the attributes and append to our output.
_cleanHtml.Append(RemoveInvalidAttributes(tagMatch, this._allowedAttributes, this._invalidHtmlAttributes));
}
else
{
// Invalid tag. Call RemoveInvalidAttributes so that we can get our list of invalid attributes updated.
RemoveInvalidAttributes(tagMatch, this._allowedAttributes, this._invalidHtmlAttributes);
// Add to list of invalid tags if not already there
if (!this._invalidHtmlTags.Contains(tagName))
this._invalidHtmlTags.Add(tagName);
}
// Add any text between this start tag and the beginning of the next tag.
Match contentMatch = _innerContentRegEx.Match(_dirtyHtml, index);
if (contentMatch.Success)
{
_cleanHtml.Append(contentMatch.Value);
// Increment our index so that when we search for the next tag we do it after the content we just found.
index = contentMatch.Index + contentMatch.Length;
}
return index;
}
/// <summary>
/// Scrub the specified <paramref name="tagMatch"/> of invalid HTML tags, attributes, and javascript. The tag will be
/// an ending tag (e.g. </p>).
/// </summary>
/// <param name="tagMatch">A <see cref="Match"/> resulting from passing a string containing HTML to an instance of
/// <see cref="TagRegex"/>.</param>
/// <param name="index">The position within the original HTML where the <paramref name="tagMatch"/> ends.</param>
/// <returns>The position within the original HTML after the <paramref name="tagMatch"/> and any text that occurs
/// after it. It can be used by the calling code for looking for the next match.</returns>
private int ProcessEndTag(Match tagMatch, int index)
{
if (Array.IndexOf<string>(this._allowedTags, tagMatch.Groups["tagname"].Value.ToLowerInvariant()) >= 0)
{
_cleanHtml.Append(tagMatch.Value);
}
// Add any text between this end tag and the beginning of the next tag.
Match contentMatch = _innerContentRegEx.Match(_dirtyHtml, index);
if (contentMatch.Success)
{
_cleanHtml.Append(contentMatch.Value);
// Increment our index so that when we search for the next tag we do it after the content we just found.
index = contentMatch.Index + contentMatch.Length;
}
return index;
}
/// <summary>
/// Removes HTML attributes and their values from the HTML string in <paramref name="tagMatch"/> if they do not exist in
/// <paramref name="allowedAttributes"/>. Any invalid attributes are added to <paramref name="invalidHtmlAttributes"/>.
/// </summary>
/// <param name="tagMatch">A <see cref="Match"/> resulting from passing a string containing HTML to an instance of
/// <see cref="TagRegex"/>.</param>
/// <param name="allowedAttributes">The HTML attributes that are allowed to be present in the HTML string in
/// <paramref name="tagMatch"/>.</param>
/// <param name="invalidHtmlAttributes">A running list of invalid HTML attributes. Any attributes found to be invalid
/// in <paramref name="tagMatch"/> are added to this list.</param>
/// <returns>Returns the HTML string stored in <paramref name="tagMatch"/> with invalid attributes and their values removed.</returns>
private static string RemoveInvalidAttributes(Match tagMatch, string[] allowedAttributes, ICollection<string> invalidHtmlAttributes)
{
string cleanTag = String.Concat("<", tagMatch.Groups["tagname"].Value.ToLowerInvariant());
Group grpAttrName = tagMatch.Groups["attrname"];
Group grpAttrVal = tagMatch.Groups["attrval"];
CaptureCollection attrNameCaptures = grpAttrName.Captures;
CaptureCollection attrValCaptures = grpAttrVal.Captures;
if (attrNameCaptures.Count == attrValCaptures.Count)
{
for (int attValuePairIterator = 0; attValuePairIterator < attrNameCaptures.Count; attValuePairIterator++)
{
if (Array.IndexOf<string>(allowedAttributes, attrNameCaptures[attValuePairIterator].Value.ToLowerInvariant()) >= 0)
{
// Valid attribute. Append attribute/value string to our clean tag.
cleanTag += GetAttValuePair(tagMatch, attValuePairIterator);
}
else
{
if (!invalidHtmlAttributes.Contains(attrNameCaptures[attValuePairIterator].Value.ToLowerInvariant()))
invalidHtmlAttributes.Add(attrNameCaptures[attValuePairIterator].Value.ToLowerInvariant());
}
}
}
cleanTag += ">";
return cleanTag;
}
/// <summary>
/// Gets the attribute="value" string in the <see cref="tagMatch"/> at the specified <see cref="index" />. If the original
/// value was not surrounded by quotation marks or apostrophes, add them, selectively choosing the most appropriate one so
/// as not to interfere with the presence of one or the other in the attribute value. For example, if the attribute value
/// contains an apostrophe, surround it with quotation marks. Includes a leading space. (Example: " class='boldtext'")
/// </summary>
/// <param name="tagMatch">A <see cref="Match"/> resulting from passing a string containing HTML to an instance of
/// <see cref="TagRegex"/>.</param>
/// <param name="index">The index of the attribute within the <see cref="CaptureCollection"/> of <paramref name="tagMatch"/>.</param>
/// <returns>Returns an attribute="value" string with a leading space (Example: " class='boldtext'").</returns>
private static string GetAttValuePair(Match tagMatch, int index)
{
char[] delimiters = new char[] { '\'', '"' };
Capture attrValCapture = tagMatch.Groups["attrval"].Captures[index];
int indexOfAttributeStart = attrValCapture.Index - tagMatch.Index;
// Get the characters at the start and end of the attribute value. Typically this is a quote or apostrophe.
char beginAttValue = tagMatch.Value.Substring(indexOfAttributeStart - 1, 1)[0];
char endAttValue = tagMatch.Value.Substring(indexOfAttributeStart + attrValCapture.Length, 1)[0];
// If one or both characters are not a quote or apostrophe, specify one. If the attribute value contains one,
// then choose the other so as not to interfere.
if (Array.IndexOf(delimiters, beginAttValue) < 0)
beginAttValue = (attrValCapture.Value.Contains("'") ? '"' : '\'');
if (Array.IndexOf(delimiters, endAttValue) < 0)
endAttValue = (attrValCapture.Value.Contains("'") ? '"' : '\'');
return String.Concat(" ", tagMatch.Groups["attrname"].Captures[index].Value, "=", beginAttValue, attrValCapture.Value, endAttValue);
}
///// <summary>
///// HTML-encodes a string and returns the encoded string.
///// </summary>
///// <param name="text">The text string to encode. </param>
///// <returns>The HTML-encoded text.</returns>
//private static string HtmlEncode(string text)
//{
// if (text == null)
// return null;
// StringBuilder sb = new StringBuilder(text.Length);
// int len = text.Length;
// for (int i = 0; i < len; i++)
// {
// switch (text[i])
// {
// case '<':
// sb.Append("<");
// break;
// case '>':
// sb.Append(">");
// break;
// case '"':
// sb.Append(""");
// break;
// case '&':
// sb.Append("&");
// break;
// default:
// if (text[i] > 159)
// {
// // decimal numeric entity
// sb.Append("&#");
// sb.Append(((int)text[i]).ToString(CultureInfo.InvariantCulture));
// sb.Append(";");
// }
// else
// sb.Append(text[i]);
// break;
// }
// }
// return sb.ToString();
//}
/// <summary>
/// Delete any script tag and its content. Delete any instances of the string "javascript:". If javascript
/// is detected, the member variable _javascriptDetected is set to <c>true</c>.
/// </summary>
/// <param name="html">The string to be cleaned of script tags.</param>
/// <returns>
/// Returns <paramref name="html"/> cleaned of script tags.
/// </returns>
private string DeleteScriptTags(string html)
{
int originalLength = html.Length;
// Delete any <script> tags
html = _scriptTag.Replace(html, String.Empty);
// Delete any instances of the string "javascript:"
html = _jsAttributeRegex.Replace(html, String.Empty);
if (html.Length != originalLength)
{
this._invalidJavascriptDetected = true;
}
return html;
}
#endregion
}
}