Cette page n'est pas encore disponible en français, sa traduction est en cours. Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.
usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.AspNetCore.Http;usingSystem.IO;usingSystem.Web;usingSystem.Text;namespaceControllers{publicclassVulnerableController:Controller{privatereadonlystring_rootPath;publicVulnerableController(stringrootPath){_rootPath=rootPath;} [HttpPost("/path-test")]publicIActionResultPost(){// Get parameter from cookiesstringparam="defaultValue";if(Request.Cookies!=null){foreach(varcookieinRequest.Cookies){if(cookie.Key.Equals("TestCookie")){param=HttpUtility.UrlDecode(cookie.Value,Encoding.UTF8);break;}}}// Vulnerable: User input directly in Path.CombinestringfileName=Path.Combine(_rootPath,"files",param);// Use the unsafe valueFileStreamfs=null;try{fs=newFileStream(fileName,FileMode.Open);// Read file...}catch(Exceptione){// Handle error...}finally{fs?.Close();}returnOk();}}}
Compliant Code Examples
usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.AspNetCore.Http;usingSystem.IO;usingSystem.Web;usingSystem.Text;namespaceControllers{publicclassSafeController:Controller{ [HttpPost("/path-test")]publicIActionResultPost(){// Get parameter from cookiesstringparam="defaultValue";if(Request.Cookies!=null){foreach(varcookieinRequest.Cookies){if(cookie.Key.Equals("TestCookie")){param=HttpUtility.UrlDecode(cookie.Value,Encoding.UTF8);break;}}}// Safe: Uses ternary that always evaluates to a constantstringfilePath=(7*18)+106>200?"safe_constant_filename":param;// Use the safe valueFileStreamfs=null;try{stringfullPath=Constants.FILES_DIR+filePath;fs=newFileStream(fullPath,FileMode.Open);// Read file...}catch(Exceptione){// Handle error...}finally{fs?.Close();}returnOk();}}publicstaticclassConstants{publicstaticstringFILES_DIR="files/";}}
Seamless integrations. Try Datadog Code Security
Datadog Code Security
Try this rule and analyze your code with Datadog Code Security
How to use this rule
1
2
rulesets:- csharp-security # Rules to enforce C# security.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Security scans to your CI pipelines