Sanitize Razor syntax in the template to be used as layout

Here is the script. We currently store Razor templates on disk for the CMS multi-user system. We need the ability for admins in a multi-user system to upload their own website templates (layouts), but we must be sure that they will not contain Razor markup, which could potentially be harmful.

In fact, we want to be able to encode any Razor syntax that could be included in the client template.

Sentence:
Allow administrators to upload a template that is decorated with approved tags using a secure template system such as dotliquid .
When booting, first replace all β€œ@” characters with β€œ@@” to avoid any Razor syntax . Then replace the approved tags with the appropriate Razor markup and save the template in the database.
Downloading this page will use a custom VirtualPathProvider - out of scope for this question ...

Questions

  • If I just replaced all the signs β€œ@” with β€œ@@”, does it effectively β€œencode” all the razor markup that could exist in the template?
  • Are there any problems if the template contains the legal signs "@", for example, in the email address or on Twitter? My initial tests show that double escape works.

UPDATE

My tests show that escaping all the @ signs with a different @ sign will sanitize the pattern, avoiding the Razor syntax. But I would like to hear from someone who may have a deeper knowledge on this subject.

+4
source share
1 answer

1) Writing a function to enter the razor code with @ to prevent razor injection is a kind of hacker solution. It’s like adding icing to a burnt house to make it better. Why not just prevent it in the first place?

Instead, try this in the appropriate view:

<%=Html.Encode(feedback.Message)%> 

or add

 <text> ... </text> 

to the inputs before they become processes.

2) If you can guarantee that it is a legitimate email address, then everything will be fine. But it is difficult to guarantee. Therefore, I suggest that you use simple but effective email validation using JavaScript regex. This is a logical function that you can put in your JavaScript to check email (this regular expression has a success rate of ~ 95%):

 function isValidEmailAddress(emailAddress) { var emailPattern = new RegExp(/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[az][az])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i); return emailPattern.test(emailAddress); } 
-1
source

Source: https://habr.com/ru/post/1485448/


All Articles