# 弱點掃描相關處理 ###### tags: `CSRF` `OWASP` ### Absence of Anti-CSRF Tokens #### View form 要加上 @Html.AntiForgeryToken() ``` <form> @Html.AntiForgeryToken() ......... </form> ``` #### Cntroller 要加上 [ValidateAntiForgeryToken] ``` [HttpPost] [ValidateAntiForgeryToken] public IActionResult Search(string Keyword) { } ``` #### AJAX 使用AJAX呼叫時加上 ``` beforeSend: function (xhr) { //for CSRF xhr.setRequestHeader("requestverificationtoken", $('input:hidden[name="__RequestVerificationToken"]').val()); } ``` ``` $.ajax({ url: url, type: "post", async: false, data: { 'key1': value, 'key2': value, }, beforeSend: function (xhr) { //for CSRF xhr.setRequestHeader("requestverificationtoken", $('input:hidden[name="__RequestVerificationToken"]').val()); }, success: function (result) { }, error: function () { } }); ``` ### CSP相關 在Startup.cs中加入,以利在response header加入相關標頭 ``` app.Use(async (context, next) => { var rng = new RNGCryptoServiceProvider(); var nonceBytes = new byte[32]; rng.GetBytes(nonceBytes); var nonce = Convert.ToBase64String(nonceBytes); context.Items["ScriptNonce"] = nonce; context.Response.Headers.Add( "Content-Security-Policy", "object-src 'self';" + "font-src 'self' 'unsafe-inline' data: https:;" + "img-src https://maps.google.com 'self' data: maps.gstatic.com *.googleapis.com *.ggph;" + "style-src 'self' 'unsafe-inline';" + "style-src-elem 'self' 'unsafe-inline' https:;" + "script-src 'self' maps.googleapis.com https:;" + "connect-src 'self';" + "frame-src 'none';" + "default-src 'self';" + "frame-ancestors 'none';" ); context.Response.Headers.Add("X-Content-Type-Options", "nosniff"); context.Response.Headers.Add("X-Frame-Options", "DENY"); context.Response.Headers.Add("X-Xss-Protection", "1"); context.Response.Headers.Add("Referrer-Policy", "no-referrer"); context.Response.Headers.Add("Permissions-Policy", "geolocation=(), microphone=()"); await next(); }); ``` ### X-Content-Type-Options Header Missing 在Startup.cs中加入,以利在response header加入相關標頭 ``` app.Use(async (context, next) => { context.Response.Headers.Add("X-Frame-Options", "DENY"); context.Response.Headers.Add("X-Content-Type-Options", "nosniff"); await next(); }); ``` ### Missing Anti-clickjacking Header 在Startup.cs中加入,以利在response header加入相關標頭 ``` app.Use(async (context, next) => { context.Response.Headers.Add("X-Frame-Options", "DENY"); await next(); }); ``` ### Cookie Without Secure Flag 在Startup.cs中加入,Secure = CookieSecurePolicy.Always ``` app.UseCookiePolicy( new CookiePolicyOptions { Secure = CookieSecurePolicy.Always, HttpOnly = HttpOnlyPolicy.Always }); ```