Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// {fact rule=cookie-without-http-only-flag@v1.0 defects=0}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
// Compliant: Sensitive cookie with 'HttpOnly' flag
<httpCookies httpOnlyCookies="true" requireSSL="true" />
<roleManager defaultProvider="SqlProvider"
enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPROLES"
cookieTimeout="30"
cookiePath="/MyApplication"
cookieSlidingExpiration="true"
cookieProtection="Encrypted" >
<providers>
<add
name="SqlProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="SqlServices"
applicationName="MyApplication" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\Microsoft.IIS.Administration.dll" forwardWindowsAuthToken="true" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
<security>
<authentication>
<windowsAuthentication enabled="true" />
</authentication>
<authorization>
<clear />
<add accessType="Allow" roles="Administrators,IIS Administrators" />
</authorization>
</security>
</system.webServer>
</location>
</configuration>
//{fact}


//{fact rule=cookie-without-http-only-flag@v1.0 defects=0}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
// Noncompliant: Sensitive cookie without 'HttpOnly' flag
<httpCookies httpOnlyCookies="false" requireSSL="false" />
<roleManager defaultProvider="SqlProvider"
enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPROLES"
cookieTimeout="30"
cookiePath="/MyApplication"
cookieSlidingExpiration="true"
cookieProtection="Encrypted" >
<providers>
<add
name="SqlProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="SqlServices"
applicationName="MyApplication" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\Microsoft.IIS.Administration.dll" forwardWindowsAuthToken="true" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
<security>
<authentication mode="Forms">
<forms loginUrl="member_login.aspx"
cookieless="UseCookies"
// ruleid: web-config-insecure-cookie-settings-csharp-rule
requireSSL="false"
path="/MyApplication" />
</authentication>
<authorization>
<clear />
<add accessType="Allow" roles="Administrators,IIS Administrators" />
</authorization>
</security>
</system.webServer>
</location>
</configuration>
//{fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// {fact rule=ldap-injection@v1.0 defects=1}
public User Login(string userName, string password)
{
using (DirectoryEntry entry = new DirectoryEntry(config.Path, config.UserDomainName + "\\" + userName, password))
{
using (DirectorySearcher searcher = new DirectorySearcher(entry))
{
// Noncompliant: improper validation or sanitization
searcher.Filter = String.Format("({0}={1})", SAMAccountNameAttribute, userName);
searcher.PropertiesToLoad.Add(DisplayNameAttribute);
searcher.PropertiesToLoad.Add(SAMAccountNameAttribute);
var result = searcher.FindOne();
if (result != null)
{
var displayName = result.Properties[DisplayNameAttribute];
var samAccountName = result.Properties[SAMAccountNameAttribute];

return new User
{
DisplayName = displayName == null || displayName.Count <= 0 ? null : displayName[0].ToString(),
UserName = samAccountName == null || samAccountName.Count <= 0 ? null : samAccountName[0].ToString()
};
}
}
}
}
// {/fact}

// {fact rule=ldap-injection@v1.0 defects=0}
public User Login1(string userName, string password)
{
using (DirectoryEntry entry = new DirectoryEntry(config.Path, config.UserDomainName + "\\" + userName, password))
{
using (DirectorySearcher searcher = new DirectorySearcher(entry))
{
// Compliant: proper validation or sanitization
searcher.Filter = String.Format("({0}={1})", Encoder.LdapFilterEncode(SAMAccountNameAttribute), Encoder.LdapFilterEncode(userName));
searcher.PropertiesToLoad.Add(DisplayNameAttribute);
searcher.PropertiesToLoad.Add(SAMAccountNameAttribute);
var result = searcher.FindOne();
if (result != null)
{
var displayName = result.Properties[DisplayNameAttribute];
var samAccountName = result.Properties[SAMAccountNameAttribute];

return new User
{
DisplayName = displayName == null || displayName.Count <= 0 ? null : displayName[0].ToString(),
UserName = samAccountName == null || samAccountName.Count <= 0 ? null : samAccountName[0].ToString()
};
}
}
}
}
// {/fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;

