This rule is designed to prevent Cross-Site Scripting (XSS) attacks, which occur when an application includes untrusted data in a new web page without proper validation or escaping. XSS attacks allow attackers to execute scripts in the victim’s browser, which can lead to a variety of malicious outcomes such as stealing sensitive data or performing actions on behalf of the user.
The importance of this rule lies in the potential for significant security breaches. XSS attacks can lead to unauthorized access, data theft, and other serious consequences. Therefore, it is crucial to ensure that your C# code is not susceptible to such vulnerabilities.
Good coding practices to avoid XSS attacks include always encoding user input before including it in HTML content, using functions like HtmlEncoder.Default.Encode or HttpUtility.HtmlEncode. Avoid using methods that might introduce vulnerabilities, such as Html.Raw or direct Response.Write with user input. Even when the input comes from a seemingly trusted source, it’s still a good idea to encode it, as it might contain dangerous payloads that were injected earlier.
Non-Compliant Code Examples
usingMicrosoft.AspNetCore.Mvc;usingSystem.Web;namespaceVulnerableApp{publicclassVulnerableController:Controller{ [HttpGet("/profile")]publicIActionResultShowProfile(stringusername){// Non-compliant: Unencoded user input in ContentreturnContent("<div>Hello, "+username+"</div>","text/html");} [HttpGet("/comment")]publicIActionResultShowComment(stringcomment){// Non-compliant: Html.Raw with user inputViewBag.UserComment=Html.Raw(comment);returnView();} [HttpGet("/search")]publicIActionResultSearch(stringquery){// Non-compliant: Direct Response.Write with user inputResponse.ContentType="text/html";Response.Write("<h2>Search results for: "+query+"</h2>");returnnewEmptyResult();}}}
Compliant Code Examples
usingMicrosoft.AspNetCore.Mvc;usingSystem.Web;usingSystem.Text.Encodings.Web;namespaceSecureApp{publicclassSecureController:Controller{ [HttpGet("/user-profile")]publicIActionResultShowUserProfile(stringusername){// Compliant: Using HTML encodingreturnContent("<div>Hello, "+HtmlEncoder.Default.Encode(username)+"</div>","text/html");// Also compliant: Using HttpUtility// return Content("<div>Hello, " + HttpUtility.HtmlEncode(username) + "</div>", "text/html");} [HttpGet("/welcome")]publicIActionResultWelcome(stringname){// Compliant: Static string without user inputreturnContent("<h1>Welcome to our site!</h1>","text/html");} [HttpGet("/product")]publicIActionResultShowProduct(intid){stringproductName=GetProductName(id);// From database, not user input// Compliant: Values from trusted sourcesViewBag.ProductName=productName;returnView();}}}
원활한 통합. Datadog Code Security를 경험해 보세요
Datadog Code Security
이 규칙을 사용해 Datadog Code Security로 코드를 분석하세요
규칙 사용 방법
1
2
rulesets:- csharp-security # Rules to enforce C# security.
리포지토리 루트에 위의 내용을 포함하는 static-analysis.datadog.yml을 만듭니다
무료 IDE 플러그인을 사용하거나 CI 파이프라인에 Code Security 검사를 추가합니다