Review cookies created without HttpOnly and Secure flags
Matches methods that instantiate CookieOptions, CookieBuilder or HttpCookie without assigning both HttpOnly and Secure (or SecurePolicy), and methods calling Response.Cookies.Append(name, value) without options while the application does not use UseCookiePolicy(). The rule cannot see the assigned value: it reports the missing assignment, which in practice means the insecure default.
This is CWE-1004 Sensitive Cookie Without 'HttpOnly' Flag and CWE-614 Sensitive Cookie in HTTPS Session Without 'Secure' Attribute.
Flagged Code
This is CWE-1004 Sensitive Cookie Without 'HttpOnly' Flag and CWE-614 Sensitive Cookie in HTTPS Session Without 'Secure' Attribute.
Flagged Code
public void RememberSession(string token)
{
var options = new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(7) };
Response.Cookies.Append("session", token, options); // flagged: HttpOnly and Secure not set
}
Fixed Codepublic void RememberSession(string token)
{
var options = new CookieOptions
{
Expires = DateTimeOffset.UtcNow.AddDays(7),
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Strict
};
Response.Cookies.Append("session", token, options);
}How to fix
Set HttpOnly = true, Secure = true (or SecurePolicy = CookieSecurePolicy.Always) and a SameSite mode on every cookie carrying session or identity data, or apply them globally with app.UseCookiePolicy(new CookiePolicyOptions { HttpOnly = HttpOnlyPolicy.Always, Secure = CookieSecurePolicy.Always }). Suppress the issue for cookies that scripts legitimately need to read (e.g. a UI preference).
CQLinq source
This rule is written in CQLinq, C# LINQ over the NDepend code model. It ships with every new NDepend project: you can read it, adapt it, or use it as a starting point for your own custom rules.
// <Name>Review cookies created without HttpOnly and Secure flags</Name>
// <Id>ND3117:ReviewCookiesCreatedWithoutHttpOnlyAndSecureFlags</Id>
warnif count > 0
// Third-party members are part of the code model only when the application uses them.
let cookieTypes = ThirdParty.Types.WithFullNameIn(
"Microsoft.AspNetCore.Http.CookieOptions",
"Microsoft.AspNetCore.Http.CookieBuilder",
"System.Web.HttpCookie").ToArray()
where cookieTypes.Any()
let cookieCtors = cookieTypes.ChildMethods().Where(m => m.IsConstructor).ToHashSetEx()
let httpOnlySetters = cookieTypes.ChildMethods().Where(m => m.SimpleName == "set_HttpOnly").ToHashSetEx()
let secureSetters = cookieTypes.ChildMethods().Where(m => m.SimpleNameEqualsAny("set_Secure", "set_SecurePolicy")).ToHashSetEx()
// response.Cookies.Append(name, value) without options gets neither flag,
// unless a cookie policy middleware applies them globally.
let appUsesCookiePolicy = Application.Methods.Any(m =>
m.IsUsing("Microsoft.AspNetCore.Builder.CookiePolicyAppBuilderExtensions.UseCookiePolicy(IApplicationBuilder)".AllowNoMatch()) ||
m.IsUsing("Microsoft.AspNetCore.Builder.CookiePolicyAppBuilderExtensions.UseCookiePolicy(IApplicationBuilder,CookiePolicyOptions)".AllowNoMatch()))
let appendWithoutOptions = appUsesCookiePolicy ? new IMethod[0] :
ThirdParty.Types.WithFullName("Microsoft.AspNetCore.Http.IResponseCookies")
.ChildMethods().Where(m => m.SimpleName == "Append" && m.NbParameters == 2).ToArray()
from m in Application.Methods
let createsCookie = m.MethodsCalled.Intersect(cookieCtors).Any()
let missingHttpOnly = createsCookie && !m.MethodsCalled.Intersect(httpOnlySetters).Any()
let missingSecure = createsCookie && !m.MethodsCalled.Intersect(secureSetters).Any()
let appendsWithoutOptions = m.MethodsCalled.Intersect(appendWithoutOptions).Any()
where missingHttpOnly || missingSecure || appendsWithoutOptions
select new {
m,
missing = appendsWithoutOptions ? "options (HttpOnly and Secure)" :
missingHttpOnly && missingSecure ? "HttpOnly and Secure" :
missingHttpOnly ? "HttpOnly" : "Secure",
Debt = 10.ToMinutes().ToDebt(),
Severity = Severity.Medium
}
//<Expl>
// The *{0}* creates a cookie without setting {1}. Without *HttpOnly* a
// script injected in the page can read the cookie; without *Secure* it is
// sent in clear over HTTP.
//</Expl>
//<Desc>
// Matches methods that instantiate *CookieOptions*, *CookieBuilder* or
// *HttpCookie* without assigning both *HttpOnly* and *Secure* (or
// *SecurePolicy*), and methods calling *Response.Cookies.Append(name, value)*
// without options while the application does not use
// *UseCookiePolicy()*. The rule cannot see the assigned value: it reports
// the missing assignment, which in practice means the insecure default.
//
// This is CWE-1004 *Sensitive Cookie Without 'HttpOnly' Flag* and CWE-614
// *Sensitive Cookie in HTTPS Session Without 'Secure' Attribute*.
//
// **Flagged Code**
// ```csharp
// public void RememberSession(string token)
// {
// var options = new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(7) };
// Response.Cookies.Append("session", token, options); // flagged: HttpOnly and Secure not set
// }
// ```
//
// **Fixed Code**
// ```csharp
// public void RememberSession(string token)
// {
// var options = new CookieOptions
// {
// Expires = DateTimeOffset.UtcNow.AddDays(7),
// HttpOnly = true,
// Secure = true,
// SameSite = SameSiteMode.Strict
// };
// Response.Cookies.Append("session", token, options);
// }
// ```
//</Desc>
//<HowToFix>
// Set *HttpOnly = true*, *Secure = true* (or *SecurePolicy = CookieSecurePolicy.Always*)
// and a *SameSite* mode on every cookie carrying session or identity data,
// or apply them globally with *app.UseCookiePolicy(new CookiePolicyOptions { HttpOnly = HttpOnlyPolicy.Always, Secure = CookieSecurePolicy.Always })*.
// Suppress the issue for cookies that scripts legitimately need to read
// (e.g. a UI preference).
//</HowToFix>
Open in the interactive Rules Explorer · All default rules
Security: all 39 items
- Software Composition Analysis (SCA) ND3120
- Transitive Software Composition Analysis (SCA) ND3121
- Don't hard-code secrets in constants ND3114
- Review credentials built from hard-coded values ND3115
- Don't use insecure deserializers ND3110
- Don't use weak hash algorithms (MD5, SHA1) ND3109
- Don't use DES/3DES/RC2 weak cipher algorithms ND3102
- Don't use weak password-based key derivation ND3123
- Don't use the ECB encryption mode ND3132
- Don't disable certificate validation ND3103
- Don't hard-code TLS/SSL protocol versions ND3122
- Review commands vulnerable to SQL injection ND3107
- Review data adapters vulnerable to SQL injection ND3108
- Review raw SQL built from composed strings ND3128
- Review LDAP filters composed from strings ND3137
- Don't enable external XML entity resolution (XXE) ND3111
- Review processes started with a composed arguments string ND3124
- Review web endpoints building file paths from their parameters ND3129
- Review custom archive extraction (Zip Slip) ND3135
- Review assemblies and types loaded from runtime-provided names ND3125
- Review web endpoints without [Authorize] nor [AllowAnonymous] ND3118
- Review state-changing endpoints opened to anonymous callers ND3130
- Review state-changing MVC actions without anti-forgery validation ND3119
- Review HTML-encoding bypasses ND3133
- Review explicitly disabled request validation ND3134
- Review redirects to a URL that is not validated as local ND3126
- Review request-influenced outbound HTTP calls (SSRF) ND3136
- Review insecure ASP.NET Core CORS policies and unguarded developer exception page ND3116
- Review cookies created without HttpOnly and Secure flags ND3117
- Review regular expressions without a match timeout (ReDoS) ND3112
- Review secrets compared with non-constant-time equality ND3113
- Review secrets passed to logging methods ND3127
- Review security operations that log nothing ND3131
- Don't use System.Random for security purposes ND3101
- Don't use CoSetProxyBlanket and CoInitializeSecurity ND3100
- Review publicly visible event handlers ND3104
- Pointers should not be publicly visible ND3105
- Seal methods that satisfy non-public interfaces ND3106
- Restrict sensitive APIs to reviewed components ND3138