[研究]ckeditor 與 Cross-site Scripting (XSS)
2021-09-23
ckeditor 是 Web-Based HTML 所見即所得(What You See Is What You Get,縮寫 WYSIWYG)編輯器,所以有可能被寫入 Cross-site Scripting (XSS)內容。
本篇是一種處理方式
XXX.aspx.cs
using System.Web.Security.AntiXss; Literal2.Text = AntiXssEncoder.HtmlEncode(DataResult.DataContent, true); Literal2.Text = Common.AntiXssHtmlDecode(Literal2.Text); |
Common.cs 內容 (要還原那些東西,請依自己需求調整)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Data; using System.Data.SqlClient; using System.Text.RegularExpressions; using System.Text; using System.Net.Sockets; using System.IO; using System.Net; namespace WebApplication1 { public class Common { public Common() { // // TODO: 在此加入建構函式的程式碼 // } public static string AntiXssHtmlDecode(string inputStr2) { //AntiXssEncoder.HtmlEncode Method //https://docs.microsoft.com/zh-tw/dotnet/api/system.web.security.antixss.antixssencoder.htmlencode?view=netframework-4.8 //它使用白名單,所以除非是允許的字元,其他都被編碼, //因為大於,小於 不在白名單,所以被編碼了,所以 HTML tag 全部失效 //為了HTML tag部分仍有效,還原部分 string inputStr = inputStr2; inputStr = inputStr.Replace(">", ">"); inputStr = inputStr.Replace("</", "</"); inputStr = inputStr.Replace(""", "\""); inputStr = inputStr.Replace("'", "'"); inputStr = inputStr.Replace("&", "&"); inputStr = inputStr.Replace(" ", " "); inputStr = inputStr.Replace("<a", "<A"); inputStr = inputStr.Replace("<A", "<A"); inputStr = inputStr.Replace("<b", "<b"); inputStr = inputStr.Replace("<B", "<B"); inputStr = inputStr.Replace("<c", "<c"); inputStr = inputStr.Replace("<C", "<C"); inputStr = inputStr.Replace("<d", "<d"); inputStr = inputStr.Replace("<D", "<D"); inputStr = inputStr.Replace("<h", "<H"); inputStr = inputStr.Replace("<H", "<H"); inputStr = inputStr.Replace("<i", "<i"); inputStr = inputStr.Replace("<I", "<I"); inputStr = inputStr.Replace("<sp", "<sp"); inputStr = inputStr.Replace("<SP", "<SP"); inputStr = inputStr.Replace("<st", "<st"); inputStr = inputStr.Replace("<ST", "<ST"); inputStr = inputStr.Replace("<t", "<t"); inputStr = inputStr.Replace("<T", "<T"); inputStr = inputStr.Replace("<u", "<u"); inputStr = inputStr.Replace("<U", "<U"); inputStr = inputStr.Replace("<p", "<P"); inputStr = inputStr.Replace("<P", "<P"); string output = inputStr; return output; } } } |
另外下面的方式也可考慮。
NuGet Gallery | HtmlSanitizer 6.0.441
https://www.nuget.org/packages/HtmlSanitizer/
GitHub - mganss/HtmlSanitizer: Cleans HTML to avoid XSS attacks
https://github.com/mganss/HtmlSanitizer
(完)
沒有留言:
張貼留言