### Install SecurityCodeScan.VS2019 NuGet Package Source: https://security-code-scan.github.io/ Use this command in the Package Manager Console to install the SecurityCodeScan.VS2019 NuGet package into all projects within a solution. ```powershell Get-Project -All | Install-Package SecurityCodeScan.VS2019 ``` -------------------------------- ### Install Stand-alone Security Scan Tool Source: https://security-code-scan.github.io/ Install the global .NET tool for Security Code Scan. For older .NET 4.x projects, use the provided zip file from GitHub Releases. ```bash dotnet tool install --global security-scan ``` -------------------------------- ### Configure Custom Sink in Project-Specific YAML Source: https://security-code-scan.github.io/ Example of a project-specific configuration file (SecurityCodeScan.config.yml) to define a custom sink. Requires 'Version: 3.1' to be present. ```yaml Version: 3.1 Sinks: - Type: System.Messaging.BinaryMessageFormatter TaintTypes: - SCS0028 Methods: - Name: Read Arguments: - message ``` -------------------------------- ### Validate Input for XPath Queries Source: https://security-code-scan.github.io/ This example illustrates validating user input before using it in an XPath query to prevent XPath injection. Whitelisting characters is a recommended approach. ```csharp var doc = new XmlDocument {XmlResolver = null}; doc.Load("/config.xml"); var results = doc.SelectNodes("/Config/Devices/Device[id='" + input + "']"); ``` ```csharp Regex rgx = new Regex(@"^[a-zA-Z0-9]+$"); if(rgx.IsMatch(input)) //Additional validation { XmlDocument doc = new XmlDocument {XmlResolver = null}; doc.Load("/config.xml"); var results = doc.SelectNodes("/Config/Devices/Device[id='" + input + "']"); } ``` -------------------------------- ### Configure Custom Sink in User-Specific YAML Source: https://security-code-scan.github.io/ Example of a user-specific configuration file (config-3.1.yml) to define a custom sink, specifying the type, taint types, and methods that should be considered sinks for taint analysis. ```yaml Sinks: - Type: System.Messaging.BinaryMessageFormatter TaintTypes: - SCS0028 Methods: - Name: Read Arguments: - message ``` -------------------------------- ### Serialize Simple DTOs with Json.NET Source: https://security-code-scan.github.io/ This example shows how to serialize Data Transfer Objects (DTOs) using Json.NET with TypeNameHandling set to None. This ensures that only simple data is serialized, making it safe to deserialize. ```csharp class DataForStorage { public string Id; public int Count; } var data = JsonConvert.SerializeObject(json, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None }); ``` -------------------------------- ### Safe JavaScriptSerializer Usage Source: https://security-code-scan.github.io/ This example shows a safer way to use JavaScriptSerializer by omitting the TypeResolver. This prevents the serializer from resolving types from the input, mitigating the risk of arbitrary code execution. ```csharp private void ConvertData(string json) { var mySerializer = new JavaScriptSerializer(/* no resolver here */); Object mything = mySerializer.Deserialize(json, typeof(SomeDataClass)); } ``` -------------------------------- ### LDAP Query Input Validation Source: https://security-code-scan.github.io/ Validate dynamic values passed to LDAP queries to prevent malicious users from extending the query. This example shows a vulnerable path where input is directly used. ```csharp var dir = new DirectoryEntry(); dir.Path = $"GC://DC={input},DC=com"; ``` -------------------------------- ### Enable ViewState MAC Source: https://security-code-scan.github.io/ Ensure enableViewStateMac is set to 'true' in the system.web pages configuration. This setting prevents attackers from tampering with the ViewState data. ```xml ... ... ``` -------------------------------- ### Compute Hash using SHA256 Source: https://security-code-scan.github.io/ Migrate from SHA1 to SHA256 for hashing. Note that for password hashing, adaptive algorithms are recommended over direct hashing. ```csharp var hashProvider = SHA256Managed.Create(); var hash = hashProvider.ComputeHash(str); ``` -------------------------------- ### Add Microsoft.Net.Compilers.Toolset NuGet Package Source: https://security-code-scan.github.io/ If encountering compiler toolset mismatches with Roslyn analyzers, add this NuGet package to the project as a workaround. Note that this is not a long-term supported solution. ```bash dotnet add package microsoft.net.compilers.toolset ``` -------------------------------- ### AES Symmetric Encryption in C# Source: https://security-code-scan.github.io/ This snippet demonstrates how to perform symmetric encryption using the AES algorithm in C#. Ensure that the key is securely managed and consider authenticated encryption for data integrity. ```csharp // Create a string to encrypt. byte[] encrypted; var encryptor = new AesManaged(); encryptor.Key = key; encryptor.GenerateIV(); var iv = encryptor.IV; // Create the streams used for encryption. using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(Data); } encrypted = msEncrypt.ToArray(); return encrypted; } } ``` -------------------------------- ### Configure ViewState MAC Source: https://security-code-scan.github.io/ Set enableViewStateMac to 'true' in the system.web pages configuration. This ensures the integrity of ViewState data by enabling a Message Authentication Code (MAC). ```xml ... ... ``` -------------------------------- ### Configure XML Parser to Prevent XXE Source: https://security-code-scan.github.io/ This code snippet addresses XML External Entity (XXE) vulnerabilities by showing how to configure the XML parser. DTD expansion is disabled by default in later .NET versions, but explicit configuration might be needed. ```csharp // DTD expansion is enabled by default XmlReaderSettings settings = new XmlReaderSettings(); XmlReader reader = XmlReader.Create(inputXml, settings); ``` ```csharp XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(pathToXmlFile); Console.WriteLine(xmlDoc.InnerText); ``` -------------------------------- ### Encrypt Data using DES (Deprecated) Source: https://security-code-scan.github.io/ This code demonstrates encryption using DES, which is considered weak. Modern applications should use AES. ```csharp DES DESalg = DES.Create(); // Create a string to encrypt. byte[] encrypted; ICryptoTransform encryptor = DESalg.CreateEncryptor(key, zeroIV); // Create the streams used for encryption. using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(Data); } encrypted = msEncrypt.ToArray(); return encrypted; } } ``` -------------------------------- ### Automate AdditionalFileItemNames Addition with PowerShell Source: https://security-code-scan.github.io/ A PowerShell script to recursively find all .csproj files in a directory and automatically add the 'AdditionalFileItemNames' element to their PropertyGroup if it's missing. ```powershell Get-ChildItem *.csproj -Recurse | ForEach-Object { $content = [xml] (Get-Content $_) $propertyGroups = $content.SelectNodes("//Project/PropertyGroup") if (-not $propertyGroups[0].AdditionalFileItemNames) { Write-Host "AdditionalFileItemNames missing in $_" $additionalFileItemNamesElt = $content.CreateElement("AdditionalFileItemNames") $additionalFileItemNamesElt.set_InnerText('$(AdditionalFileItemNames);Content') $propertyGroups[0].AppendChild($additionalFileItemNamesElt) } Set-ItemProperty $_ -name IsReadOnly -value $false $content.Save($_) # Normalize line endings (Get-Content $_ -Encoding UTF8) | Set-Content $_ -Encoding UTF8 } ``` -------------------------------- ### Validate Input for OS Command Execution Source: https://security-code-scan.github.io/ This snippet demonstrates how to validate user input before passing it to an OS command to prevent command injection. Ensure input is validated against a whitelist of allowed characters. ```csharp var p = new Process(); p.StartInfo.FileName = "exportLegacy.exe"; p.StartInfo.Arguments = " -user " + input + " -role user"; p.Start(); ``` ```csharp Regex rgx = new Regex(@"^[a-zA-Z0-9]+$"); if(rgx.IsMatch(input)) { var p = new Process(); p.StartInfo.FileName = "exportLegacy.exe"; p.StartInfo.Arguments = " -user " + input + " -role user"; p.Start(); } ``` -------------------------------- ### Add AdditionalFileItemNames to MSBuild Project Source: https://security-code-scan.github.io/ Modify C# (.csproj) or VB.NET (.vbproj) project files to enable analysis of .aspx and web.config files by adding the 'AdditionalFileItemNames' element. ```xml [..] $(AdditionalFileItemNames);Content ``` -------------------------------- ### Configure HTTP Cookies to Not Require SSL (Vulnerable) Source: https://security-code-scan.github.io/ This code represents a vulnerable configuration where cookies might be sent over unencrypted channels. It is explicitly set to 'false' or relies on the default behavior, which is not secure. ```xml ``` ```csharp // default is left var cookie = new HttpCookie("test"); // or explicitly set to false var cookie = new HttpCookie("test"); cookie.Secure = false; ``` -------------------------------- ### Secure Deserialization with Json.NET Source: https://security-code-scan.github.io/ This snippet demonstrates secure deserialization using Json.NET by setting TypeNameHandling to None. This ensures that type information is not used during deserialization, preventing potential exploits. ```csharp // Json.net will inspect if the serialized data is the Expected type var data = JsonConvert.DeserializeObject(json, new JsonSerializerSettings { // Type information is not used, only simple types like int, string, double, etc. will be resolved TypeNameHandling = TypeNameHandling.None }); ``` -------------------------------- ### Configure ASP.NET Identity Password Requirements Source: https://security-code-scan.github.io/ Ensure strong password policies are enforced by setting appropriate requirements for password length and complexity. ```csharp PasswordValidator pwdv = new PasswordValidator(); ``` ```csharp PasswordValidator pwdv = new PasswordValidator { RequiredLength = 6, }; ``` ```csharp PasswordValidator pwdv = new PasswordValidator { RequiredLength = 8, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, }; ``` -------------------------------- ### Implement Authorization Attributes in ASP.NET Controllers Source: https://security-code-scan.github.io/ Use [Authorize] and [AllowAnonymous] attributes to explicitly define access control for controller actions. Ensure endpoints are protected unless explicitly made anonymous. ```csharp public class AccountController : Controller { public ActionResult Login() { } [Authorize] public ActionResult Logout() { } } ``` ```csharp [Authorize] public class AccountController : Controller { [AllowAnonymous] public ActionResult Login() { } public ActionResult Logout() { } } ``` -------------------------------- ### Configure PrivateAssets for NuGet Package Source: https://security-code-scan.github.io/ To prevent Roslyn analyzers from being automatically added to dependent projects (e.g., unit test projects), add the NuGet package as private in the project file. ```xml ``` -------------------------------- ### Encrypt Data with .NET AES CBC and HMACSHA256 Source: https://security-code-scan.github.io/ Encrypts data using AES in CBC mode with PKCS7 padding and authenticates it using HMACSHA256. This method requires separate encryption and authentication keys. The output includes the Initialization Vector (IV), ciphertext, and the HMAC tag. ```csharp using System.IO; using System.Security.Cryptography; public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null) { //User Error Checks if (cryptKey == null || cryptKey.Length != KeyBitSize / 8) throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "cryptKey"); if (authKey == null || authKey.Length != KeyBitSize / 8) throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "authKey"); if (secretMessage == null || secretMessage.Length < 1) throw new ArgumentException("Secret Message Required!", "secretMessage"); byte[] cipherText; byte[] iv; using (var aes = new AesManaged { KeySize = KeyBitSize, BlockSize = BlockBitSize, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 }) { //Use random IV aes.GenerateIV(); iv = aes.IV; using (var encrypter = aes.CreateEncryptor(cryptKey, iv)) using (var cipherStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write)) using (var binaryWriter = new BinaryWriter(cryptoStream)) { //Encrypt Data binaryWriter.Write(secretMessage); } cipherText = cipherStream.ToArray(); } } //Assemble encrypted message and add authentication using (var hmac = new HMACSHA256(authKey)) using (var encryptedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(encryptedStream)) { //Prepend IV binaryWriter.Write(iv); //Write Ciphertext binaryWriter.Write(cipherText); binaryWriter.Flush(); //Authenticate all data var tag = hmac.ComputeHash(encryptedStream.ToArray()); //Postpend tag binaryWriter.Write(tag); } return encryptedStream.ToArray(); } } ``` -------------------------------- ### Enable ViewState encryption mode Source: https://security-code-scan.github.io/ Configure viewStateEncryptionMode to 'Always' in the system.web pages element. This ensures that ViewState is encrypted, protecting sensitive information from client-side exposure. ```xml ... ... ``` -------------------------------- ### Enable Request Validation in Pages Configuration Source: https://security-code-scan.github.io/ Ensure validateRequest is set to 'true' in the system.web pages configuration. This enables built-in protection against XSS attacks by validating incoming request data. ```xml ... ... ``` -------------------------------- ### Custom SerializationBinder for BinaryFormatter Source: https://security-code-scan.github.io/ This code implements a custom SerializationBinder to restrict the types that BinaryFormatter can deserialize. It uses a whitelist approach to only allow specific, safe types, mitigating risks from untrusted data. ```csharp class LimitedBinder : SerializationBinder { List allowedTypes = new List() { typeof(Exception), typeof(List), }; public override Type BindToType(string assemblyName, string typeName) { var type = Type.GetType(String.Format("{0}, {1}", typeName, assemblyName), true); foreach(Type allowedType in allowedTypes) { if(type == allowedType) return allowedType; } // Don’t return null for unexpected types – // this makes some serializers fall back to a default binder, allowing exploits. throw new Exception("Unexpected serialized type"); } } var formatter = new BinaryFormatter() { Binder = new LimitedBinder () }; var data = (List)formatter.Deserialize (fs); ``` -------------------------------- ### Generate Cryptographically Secure Random Bytes Source: https://security-code-scan.github.io/ Replace `System.Random` with `System.Security.Cryptography.RandomNumberGenerator` for generating cryptographically secure random numbers. ```csharp using System.Security.Cryptography; var rnd = RandomNumberGenerator.Create(); ``` -------------------------------- ### Encode LDAP Filter Input Source: https://security-code-scan.github.io/ Use `LdapFilterEncode` from the AntiXSS library to properly encode input for LDAP filters, preventing injection attacks. ```csharp var searcher = new DirectorySearcher(); searcher.Filter = "(cn=" + Encoder.LdapFilterEncode(input) + ")"; ``` -------------------------------- ### Externalize Hardcoded Passwords in ASP.NET Source: https://security-code-scan.github.io/ Avoid hardcoding sensitive information like passwords directly in the code. Store them in configuration files and retrieve them at runtime. ```csharp config.setPassword("NotSoSecr3tP@ssword"); ``` ```xml ``` ```csharp string apiPassword = ConfigurationManager.AppSettings["api_password"]; config.setPassword(apiPassword); ``` -------------------------------- ### Configure ViewState encryption mode Source: https://security-code-scan.github.io/ Set viewStateEncryptionMode to 'Always' in the system.web configuration to ensure ViewState is always encrypted. This protects sensitive data stored in hidden fields from being leaked to the client. ```xml ... ... ``` ```xml ... ... ``` -------------------------------- ### Prevent SQL Injection with Parameterized Queries Source: https://security-code-scan.github.io/ This code shows how to prevent SQL injection by using parameterized queries instead of string concatenation. This is crucial when user input is included in database queries. ```csharp var cmd = "SELECT * FROM Users WHERE username = '" + input + "' and role='user'"; ctx.Database.ExecuteSqlCommand( cmd); ``` ```csharp var cmd = "SELECT * FROM Users WHERE username = @username and role='user'"; ctx.Database.ExecuteSqlCommand( cmd, new SqlParameter("@username", input)); ``` -------------------------------- ### Enable Event Validation in ASP.NET Configuration Source: https://security-code-scan.github.io/ Ensure event validation is enabled in the web.config file to reduce the risk of unauthorized post-back requests. The default value is true, which is secure. ```xml ... ... ``` ```xml ... ... ``` -------------------------------- ### Configure HTTP Cookies to Require SSL Source: https://security-code-scan.github.io/ Ensures that cookies are only sent over HTTPS by setting the 'requireSSL' attribute to 'true' in the httpCookies configuration or by explicitly setting the 'Secure' property to 'true' in code. ```xml ``` ```csharp var cookie = new HttpCookie("test"); cookie.Secure = true; //Add this flag cookie.HttpOnly = true; ``` -------------------------------- ### Configure HttpOnly flag for cookies Source: https://security-code-scan.github.io/ Set httpOnlyCookies to true in the configuration to enhance cookie security. This prevents client-side scripts from accessing sensitive cookie data, reducing XSS attack vectors. ```xml ``` -------------------------------- ### Disable Certificate Validation (Conditional Debug) Source: https://security-code-scan.github.io/ Conditionally disable server certificate validation within a DEBUG build using `#if DEBUG`. This is a safer approach for development environments. ```csharp #if DEBUG ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; #endif ``` -------------------------------- ### Vulnerable JavaScriptSerializer Usage Source: https://security-code-scan.github.io/ This code snippet demonstrates a vulnerable use of JavaScriptSerializer by passing a custom TypeResolver, which can lead to arbitrary code execution if the input JSON is crafted maliciously. ```csharp private void ConvertData(string json) { var mySerializer = new JavaScriptSerializer(new SimpleTypeResolver()); Object mything = mySerializer.Deserialize(json, typeof(SomeDataClass)/* the type doesn't matter */); } ``` -------------------------------- ### Encrypt Data with Bouncy Castle GCM Source: https://security-code-scan.github.io/ Encrypts a secret message using AES in GCM mode with a provided key. Requires a 256-bit key and generates a random nonce. The output includes the nonce and the ciphertext with an authentication tag. ```csharp using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Modes; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; public static readonly int BlockBitSize = 128; public static readonly int KeyBitSize = 256; public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] key) { //User Error Checks if (key == null || key.Length != KeyBitSize / 8) throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key"); if (secretMessage == null || secretMessage.Length == 0) throw new ArgumentException("Secret Message Required!", "secretMessage"); //Using random nonce large enough not to repeat var nonce = new byte[NonceBitSize / 8]; Random.NextBytes(nonce, 0, nonce.Length); var cipher = new GcmBlockCipher(new AesFastEngine()); var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, new byte[0]); cipher.Init(true, parameters); //Generate Cipher Text With Auth Tag var cipherText = new byte[cipher.GetOutputSize(secretMessage.Length)]; var len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0); cipher.DoFinal(cipherText, len); //Assemble Message using (var combinedStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(combinedStream)) { //Prepend Nonce binaryWriter.Write(nonce); //Write Cipher Text binaryWriter.Write(cipherText); } return combinedStream.ToArray(); } } ``` -------------------------------- ### Enable Request Validation Mode Source: https://security-code-scan.github.io/ Configure requestValidationMode to '4.5' in the system.web httpRuntime element. This ensures that request validation is enabled for all HTTP requests, providing comprehensive XSS protection. ```xml ... ... ``` -------------------------------- ### Safe JSON Output from DTO Serialization Source: https://security-code-scan.github.io/ This JSON output demonstrates the result of serializing a simple DTO using Json.NET with TypeNameHandling.None. It contains only data and no type information, making it safe for deserialization. ```json { "Id": null, "Count": 0 } ``` -------------------------------- ### Encode LDAP Distinguished Name Input Source: https://security-code-scan.github.io/ Use `LdapDistinguishedNameEncode` from the AntiXSS library to properly encode input for LDAP distinguished names, preventing injection attacks. ```csharp var dir = new DirectoryEntry(); dir.Path = $"GC://DC={Encoder.LdapDistinguishedNameEncode(input)},DC=com"; ``` -------------------------------- ### Enable Request Validation in Controller Source: https://security-code-scan.github.io/ Ensure request validation is enabled by removing the [ValidateInput(false)] attribute from controller methods. This provides a basic defense against XSS attacks by filtering potentially harmful input. ```csharp public class TestController { [HttpPost] public ActionResult ControllerMethod(string input) { return f(input); } } ``` -------------------------------- ### Configure Request Validation Mode Source: https://security-code-scan.github.io/ Set requestValidationMode to '4.5' in the system.web httpRuntime configuration. This ensures that request validation is applied more broadly, enhancing protection against XSS attacks. ```xml ... ... ``` -------------------------------- ### Prevent XSS by HTML Encoding Output in ASP.NET MVC Source: https://security-code-scan.github.io/ Encode dynamic content from user input using HttpUtility.HtmlEncode to prevent cross-site scripting (XSS) attacks. This ensures that script injection is neutralized. ```csharp public class TestController : Controller { [HttpGet("{myParam}")] public string Get(string myParam) { return "value " + HttpUtility.HtmlEncode(myParam); } } ``` -------------------------------- ### Enable HttpOnly flag for cookies in C# Source: https://security-code-scan.github.io/ Ensure HttpOnly is set to true for HttpCookie objects in C# code. This is a critical step in preventing session hijacking and other attacks that exploit client-side script access to cookies. ```csharp var cookie = new HttpCookie("test"); cookie.Secure = true; cookie.HttpOnly = true; //Add this flag ``` -------------------------------- ### Prevent CSRF with AntiForgeryToken in ASP.NET MVC Source: https://security-code-scan.github.io/ Implement AntiForgeryToken in your views and controllers to protect against Cross-Site Request Forgery attacks. This involves adding @Html.AntiForgeryToken() in the view and the [ValidateAntiForgeryToken] attribute to the controller action. ```csharp public class TestController { [HttpPost] public ActionResult ControllerMethod(string input) { //Do an action in the context of the logged in user } } ``` ```html @Html.AntiForgeryToken() ``` ```csharp public class TestController { [HttpPost] [ValidateAntiForgeryToken] //Annotation added public ActionResult ControllerMethod(string input) { //Do an action in the context of the logged in user } } ``` -------------------------------- ### Prevent Path Traversal in ASP.NET MVC Source: https://security-code-scan.github.io/ Validate filenames by checking for invalid characters before reading files to prevent path traversal attacks. Return a BadRequest if invalid characters are found. ```csharp [RedirectingAction] public ActionResult Download(string fileName) { if (fileName.IndexOfAny(InvalidFilenameChars) >= 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/ClientDocument/") + fileName); return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); } ``` -------------------------------- ### Vulnerable BinaryFormatter Deserialization Source: https://security-code-scan.github.io/ This code shows a dangerous pattern of deserializing data from an untrusted stream using BinaryFormatter. This can lead to arbitrary code execution as BinaryFormatter reads type information directly from the stream. ```csharp // DO NOT DO THIS! var thing = (MyType)new BinaryFormatter().Deserialize(untrustedStream); ``` -------------------------------- ### Disable Certificate Validation (Debug Only) Source: https://security-code-scan.github.io/ Temporarily disable server certificate validation by setting `ServicePointManager.ServerCertificateValidationCallback` to `true`. This should only be used in testing environments. ```csharp ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; ``` -------------------------------- ### Vulnerable AES Encryption (OFB Mode) in C# Source: https://security-code-scan.github.io/ This code snippet shows a vulnerable implementation of AES encryption using OFB mode without an HMAC. This makes the ciphertext susceptible to tampering without detection. For secure applications, use authenticated encryption. ```csharp using (var aes = new AesManaged { KeySize = KeyBitSize, BlockSize = BlockBitSize, Mode = CipherMode.OFB, Padding = PaddingMode.PKCS7 }) { using (var encrypter = aes.CreateEncryptor(cryptKey, new byte[16])) using (var cipherStream = new MemoryStream()) { using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write)) using (var binaryWriter = new BinaryWriter(cryptoStream)) { //Encrypt Data binaryWriter.Write(secretMessage); } cipherText = cipherStream.ToArray(); } } //Missing HMAC suffix to assure integrity ``` -------------------------------- ### Set HttpOnly flag for cookies Source: https://security-code-scan.github.io/ Ensure HttpOnlyCookies is set to true in configuration to prevent JavaScript access to sensitive cookies. This mitigates risks associated with Cross-Site Scripting (XSS) attacks. ```xml ``` -------------------------------- ### Prevent XXE with XmlReaderSettings in .NET Source: https://security-code-scan.github.io/ Prior to .NET 4.5.2, configure XmlReaderSettings to prohibit DTDs to prevent XXE attacks. For .NET 4.0 - 4.5.2, use DtdProcessing.Prohibit. Ensure proper configuration to avoid vulnerabilities. ```csharp var settings = new XmlReaderSettings(); // Prior to .NET 4.0 settings.ProhibitDtd = true; // default is false! // .NET 4.0 - .NET 4.5.2 settings.DtdProcessing = DtdProcessing.Prohibit; // default is DtdProcessing.Parse! XmlReader reader = XmlReader.Create(inputXml, settings); ``` -------------------------------- ### Enable HttpOnly flag for cookies in C# Source: https://security-code-scan.github.io/ Explicitly set the HttpOnly property to true for HttpCookie objects in C# code. This is crucial for protecting session IDs and other sensitive information from JavaScript access. ```csharp // default is left var cookie = new HttpCookie("test"); // or explicitly set to false var cookie = new HttpCookie("test"); cookie.HttpOnly = false; ``` -------------------------------- ### Remove Caching to Ensure Authorization in ASP.NET MVC Source: https://security-code-scan.github.io/ Ensure that authorization is not bypassed by removing the [OutputCache] attribute when [Authorize] is used. Caching can disable authorization for subsequent requests. ```csharp [Authorize] public class AdminController : Controller { [OutputCache] public ActionResult Index() { return View(); } } ``` ```csharp [Authorize] public class AdminController : Controller { public ActionResult Index() { return View(); } } ``` -------------------------------- ### Prevent XXE with XmlDocument in .NET Source: https://security-code-scan.github.io/ Set XmlResolver to null on XmlDocument to disable DTDs and prevent XXE attacks. This is not the default behavior and must be explicitly set. ```csharp XmlDocument xmlDoc = new XmlDocument(); xmlDoc.XmlResolver = null; // Setting this to NULL disables DTDs - Its NOT null by default. xmlDoc.Load(pathToXmlFile); Console.WriteLine(xmlDoc.InnerText); ``` -------------------------------- ### Validate Redirect URL in ASP.NET MVC Source: https://security-code-scan.github.io/ Validate that redirect URLs are local using Url.IsLocalUrl() to prevent open redirect vulnerabilities. This ensures that the application does not redirect users to untrusted external sites. ```csharp [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { if (MembershipService.ValidateUser(model.UserName, model.Password)) { FormsService.SignIn(model.UserName, model.RememberMe); if (!String.IsNullOrEmpty(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } // If we got this far, something failed, redisplay form return View(model); } ``` ```csharp [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { if (MembershipService.ValidateUser(model.UserName, model.Password)) { FormsService.SignIn(model.UserName, model.RememberMe); if (Url.IsLocalUrl(returnUrl)) // Make sure the url is relative, not absolute path { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } // If we got this far, something failed, redisplay form return View(model); } ``` -------------------------------- ### Secure XSLT Transformation in C# Source: https://security-code-scan.github.io/ Disable script execution in XSLT transformations unless absolutely necessary and in a fully trusted environment to prevent Remote Code Execution (RCE). ```csharp XslCompiledTransform transform = new XslCompiledTransform(); XsltSettings settings = new XsltSettings() {EnableScript = true}; transform.Load(xslPath, settings, null); // Execute the transformation. transform.Transform(reader, writer); ``` -------------------------------- ### Disable Request Validation in Pages Configuration Source: https://security-code-scan.github.io/ Setting validateRequest to 'false' in the system.web pages configuration disables a security feature that helps prevent XSS attacks. It is recommended to keep this setting enabled. ```xml ... ... ``` -------------------------------- ### Disable Request Validation in Controller Source: https://security-code-scan.github.io/ Disabling request validation using [ValidateInput(false)] in a controller method can expose the application to XSS attacks. It is recommended to keep request validation enabled. ```csharp public class TestController { [HttpPost] [ValidateInput(false)] public ActionResult ControllerMethod(string input) { return f(input); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.