Skip to content

Commit

Permalink
Adding xss sanitizer attribute (#71)
Browse files Browse the repository at this point in the history
* 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
Nechelovek and Батура Иван committed Feb 19, 2024
1 parent 770d7cc commit 26229a3
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
44 changes: 44 additions & 0 deletions ATI.Services.Common/Xss/Attribute/XssSanitizerAttribute.cs
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;
}
}
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,16 @@ app.UseXssValidation();
[XssValidate]
```

#### Аттрибут XssSanitizer
Атрибут который экранирует Xss, либо выдает ошибку на моменте валидации модели. Атрибут добавляется к полям.
Чтобы валидации прошла, на метод, в котором требуется валидации модели с аттрибутом `XssSanitizer` нужно добавить аттрибут
```csharp
[ValidateModelState]
```
По умолчанию атрибут будет эранировать xss. Для того чтобы была ошибка на моменте валидации, нужно передать параметр в атрибут следующим образом
```csharp
[XssSanitizer(IsReplace = false)]
```



0 comments on commit 26229a3

Please sign in to comment.