The rule “Avoid potential cookie injections” is important to prevent the exploitation of insecure handling of cookies in your application. Cookie injection attacks can lead to unauthorized access and alteration of user data, which may result in serious security breaches such as session hijacking and identity theft.
In the non-compliant code, the user input is directly used to set a cookie. This is insecure because an attacker could potentially inject malicious content into the cookie.
To avoid violating this rule, ensure that user input is properly sanitized before using it to set a cookie. In the compliant code, the user input is first passed through a HMAC function, which creates a fixed-size string based on the input and a secret key. This ensures that even if an attacker can control the input, they cannot control the output or reverse-engineer the key. The cookie is also set with the httponly, secure, and samesite attributes to further enhance security.