-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adding xss sanitizer attribute (#71)
* Adding xss sanitizer attribute * Update readme file with instruction how to use XssSanitizer * Replace special symbol for sanitize * Change char symbol to string --------- Co-authored-by: Батура Иван <batura.i@MacBook-Pro-Komov.local>
- Loading branch information
1 parent
770d7cc
commit 26229a3
Showing
2 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
44 changes: 44 additions & 0 deletions
44
ATI.Services.Common/Xss/Attribute/XssSanitizerAttribute.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
using System; | ||
using System.ComponentModel.DataAnnotations; | ||
using Ganss.Xss; | ||
|
||
namespace ATI.Services.Common.Xss.Attribute; | ||
|
||
/// <summary> | ||
/// Валидирует поле на наличие недопустимых символов | ||
/// </summary> | ||
public class XssSanitizerAttribute : ValidationAttribute | ||
{ | ||
/// <summary> | ||
/// Экранировать XSS и отдавать success | ||
/// </summary> | ||
/// <value>true - экранирует XSS </value> | ||
/// <value>false - возвращает, что модель не валидна</value>> | ||
public bool IsReplace { get; set; } = true; | ||
|
||
private static readonly HtmlSanitizer Sanitizer = new (); | ||
|
||
protected override ValidationResult IsValid(object value, ValidationContext context) | ||
{ | ||
var rawValue = value as string; | ||
if (rawValue == null) | ||
return ValidationResult.Success; | ||
|
||
// Реплейсим спец. символ, потому что санитайзер его считает за xss | ||
rawValue = rawValue | ||
.Replace("\r", String.Empty) | ||
.TrimStart(); | ||
|
||
var sanitised = Sanitizer.Sanitize(rawValue); | ||
|
||
if (sanitised != rawValue) | ||
{ | ||
if (!IsReplace) | ||
return new ValidationResult("Xss was detected"); | ||
|
||
context.ObjectType.GetProperty(context.MemberName) | ||
?.SetValue(context.ObjectInstance, sanitised); | ||
} | ||
return ValidationResult.Success; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters