Cookie ‘Secure’ attribute is not set to true¶
ID: cs/web/cookie-secure-not-set
Kind: problem
Security severity: 5.0
Severity: error
Precision: high
Tags:
- security
- external/cwe/cwe-319
- external/cwe/cwe-614
Query suites:
- csharp-code-scanning.qls
- csharp-security-extended.qls
- csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
Cookies without the Secure flag set may be transmitted using HTTP instead of HTTPS. This leaves them vulnerable to being read by a third party attacker. If a sensitive cookie such as a session key is intercepted this way, it would allow the attacker to perform actions on a user’s behalf.
Recommendation¶
When using ASP.NET Core, ensure cookies have the secure flag set by setting Microsoft.AspNetCore.Http.CookieOptions.Secure to true, or using CookiePolicyOptions to set a default security policy.
When using ASP.NET Web Forms, cookies can be configured as secure by default in the Web.config file, setting the requireSSL attribute to true in the forms or httpCookies element. Cookies may also be set to be secure programmatically by setting the System.Web.HttpCookie.Secure attribute to true.
Example¶
In the example below, Microsoft.AspNetCore.Http.CookieOptions.Secure is set to true.
class MyController : Controller
{
void Login()
{
var cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions() { Secure = true };
Response.Cookies.Append("auth", "secret", cookieOptions);
}
}
In the following example, CookiePolicyOptions are set programmatically to configure defaults.
public class Startup
{
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCookiePolicy(new CookiePolicyOptions()
{
Secure = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always,
HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always
});
}
}
In the example below System.Web.HttpCookie.Secure is set to true programmatically.
class MyController : Controller
{
void Login()
{
var cookie = new System.Web.HttpCookie("cookieName") { Secure = true };
}
}
In the example below, the requireSSL attribute is set to true in the forms element of the Web.config file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<authentication>
<forms
requireSSL="true"
... />
</authentication>
<httpCookies
requireSSL="true"
... />
</system.web>
</configuration>
References¶
ASP.NET Core docs: CookieOptions.Secure Property.
MDN: Set-Cookie Header.
Web Forms docs: FormsAuthentication.RequireSSL Property.
Web Forms docs: forms Element for authentication.
Web Forms docs: httpCookies Element.
Detectify: Cookie lack Secure flag.
PortSwigger: TLS cookie without secure flag set.
Common Weakness Enumeration: CWE-319.
Common Weakness Enumeration: CWE-614.