public class Example
{

// {fact rule=double-epsilon-equality@v1.0 defects=1}
static bool lazyEqualLeftCompare(double v1, double v2){
// Noncompliant: valur other than 0
return Math.Abs(v1 - v2) <= Double.Epsilon;
}
// {/fact}

// {fact rule=double-epsilon-equality@v1.0 defects=0}

static bool uselessZeroEqual(){
double v1 = 0;
double v2 = 0;
// Compliant: value is zero
return Math.Abs(v1 - v2) <= Double.Epsilon;
}
// {/fact}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// {fact rule=jwt-no-expiry@v1.0 defects=1}
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{

options.TokenValidationParameters = new TokenValidationParameters
{
// Noncompliant: ValidateLifetime is set to false
ValidateLifetime = false,
RequireSignedTokens = true,
ValidateIssuer = false,
ValidateAudience = false,
RequireExpirationTime = true
};
});
// {/fact}

// {fact rule=jwt-no-expiry@v1.0 defects=0}
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{

options.TokenValidationParameters = new TokenValidationParameters
{
// Compliant: ValidateLifetime is set to true
ValidateLifetime = true,
RequireSignedTokens = true,
ValidateIssuer = false,
ValidateAudience = false,
RequireExpirationTime = true
};
});
18 changes: 18 additions & 0 deletions csharp/src/detectors/mass-assignment/MassAssignment.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Microsoft.AspNetCore.Mvc;
// {fact rule=mass-assignment@v1.0 defects=1}
public IActionResult Create(UserModel model)
{
context.SaveChanges();
// Noncompliant: `Bind` attribute not present
return View("Index", model);
}
// {fact}

// {fact rule=mass-assignment@v1.0 defects=0}
public IActionResult Create([Bind(nameof(UserModel.Name))] UserModel model)
{
context.SaveChanges();
// Compliant: `Bind` attribute present
return View("Index", model);
}
// {fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace MemMarshalCreateSpan {
public class MemMarshalCreateSpan {
// {fact rule=memory-marshal-create-span@v1.0 defects=1}
public void MarshalNoncompliant() {

// Noncompliant: length argument is not checked
Span<T> ToSpan() => MemoryMarshal.CreateSpan(ref _e0, 1);

}
// {/fact}

// {fact rule=memory-marshal-create-span@v1.0 defects=0}
public void MarshalCompliant() {
memory-marshal-create-span@v1.0

// Compliant: length argument is checked
Span<int> intSpan = MemoryMarshal.Cast<byte, int>(byteSpan);

}
// {/fact}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8" ?>
#{fact rule=debugbinary@v1.0eifjcbfcvuunegvkrtccfccigfktjuddgegletttbctr
defects=1}
<configuration>
<system.web>
# Noncompliant: `debug` is set to `false`
<compilation
defaultLanguage="c#"
debug="true"
/>
<trace enabled="true" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"/>
</system.web>
</configuration>
#{fact}

#{fact rule=debugbinary@v1.0 defects=0}
<configuration>
<system.web>
# complaint: `debug` is set to `true`
<compilation
defaultLanguage="c#"
/>
</system.web>
</configuration>
#fact
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// {fact rule=prevent-excessive-authentication@v1.0 defects=1}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");

if (ModelState.IsValid)
{
// Noncompliant: lockoutOnFailure us set to false
var result = await _signInManager.PasswordSignInAsync(Input.Email,
Input.Password, Input.RememberMe,
lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl,
Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}

return Page();
}
//{fact}

// {fact rule=prevent-excessive-authentication@v1.0 defects=0}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
// Compliant:lockoutOnFailure is set to true
var result = await _signInManager.PasswordSignInAsync(Input.Email,
Input.Password, Input.RememberMe,
lockoutOnFailure: true);

if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl,
Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return Page();
}
}

return Page();
}
//{fact}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<!-- this is a test for C# from the community contributor and is left as-is for future forking into C# specific rules -->
<!-- #{fact rule=razor-use-of-html-string@v1.0 defects=1} -->
public void RenderDescription(string description)
{
var newcontent = new Microsoft.AspNetCore.Html.HtmlString(description);
}


<div>
<div>
<!-- Noncompliant: Improper Encoding or Escaping of Output -->
<div>@(new HtmlString(description))</div>
</div>
</div>
<!--{fact}-->

<!-- this is a test for C# from the community contributor and is left as-is for future forking into C# specific rules -->
<!-- #{fact rule=razor-use-of-html-string@v1.0 defects=0} -->
public void RenderDescription(string description)
{
var newcontent = new Microsoft.AspNetCore.Html.HtmlString(WebUtility.HtmlEncode(description));
}


<div>
<div>
<!-- Compliant: Proper Encoding or Escaping of Output -->
<div>@(new HtmlString(HttpUtility.HtmlEncode(description)))</div>
</div>
</div>
<!--{fact}-->
Loading