feat(dotnet): .NET detection, NuGet SBOM, C# rules and config checks #447

Merged
sharang merged 3 commits from feat/dotnet-minimal into main 2026-10-05 14:38:14 +00:00
34 changed files with 3356 additions and 43 deletions

No files matched your search

@@ -0,0 +1,258 @@
// Test cases for cra_semgrep_csharp.yaml: `semgrep --test compliance-agent/rules`.
// Each `ruleid:` line must be found by that rule; each `ok:` line must not.
using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Web;
using System.Web.UI;
using System.Xml;
using Newtonsoft.Json;
namespace Plant.Tests
{
public class SqlCases
{
public void Run(SqlConnection conn, string id, PlantContext db)
{
// ruleid: cra-ai-20-csharp-sql-string
var cmd = new SqlCommand("SELECT * FROM Orders WHERE Id = " + id, conn);
// ruleid: cra-ai-20-csharp-sql-string
var cmd2 = new SqlCommand($"DELETE FROM Orders WHERE Id = {id}", conn);
string sql = "SELECT * FROM Users WHERE Name = '" + id + "'";
// ruleid: cra-ai-20-csharp-sql-string
var cmd3 = new SqlCommand(sql, conn);
var sql2 = "SELECT * FROM Lines WHERE Code = '" + id + "'";
// ruleid: cra-ai-20-csharp-sql-string
var cmd4 = new SqlCommand(sql2, conn);
// ruleid: cra-ai-20-csharp-sql-string
cmd.CommandText = String.Format("UPDATE Orders SET State = {0}", id);
// ruleid: cra-ai-20-csharp-sql-string
db.Database.ExecuteSqlCommand("DELETE FROM Log WHERE Day < " + id);
// ruleid: cra-ai-20-csharp-sql-string
var rows = db.Orders.FromSqlRaw($"SELECT * FROM Orders WHERE Id = {id}");
// ok: cra-ai-20-csharp-sql-string
var safe = new SqlCommand("SELECT * FROM Orders WHERE Id = @id", conn);
safe.Parameters.AddWithValue("@id", id);
// ok: cra-ai-20-csharp-sql-string
var constant = new SqlCommand("SELECT * FROM Orders " + "ORDER BY Id", conn);
// ok: cra-ai-20-csharp-sql-string
var interpolated = db.Orders.FromSqlInterpolated($"SELECT * FROM Orders WHERE Id = {id}");
}
}
public class ProcessCases
{
public void Run(string host, string path)
{
// ruleid: cra-ai-20-csharp-process-start
Process.Start("cmd.exe", "/c ping " + host);
var psi = new ProcessStartInfo("tool.exe");
// ruleid: cra-ai-20-csharp-process-start
psi.Arguments = $"--target {host}";
// ok: cra-ai-20-csharp-process-start
Process.Start("notepad.exe");
// ok: cra-ai-20-csharp-process-start
Process.Start(path);
var startInfo = new ProcessStartInfo();
// ruleid: cra-ai-20-csharp-process-start
startInfo.FileName = path + "\\tool.exe";
var dialog = new SaveFileDialog();
// ok: cra-ai-20-csharp-process-start
dialog.FileName = path + ".csv";
}
}
public class DeserializationCases
{
public object Run(Stream input)
{
// ruleid: cra-ai-20-csharp-unsafe-deserialization
var formatter = new BinaryFormatter();
// ruleid: cra-ai-20-csharp-unsafe-deserialization
var ndcs = new NetDataContractSerializer();
// ruleid: cra-ai-20-csharp-unsafe-deserialization
var los = new LosFormatter();
// ruleid: cra-ai-20-csharp-unsafe-deserialization
var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
// ok: cra-ai-20-csharp-unsafe-deserialization
var safeSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None };
// ok: cra-ai-20-csharp-unsafe-deserialization
var dcs = new DataContractSerializer(typeof(Order));
return formatter.Deserialize(input);
}
}
public class XmlCases
{
public void Unsafe(string xml, string file)
{
XmlDocument doc;
doc = new XmlDocument();
// ruleid: cra-ai-20-csharp-xxe
doc.LoadXml(xml);
var doc2 = new XmlDocument();
// ruleid: cra-ai-20-csharp-xxe
doc2.Load(file);
var reader = new XmlTextReader(file);
// ruleid: cra-ai-20-csharp-xxe
while (reader.Read()) { }
var settings = new XmlReaderSettings();
// ruleid: cra-ai-20-csharp-xxe
settings.DtdProcessing = DtdProcessing.Parse;
// ruleid: cra-ai-20-csharp-xxe
settings.XmlResolver = new XmlUrlResolver();
}
public void Safe(string xml)
{
XmlDocument doc;
doc = new XmlDocument();
doc.XmlResolver = null;
// ok: cra-ai-20-csharp-xxe
doc.LoadXml(xml);
var doc2 = new XmlDocument();
doc2.XmlResolver = null;
// ok: cra-ai-20-csharp-xxe
doc2.LoadXml(xml);
var doc3 = new XmlDocument { XmlResolver = null };
// ok: cra-ai-20-csharp-xxe
doc3.LoadXml(xml);
var reader = new XmlTextReader(xml);
reader.DtdProcessing = DtdProcessing.Prohibit;
// ok: cra-ai-20-csharp-xxe
while (reader.Read()) { }
var settings = new XmlReaderSettings();
// ok: cra-ai-20-csharp-xxe
settings.DtdProcessing = DtdProcessing.Prohibit;
}
}
public class FileController
{
public HttpRequest Request;
public byte[] Download()
{
// ruleid: cra-ai-20-csharp-path-traversal
var path = Path.Combine(@"C:\Plant\Reports", Request.QueryString["file"]);
// ruleid: cra-ai-20-csharp-path-traversal
var text = File.ReadAllText(@"C:\Plant\Logs\" + Request["name"]);
// ok: cra-ai-20-csharp-path-traversal
var safe = Path.Combine(@"C:\Plant\Reports", Path.GetFileName(Request.QueryString["file"]));
return File.ReadAllBytes(safe);
}
}
public class CryptoCases
{
public void Run(byte[] data)
{
// ruleid: cra-ai-13-csharp-broken-hash-or-cipher
var md5 = MD5.Create();
// ruleid: cra-ai-13-csharp-broken-hash-or-cipher
var sha1 = new SHA1CryptoServiceProvider();
// ruleid: cra-ai-13-csharp-broken-hash-or-cipher
var des = new DESCryptoServiceProvider();
// ruleid: cra-ai-13-csharp-broken-hash-or-cipher
var tdes = TripleDES.Create();
// ok: cra-ai-13-csharp-broken-hash-or-cipher
var sha256 = SHA256.Create();
var aes = Aes.Create();
// ruleid: cra-ai-13-csharp-ecb-mode
aes.Mode = CipherMode.ECB;
// ok: cra-ai-13-csharp-ecb-mode
aes.Mode = CipherMode.CBC;
}
}
public class TlsCases
{
public void Run()
{
// ruleid: cra-ai-15-csharp-cert-validation-disabled
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, errors) => true;
// ruleid: cra-ai-15-csharp-cert-validation-disabled
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
var handler = new HttpClientHandler();
// ruleid: cra-ai-15-csharp-cert-validation-disabled
handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
// ok: cra-ai-15-csharp-cert-validation-disabled
handler.ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) => errors == System.Net.Security.SslPolicyErrors.None;
}
}
public class CredentialCases
{
// ruleid: cra-ai-8-csharp-hardcoded-credential
private const string DbPassword = "Plant#2019!";
// ruleid: cra-ai-8-csharp-hardcoded-credential
private static readonly string ApiSecret = "sk_live_51HxQ2a";
// ok: cra-ai-8-csharp-hardcoded-credential
private const string PasswordLabel = "Enter your password";
// ok: cra-ai-8-csharp-hardcoded-credential
private const string AdminPassword = "changeme";
public void Run(Config config)
{
// ruleid: cra-ai-8-csharp-hardcoded-credential
config.SmtpPassword = "mail-pa55word";
// ruleid: cra-ai-8-csharp-hardcoded-credential
var plcPassword = "Siemens#S7-1500";
// ok: cra-ai-8-csharp-hardcoded-credential
config.SmtpPassword = "";
// ok: cra-ai-8-csharp-hardcoded-credential
config.UserName = "operator1";
}
}
}
@@ -0,0 +1,266 @@
# Prüfwerk's own semgrep rules for C# (.NET Framework and .NET), #445. Written
# for Prüfwerk, not adapted from any third-party rule set (the Semgrep registry
# rules may not be used for a service offered to others).
# Same conventions as cra_semgrep.yaml: each rule id is `cra-ai-<n>-<slug>`,
# keyed back to its control via the `control-map` LUT, with its CWE and
# control in the metadata. Keep patterns tight: a false positive that the
# judge refutes marks the whole finding a false positive.
# Test cases: cra_semgrep_csharp.cs (`semgrep --test compliance-agent/rules`).
rules:
# --- cra-ai-20: injection and unsafe input handling --------------------------
- id: cra-ai-20-csharp-sql-string
languages: [csharp]
severity: ERROR
message: SQL text is built from strings (concatenation, interpolation or String.Format) and run as a command — SQL injection (CWE-89). Pass the values as parameters (SqlParameter, AddWithValue, FromSqlInterpolated).
metadata:
cwe: ["CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"]
control: cra-ai-20
pattern-either:
# The SQL text is built right in the call.
- patterns:
- pattern-either: &sql-sinks
- patterns:
- pattern-either:
- pattern: new $CMD($Q, ...)
- pattern: new $CMD($Q)
- metavariable-regex:
metavariable: $CMD
regex: ^(SqlCommand|OleDbCommand|OdbcCommand|OracleCommand|MySqlCommand|NpgsqlCommand|SQLiteCommand|SqliteCommand|SqlDataAdapter|OleDbDataAdapter)$
- pattern: $X.CommandText = $Q
- pattern: $X.ExecuteSqlCommand($Q, ...)
- pattern: $X.ExecuteSqlRaw($Q, ...)
- pattern: $X.ExecuteSqlRawAsync($Q, ...)
- pattern: $X.FromSqlRaw($Q, ...)
- pattern: $X.SqlQuery($Q, ...)
- pattern: $X.SqlQuery<$T>($Q, ...)
- metavariable-pattern:
metavariable: $Q
patterns: &built-string
- pattern-either:
- pattern: '"..." + $E'
- pattern: $E + "..."
- pattern: String.Format(...)
- pattern: string.Format(...)
- pattern-regex: (?s)^(\$@?|@\$)".*\{
- pattern-not: '"..." + "..."'
# The SQL text is built into a variable first.
- patterns:
- pattern-either:
- pattern-inside: |
$TY $Q = $INIT;
...
- pattern-inside: |
var $Q = $INIT;
...
- pattern-inside: |
$Q = $INIT;
...
- pattern-either: *sql-sinks
- metavariable-pattern:
metavariable: $INIT
patterns: *built-string
- id: cra-ai-20-csharp-process-start
languages: [csharp]
severity: WARNING
message: A process is started with a command line built from strings — command injection if any part comes from outside (CWE-78). Start a fixed program with an argument list (ProcessStartInfo.ArgumentList) and validate the values.
metadata:
cwe: ["CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"]
control: cra-ai-20
patterns:
- pattern-either:
- pattern: Process.Start($ARG, ...)
- pattern: Process.Start($FILE, $ARG, ...)
- pattern: new ProcessStartInfo($ARG, ...)
- pattern: new ProcessStartInfo($FILE, $ARG, ...)
- pattern: $P.Arguments = $ARG
# Only a ProcessStartInfo's: a file dialog's FileName is no command.
- patterns:
- pattern-either:
- pattern-inside: |
$PT $P = new ProcessStartInfo(...);
...
- pattern-inside: |
var $P = new ProcessStartInfo(...);
...
- pattern-inside: |
$P = new ProcessStartInfo(...);
...
- pattern: $P.FileName = $ARG
- metavariable-pattern:
metavariable: $ARG
patterns:
- pattern-either:
- pattern: '"..." + $E'
- pattern: $E + "..."
- pattern: String.Format(...)
- pattern: string.Format(...)
- pattern: String.Concat(...)
- pattern-regex: (?s)^(\$@?|@\$)".*\{
- pattern-not: '"..." + "..."'
- id: cra-ai-20-csharp-unsafe-deserialization
languages: [csharp]
severity: ERROR
message: $TYPE deserializes type information from its input, so data from outside can run code (CWE-502). Use a serializer bound to known types (System.Text.Json, DataContractSerializer, JSON.NET with TypeNameHandling.None).
metadata:
cwe: ["CWE-502: Deserialization of Untrusted Data"]
control: cra-ai-20
pattern-either:
- patterns:
- pattern: new $TYPE(...)
- metavariable-regex:
metavariable: $TYPE
regex: ^(BinaryFormatter|NetDataContractSerializer|LosFormatter|SoapFormatter|ObjectStateFormatter)$
- patterns:
- pattern: TypeNameHandling.$TYPE
- metavariable-regex:
metavariable: $TYPE
regex: ^(All|Auto|Objects|Arrays)$
- id: cra-ai-20-csharp-xxe
languages: [csharp]
severity: WARNING
message: XML is parsed with DTD processing or an external resolver enabled — external entities can read local files or reach internal hosts (XXE, CWE-611). Set XmlResolver = null and DtdProcessing = DtdProcessing.Prohibit (the default only from .NET Framework 4.5.2 on).
metadata:
cwe: ["CWE-611: Improper Restriction of XML External Entity Reference"]
control: cra-ai-20
pattern-either:
- pattern: $X.XmlResolver = new XmlUrlResolver(...)
- pattern: $X.DtdProcessing = DtdProcessing.Parse
- pattern: $X.ProhibitDtd = false
- patterns:
- pattern-either:
- pattern-inside: |
$D = new XmlDocument();
...
- pattern-inside: |
$DT $D = new XmlDocument();
...
- pattern-inside: |
var $D = new XmlDocument();
...
- pattern-inside: |
$D = new XmlTextReader(...);
...
- pattern-inside: |
$DT $D = new XmlTextReader(...);
...
- pattern-inside: |
var $D = new XmlTextReader(...);
...
- pattern-not-inside: |
$D.XmlResolver = null;
...
- pattern-not-inside: |
$D.DtdProcessing = DtdProcessing.Prohibit;
...
- pattern-not-inside: |
var $D = new $T { ..., XmlResolver = null, ... };
...
- pattern-not-inside: |
$DT $D = new $T { ..., XmlResolver = null, ... };
...
- pattern-either:
- pattern: $D.Load(...)
- pattern: $D.LoadXml(...)
- pattern: $D.Read()
- id: cra-ai-20-csharp-path-traversal
languages: [csharp]
severity: WARNING
message: A file path is built from request input — "..\" in it reaches files outside the intended folder (path traversal, CWE-22). Take only the file name (Path.GetFileName) and check the full path stays under the base folder.
metadata:
cwe: ["CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')"]
control: cra-ai-20
patterns:
- pattern-either:
- pattern: File.$M(..., <... Request.$P ...>, ...)
- pattern: File.$M(..., <... Request[$K] ...>, ...)
- pattern: Path.Combine(..., <... Request.$P ...>, ...)
- pattern: Path.Combine(..., <... Request[$K] ...>, ...)
- pattern: new FileStream(<... Request.$P ...>, ...)
- pattern: new FileStream(<... Request[$K] ...>, ...)
- pattern-not: File.$M(..., <... Path.GetFileName(...) ...>, ...)
- pattern-not: Path.Combine(..., <... Path.GetFileName(...) ...>, ...)
# --- cra-ai-13: Verschlüsselung sensibler Daten ------------------------------
- id: cra-ai-13-csharp-broken-hash-or-cipher
languages: [csharp]
severity: WARNING
message: $ALG is a broken algorithm (MD5, SHA-1, DES, 3DES or RC2) that protects neither integrity nor confidentiality (CWE-327). Use SHA-256 or better, and AES-GCM.
metadata:
cwe: ["CWE-327: Use of a Broken or Risky Cryptographic Algorithm"]
control: cra-ai-13
pattern-either:
- patterns:
- pattern: $ALG.Create(...)
- metavariable-regex:
metavariable: $ALG
regex: ^(MD5|SHA1|DES|TripleDES|RC2)$
- patterns:
- pattern: new $ALG(...)
- metavariable-regex:
metavariable: $ALG
regex: ^(MD5CryptoServiceProvider|MD5Cng|SHA1CryptoServiceProvider|SHA1Managed|SHA1Cng|DESCryptoServiceProvider|TripleDESCryptoServiceProvider|TripleDESCng|RC2CryptoServiceProvider|HMACMD5|HMACSHA1)$
- id: cra-ai-13-csharp-ecb-mode
languages: [csharp]
severity: WARNING
message: ECB mode encrypts equal blocks to equal ciphertext, so the structure of the data shows through (CWE-327). Use AES-GCM, or CBC with a random IV and a MAC.
metadata:
cwe: ["CWE-327: Use of a Broken or Risky Cryptographic Algorithm"]
control: cra-ai-13
pattern: CipherMode.ECB
# --- cra-ai-15: Transport-Schutz ---------------------------------------------
- id: cra-ai-15-csharp-cert-validation-disabled
languages: [csharp]
severity: ERROR
message: TLS certificate validation is switched off (the callback accepts every certificate), so anyone on the network path can read and change the traffic (CWE-295). Remove the callback, or pin the expected certificate.
metadata:
cwe: ["CWE-295: Improper Certificate Validation"]
control: cra-ai-15
pattern-either:
- pattern: HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
- patterns:
- pattern-either:
- pattern: $X.ServerCertificateValidationCallback = $F
- pattern: $X.ServerCertificateValidationCallback += $F
- pattern: $X.ServerCertificateCustomValidationCallback = $F
- pattern: $X.RemoteCertificateValidationCallback = $F
- metavariable-pattern:
metavariable: $F
pattern-either:
- pattern: (...) => true
- pattern: |
delegate { return true; }
- pattern: |
delegate (...) { return true; }
- pattern: |
(...) => { return true; }
# --- cra-ai-8: Keine Default-Passwörter --------------------------------------
- id: cra-ai-8-csharp-hardcoded-credential
languages: [csharp]
severity: ERROR
message: A credential ($NAME) is written into the source — every installation shares it, and it can be read out of the assembly (CWE-798). Load it from protected configuration or a secret store.
metadata:
cwe: ["CWE-798: Use of Hard-coded Credentials"]
control: cra-ai-8
patterns:
- pattern-either:
- pattern: $TYPE $NAME = "$VALUE";
- pattern: var $NAME = "$VALUE";
- pattern: $NAME = "$VALUE"
- pattern: const string $NAME = "$VALUE";
- metavariable-regex:
metavariable: $NAME
regex: (?i)^(.*\.)?\w*(password|passwd|pwd|secret|apikey|api_key|privatekey|private_key|accesskey|access_key|connectionpassword|encryptionkey|aeskey|secretkey|clientsecret)\w*$
- metavariable-regex:
metavariable: $NAME
regex: (?i)^(?!.*(hint|label|prompt|field|name|param|header|policy|length|regex|pattern|format|path|file|url|uri|key(name|id)|placeholder)).*$
# Six characters or more, and not a placeholder left for the installer.
- metavariable-regex:
metavariable: $VALUE
regex: ^(?!(?i:changeme|change_me|password|secret|admin|x{3,}|your_\w*|<[^>]*>|\*+|\{\d+\}|\$\{.*\}|%\w+%)$).{6,}$
+127
View File
@@ -0,0 +1,127 @@
//! The .NET stack of a code tree as classification facts (#445).
//!
//! Facts only: which target type a .NET tree is (desktop, web, service) is the
//! language classifier's call. Recorded per tree:
//!
//! - `dotnet_runtime`: `dotnet-framework`, `dotnet` (.NET Core / 5+) or
//! `dotnet-standard`, once each;
//! - `dotnet_solution`: every solution, a component of its own;
//! - `dotnet_project`: every project with its style and target frameworks,
//! e.g. `src/Hmi/Hmi.csproj (legacy; net48)`.
use std::path::Path;
use compliance_core::models::DetectedFact;
use crate::pipeline::dotnet::{inventory, Inventory};
/// What produced the facts.
const SOURCE: &str = "dotnet-inventory";
/// At most this many solution and project facts each: a large codebase has
/// dozens of projects, and the facts are a summary, not an inventory.
const MAX_FACTS: usize = 100;
/// Add the .NET facts of the tree at `root` to `facts`, skipping any already
/// there.
pub(super) fn add_facts(facts: &mut Vec<DetectedFact>, root: &Path) {
for fact in dotnet_facts(&inventory(root)) {
if !facts
.iter()
.any(|f| f.key == fact.key && f.value == fact.value)
{
facts.push(fact);
}
}
}
/// The facts of an [`Inventory`]; none for a tree without .NET.
fn dotnet_facts(inv: &Inventory) -> Vec<DetectedFact> {
let mut facts = Vec::new();
for runtime in inv.runtimes() {
facts.push(DetectedFact::new(
"dotnet_runtime",
runtime.as_str(),
SOURCE,
));
}
for sln in inv.solutions.iter().take(MAX_FACTS) {
facts.push(DetectedFact::new("dotnet_solution", sln, SOURCE));
}
for project in inv.projects.iter().take(MAX_FACTS) {
let style = if project.sdk_style { "sdk" } else { "legacy" };
let frameworks: Vec<&str> = project
.frameworks
.iter()
.map(|f| f.moniker.as_str())
.collect();
let frameworks = if frameworks.is_empty() {
"inherited".to_string()
} else {
frameworks.join(",")
};
facts.push(DetectedFact::new(
"dotnet_project",
format!("{} ({style}; {frameworks})", project.path),
SOURCE,
));
}
facts
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
#[test]
fn solutions_projects_and_runtimes_are_recorded_at_any_depth() {
let root = std::env::temp_dir().join(format!("cs-dotnet-facts-{}", uuid::Uuid::new_v4()));
let deep = root.join("src/plant/hmi/app");
std::fs::create_dir_all(&deep).expect("mkdir");
std::fs::write(root.join("src/plant/Plant.sln"), "").expect("write");
std::fs::write(root.join("src/Tools.sln"), "").expect("write");
std::fs::write(
deep.join("Hmi.csproj"),
"<Project ToolsVersion=\"15.0\"><PropertyGroup><TargetFrameworkVersion>v4.8</TargetFrameworkVersion></PropertyGroup></Project>",
)
.expect("write");
std::fs::write(
root.join("src/Api.csproj"),
"<Project Sdk=\"Microsoft.NET.Sdk.Web\"><PropertyGroup><TargetFramework>net8.0</TargetFramework></PropertyGroup></Project>",
)
.expect("write");
let mut facts = Vec::new();
add_facts(&mut facts, &root);
add_facts(&mut facts, &root);
let _ = std::fs::remove_dir_all(&root);
let got: Vec<String> = facts
.iter()
.map(|f| format!("{}={}", f.key, f.value))
.collect();
assert_eq!(
got,
[
"dotnet_runtime=dotnet-framework",
"dotnet_runtime=dotnet",
"dotnet_solution=src/Tools.sln",
"dotnet_solution=src/plant/Plant.sln",
"dotnet_project=src/Api.csproj (sdk; net8.0)",
"dotnet_project=src/plant/hmi/app/Hmi.csproj (legacy; net48)",
]
);
}
#[test]
fn a_tree_without_dotnet_adds_nothing() {
let root = std::env::temp_dir().join(format!("cs-dotnet-facts-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&root).expect("mkdir");
std::fs::write(root.join("main.go"), "package main").expect("write");
let mut facts = Vec::new();
add_facts(&mut facts, &root);
let _ = std::fs::remove_dir_all(&root);
assert!(facts.is_empty());
}
}
+15 -1
View File
@@ -5,6 +5,7 @@
//! The registry is the heuristic classifier (artifact kinds + source markers)
//! plus the Firmwerk firmware detector (behind a [`FirmwareDetector`] port).
mod dotnet;
mod firmware;
mod language;
@@ -68,7 +69,20 @@ pub async fn classify_target<D: FirmwareDetector>(
detected_by.push("firmwerk".to_string());
}
Ok(rank(verdicts, detected_by, target.target_type))
let mut classification = rank(verdicts, detected_by, target.target_type);
// The .NET stack at any depth, as facts (#445).
for artifact in &target.artifacts {
if !matches!(
artifact.kind,
ArtifactKind::GitRepo | ArtifactKind::SourceArchive
) {
continue;
}
if let Some(path) = working_paths.get(&artifact.id) {
dotnet::add_facts(&mut classification.facts, path);
}
}
Ok(classification)
}
/// Merge verdicts by target type (keeping the max confidence and its rationale),
+1 -1
View File
@@ -62,7 +62,7 @@ pub enum SbomCoverage {
}
/// The tools that check a target's components rather than its code.
const COMPONENT_TOOLS: [&str; 2] = ["syft", "osv"];
const COMPONENT_TOOLS: [&str; 3] = ["syft", "osv", "dotnet-lifecycle"];
/// The tool a skipped stage of a scan run stands for, when that stage is one
/// a control's binding relies on.
@@ -0,0 +1,711 @@
//! .NET configuration, key files and target frameworks (#445).
//!
//! Three kinds of findings, each from files alone:
//!
//! - **configuration** (`dotnet-config`): `web.config`, `app.config` and other
//! `*.config` files with a clear-text password, debug compilation, detailed
//! errors shown to everyone, cookies without `requireSSL`/`httpOnlyCookies`,
//! or a WCF binding without transport security;
//! - **key and publish files** (`secret-files`): signing keys (`.snk`, `.pfx`,
//! `.p12`), Java/Android keystores (`.jks`, `.keystore`) and publish
//! profiles (`.pubxml`, `.pubxml.user`, `.publishsettings`) committed to
//! the repository;
//! - **target frameworks past their end of support** (`dotnet-lifecycle`).
//!
//! Build output, restored packages and IDE state (`bin/`, `obj/`,
//! `packages/`, `.vs/`) are not read.
use std::path::Path;
use compliance_core::models::{Finding, ScanType, Severity};
use compliance_core::traits::{ScanOutput, Scanner};
use compliance_core::CoreError;
use super::{inventory, line_of, parse_xml, read_text, relative, walk_sources};
use crate::pipeline::dedup;
/// The scanner name of configuration findings.
pub const CONFIG_SCANNER: &str = "dotnet-config";
/// The scanner name of committed key and publish files.
pub const SECRET_FILES_SCANNER: &str = "secret-files";
/// The scanner name of end-of-support target frameworks.
pub const LIFECYCLE_SCANNER: &str = "dotnet-lifecycle";
/// Every scanner name [`DotnetConfigScanner`] reports findings under; a
/// completed scan speaks for all of them.
pub const SCANNERS: [&str; 3] = [CONFIG_SCANNER, SECRET_FILES_SCANNER, LIFECYCLE_SCANNER];
/// What a check found, before it becomes a [`Finding`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Hit {
pub scanner: &'static str,
pub scan_type: ScanType,
pub rule_id: &'static str,
pub title: String,
pub description: String,
pub remediation: &'static str,
pub severity: Severity,
pub cwe: &'static str,
pub path: String,
pub line: Option<u32>,
}
/// The .NET configuration, key-file and lifecycle checks over a tree.
#[derive(Debug, Default)]
pub struct DotnetConfigScanner {
/// The day end-of-support dates are compared with (today, in a scan).
pub today: Option<chrono::NaiveDate>,
}
impl Scanner for DotnetConfigScanner {
fn name(&self) -> &str {
CONFIG_SCANNER
}
fn scan_type(&self) -> ScanType {
ScanType::Sast
}
#[tracing::instrument(skip_all)]
async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result<ScanOutput, CoreError> {
let root = repo_path.to_path_buf();
let today = self
.today
.unwrap_or_else(|| chrono::Utc::now().date_naive());
// A check that did not finish must not read as "nothing found": the
// run would close the findings it reported before.
let hits = tokio::task::spawn_blocking(move || check_tree(&root, today))
.await
.map_err(|e| CoreError::Scanner {
scanner: CONFIG_SCANNER.to_string(),
source: Box::new(e),
})?;
let findings = hits
.into_iter()
.map(|hit| into_finding(repo_path, repo_id, hit))
.collect();
Ok(ScanOutput {
findings,
sbom_entries: Vec::new(),
})
}
}
/// A [`Hit`] as a finding of `repo_id`.
fn into_finding(repo_path: &Path, repo_id: &str, hit: Hit) -> Finding {
let line = hit.line.unwrap_or(0).to_string();
let fingerprint = dedup::compute_fingerprint(&[repo_id, hit.rule_id, &hit.path, &line]);
let mut finding = Finding::new(
repo_id.to_string(),
fingerprint,
hit.scanner.to_string(),
hit.scan_type,
hit.title,
hit.description,
hit.severity,
);
finding.rule_id = Some(hit.rule_id.to_string());
finding.cwe = Some(hit.cwe.to_string());
finding.remediation = Some(hit.remediation.to_string());
finding.code_snippet = hit
.line
.and_then(|l| crate::pipeline::source_text::read_lines(repo_path, &hit.path, l, l));
finding.line_number = hit.line;
finding.file_path = Some(hit.path);
finding
}
/// Every check over the tree under `root`, judged on `today`.
pub(crate) fn check_tree(root: &Path, today: chrono::NaiveDate) -> Vec<Hit> {
let mut hits = Vec::new();
for entry in walk_sources(root) {
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
let path = relative(root, entry.path());
if name.ends_with(".config") && !name.ends_with(".debug.config") {
if let Some(text) = read_text(entry.path()) {
hits.extend(check_config(entry.path(), &path, &text));
}
}
if let Some(hit) = check_key_file(entry.path(), &name, &path) {
hits.push(hit);
}
}
hits.extend(check_frameworks(root, today));
hits
}
/// Values that stand for a secret rather than being one: empty, masked, or a
/// token a deployment substitutes.
fn is_placeholder(value: &str) -> bool {
let v = value.trim().trim_matches(['\'', '"']);
let lower = v.to_ascii_lowercase();
v.is_empty()
|| v.chars()
.all(|c| matches!(c, '*' | 'x' | 'X' | '.' | '-' | '_'))
|| lower.contains("redacted")
|| lower.contains("placeholder")
|| lower.contains("changeme")
|| lower.contains("your_password")
|| lower.contains("yourpassword")
|| (v.starts_with("${") || v.starts_with("$(") || v.starts_with("#{"))
|| (v.starts_with('%') && v.ends_with('%'))
|| (v.starts_with("__") && v.ends_with("__"))
|| (v.starts_with('{') && v.ends_with('}'))
|| (v.starts_with('<') && v.ends_with('>'))
|| (v.starts_with('[') && v.ends_with(']'))
}
/// The password of a connection string (`Password=` or `Pwd=`), when it is a
/// real value. Entity Framework wraps the provider's connection string in
/// quotes; its keys are found the same way.
fn connection_string_password(conn: &str) -> Option<&str> {
conn.split(';').find_map(|part| {
let (key, value) = part.split_once('=')?;
let key = key
.trim()
.trim_start_matches(['"', '\''])
.to_ascii_lowercase();
let key = key.rsplit(['"', ' ']).next().unwrap_or(&key);
(matches!(key, "password" | "pwd") && !is_placeholder(value)).then_some(value)
})
}
/// Setting names under `<appSettings>` that hold a secret.
fn is_secret_setting(key: &str) -> bool {
let k = key.to_ascii_lowercase();
[
"password",
"passwd",
"pwd",
"secret",
"apikey",
"api_key",
"accesskey",
"privatekey",
]
.iter()
.any(|s| k.contains(s))
&& !k.ends_with("file")
&& !k.ends_with("path")
&& !k.contains("length")
&& !k.contains("policy")
}
/// The sibling transform `*.Release.config` of `path`, if any, as text: a
/// release transform that removes `debug` or sets `customErrors` fixes the
/// published configuration, so the base file's development values are fine.
fn release_transform(path: &Path) -> Option<String> {
let stem = path.file_stem()?.to_string_lossy();
let dir = path.parent()?;
let wanted = format!("{stem}.release.config").to_ascii_lowercase();
std::fs::read_dir(dir)
.ok()?
.filter_map(Result::ok)
.find(|e| e.file_name().to_string_lossy().to_ascii_lowercase() == wanted)
.and_then(|e| read_text(&e.path()))
}
/// The checks of one `*.config` file.
fn check_config(full: &Path, path: &str, text: &str) -> Vec<Hit> {
let Some(doc) = parse_xml(text) else {
return Vec::new();
};
let release = release_transform(full).unwrap_or_default();
let mut hits = Vec::new();
let hit = |rule_id, title: String, description: String, remediation, severity, cwe, line| Hit {
scanner: CONFIG_SCANNER,
scan_type: ScanType::Sast,
rule_id,
title,
description,
remediation,
severity,
cwe,
path: path.to_string(),
line: Some(line),
};
let under = |node: roxmltree::Node<'_, '_>, name: &str| {
node.ancestors()
.any(|a| a.is_element() && a.tag_name().name() == name)
};
for node in doc.descendants().filter(|n| n.is_element()) {
let line = line_of(&doc, node);
match node.tag_name().name() {
"add" if under(node, "connectionStrings") => {
let conn = node.attribute("connectionString").unwrap_or_default();
if connection_string_password(conn).is_some() {
let name = node.attribute("name").unwrap_or("a connection string");
hits.push(hit(
"dotnet-config-cleartext-password",
format!("Clear-text database password in connection string \"{name}\""),
"The connection string carries its password in clear text. Everyone \
with access to the repository or the installed application can read \
it, and every installation shares it."
.to_string(),
"Use integrated (Windows) authentication or a managed identity, or \
keep the password out of the file: encrypt the section \
(aspnet_regiis -pe / ProtectedConfigurationProvider) or inject it at \
deployment from a secret store.",
Severity::High,
"CWE-260",
line,
));
}
}
"add" if under(node, "appSettings") => {
let key = node.attribute("key").unwrap_or_default();
let value = node.attribute("value").unwrap_or_default();
if is_secret_setting(key) && value.len() >= 4 && !is_placeholder(value) {
hits.push(hit(
"dotnet-config-cleartext-password",
format!("Clear-text secret in application setting \"{key}\""),
"An application setting named like a password or key holds its value \
in clear text in the configuration file."
.to_string(),
"Move the secret to a secret store or protected configuration and \
inject it at deployment.",
Severity::High,
"CWE-260",
line,
));
}
}
"compilation" if node.attribute("debug").is_some_and(is_true) => {
if !release.contains("RemoveAttributes(debug)") {
hits.push(hit(
"dotnet-config-debug-compilation",
"ASP.NET compiled in debug mode (compilation debug=\"true\")".to_string(),
"Debug compilation disables optimisations and batch compilation and \
keeps debug symbols and detailed errors in the deployed application."
.to_string(),
"Set debug=\"false\" for production, or remove the attribute with a \
Web.Release.config transform (xdt:Transform=\"RemoveAttributes(debug)\").",
Severity::Medium,
"CWE-489",
line,
));
}
}
"customErrors"
if node
.attribute("mode")
.is_some_and(|m| m.eq_ignore_ascii_case("off")) =>
{
if !release.contains("customErrors") {
hits.push(hit(
"dotnet-config-custom-errors-off",
"Detailed ASP.NET errors shown to every client (customErrors mode=\"Off\")"
.to_string(),
"With customErrors off, stack traces, source lines and configuration \
details reach any visitor who triggers an error."
.to_string(),
"Set mode=\"RemoteOnly\" or \"On\" with a generic error page.",
Severity::Medium,
"CWE-209",
line,
));
}
}
"httpCookies" => {
let missing: Vec<&str> = ["requireSSL", "httpOnlyCookies"]
.into_iter()
.filter(|a| !node.attribute(*a).is_some_and(is_true))
.collect();
if !missing.is_empty() {
hits.push(hit(
"dotnet-config-insecure-cookies",
format!("Cookies without {}", missing.join(" and ")),
"Without requireSSL the session and authentication cookies are also \
sent over plain HTTP; without httpOnlyCookies scripts can read them."
.to_string(),
"Set <httpCookies requireSSL=\"true\" httpOnlyCookies=\"true\" />.",
Severity::Medium,
"CWE-614",
line,
));
}
}
"security" if under(node, "bindings") && under(node, "system.serviceModel") => {
let binding_kind = node
.ancestors()
.nth(2)
.map(|n| n.tag_name().name())
.unwrap_or_default();
let mode = node.attribute("mode").unwrap_or_default();
// Named pipes never leave the machine.
let insecure = matches!(mode, "None" | "TransportCredentialOnly")
&& binding_kind != "netNamedPipeBinding";
if insecure {
hits.push(wcf_hit(path, line, binding_kind, mode));
}
}
"binding"
if node.parent().is_some_and(|p| {
p.tag_name().name() == "basicHttpBinding" && under(p, "bindings")
}) && !node
.children()
.any(|c| c.is_element() && c.tag_name().name() == "security") =>
{
hits.push(wcf_hit(path, line, "basicHttpBinding", "None (default)"));
}
"endpoint"
if node.attribute("binding") == Some("basicHttpBinding")
&& node
.attribute("bindingConfiguration")
.is_none_or(str::is_empty)
&& under(node, "system.serviceModel") =>
{
hits.push(wcf_hit(path, line, "basicHttpBinding", "None (default)"));
}
_ => {}
}
}
hits
}
/// An unprotected WCF binding.
fn wcf_hit(path: &str, line: u32, binding: &str, mode: &str) -> Hit {
Hit {
scanner: CONFIG_SCANNER,
scan_type: ScanType::Sast,
rule_id: "dotnet-config-wcf-insecure-binding",
title: format!("WCF {binding} without transport security (mode {mode})"),
description: "Messages of this WCF binding, credentials included, travel unencrypted \
and unauthenticated."
.to_string(),
remediation: "Use security mode=\"Transport\" (HTTPS) or \
\"TransportWithMessageCredential\"; for basicHttpBinding add \
<security mode=\"Transport\" />.",
severity: Severity::High,
cwe: "CWE-319",
path: path.to_string(),
line: Some(line),
}
}
fn is_true(value: &str) -> bool {
value.trim().eq_ignore_ascii_case("true")
}
/// The smallest strong-name key file that holds a private key: a public key
/// alone (`sn -p`) is 160 bytes, a 1024-bit key pair 596.
const SNK_KEY_PAIR_MIN_BYTES: u64 = 300;
/// A key or publish file committed to the repository.
fn check_key_file(full: &Path, name: &str, path: &str) -> Option<Hit> {
let (rule_id, what, severity, cwe, remediation) =
if name.ends_with(".pfx") || name.ends_with(".p12") {
(
"secret-file-private-key",
"A PKCS#12 certificate store (private key) is committed to the repository",
Severity::High,
"CWE-321",
"Remove it from the repository and its history, revoke and replace the \
certificate, and load it from a certificate store or secret store at build time.",
)
} else if name.ends_with(".jks") || name.ends_with(".keystore") {
(
"secret-file-private-key",
"A Java/Android keystore is committed to the repository",
Severity::High,
"CWE-321",
"Remove it from the repository and its history, rotate the keys it holds (for an \
Android upload key, request a reset), and keep it in a secret store used by CI.",
)
} else if name.ends_with(".snk") {
let size = std::fs::metadata(full).map(|m| m.len()).unwrap_or(0);
if size < SNK_KEY_PAIR_MIN_BYTES {
return None;
}
(
"secret-file-signing-key",
"A strong-name key pair (.snk) is committed to the repository",
Severity::Medium,
"CWE-321",
"Keep only the public key in the repository (delay signing, `sn -p`) and sign in \
CI from a protected key.",
)
} else if name.ends_with(".publishsettings") || name.ends_with(".pubxml.user") {
(
"secret-file-publish-profile",
"A publish profile with deployment credentials is committed to the repository",
Severity::High,
"CWE-260",
"Remove it from the repository and its history, reset the deployment credentials, \
and add *.publishsettings and *.pubxml.user to .gitignore.",
)
} else if name.ends_with(".pubxml") {
let has_password = read_text(full).is_some_and(|t| {
let lower = t.to_ascii_lowercase();
lower.contains("<password>") && !lower.contains("<password></password>")
});
if !has_password {
return None;
}
(
"secret-file-publish-profile",
"A publish profile with a deployment password is committed to the repository",
Severity::High,
"CWE-260",
"Remove the password from the profile and its history, reset it, and let Visual \
Studio keep it in the .pubxml.user file (not committed) or use CI secrets.",
)
} else {
return None;
};
Some(Hit {
scanner: SECRET_FILES_SCANNER,
scan_type: ScanType::SecretDetection,
rule_id,
title: what.to_string(),
description: format!(
"{what}. Anyone with read access to the source can use it; a key in the history \
stays there after the file is deleted."
),
remediation,
severity,
cwe,
path: path.to_string(),
line: None,
})
}
/// Projects that target a framework past Microsoft's end of support.
fn check_frameworks(root: &Path, today: chrono::NaiveDate) -> Vec<Hit> {
let mut hits = Vec::new();
for project in inventory(root).projects {
for tf in &project.frameworks {
let Some((ended, product)) = super::end_of_support(&tf.moniker) else {
continue;
};
if ended > today {
continue;
}
hits.push(Hit {
scanner: LIFECYCLE_SCANNER,
scan_type: ScanType::Sbom,
rule_id: "dotnet-framework-end-of-support",
title: format!("{product} is out of support since {ended}"),
description: format!(
"{} targets {product} ({}). Microsoft has not shipped security updates for \
it since {ended}, so vulnerabilities found in the runtime stay open on \
every installation.",
project.path, tf.moniker
),
remediation: "Retarget the project to a supported version (.NET Framework \
4.8/4.8.1, or a supported .NET release) and test it there.",
severity: Severity::Medium,
cwe: "CWE-1104",
path: project.path.clone(),
line: Some(tf.line),
});
}
}
hits
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
struct Tree(std::path::PathBuf);
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn tree(files: &[(&str, &[u8])]) -> Tree {
let dir = std::env::temp_dir().join(format!("cs-dotnet-config-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).expect("mkdir");
for (path, content) in files {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
std::fs::write(full, content).expect("write");
}
Tree(dir)
}
fn today() -> chrono::NaiveDate {
chrono::NaiveDate::from_ymd_opt(2026, 10, 5).unwrap()
}
fn rules(hits: &[Hit]) -> Vec<String> {
let mut out: Vec<String> = hits
.iter()
.map(|h| format!("{} {}:{}", h.rule_id, h.path, h.line.unwrap_or(0)))
.collect();
out.sort();
out
}
const WEB_CONFIG: &str = r#"<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="Plant" connectionString="Data Source=db01;Initial Catalog=Plant;User ID=plant;Password=S3cret!2019" providerName="System.Data.SqlClient" />
<add name="Masked" connectionString="Server=db;User Id=sa;Password=***REDACTED***" />
<add name="Empty" connectionString="Server=db;User Id=sa;Password=;" />
<add name="Integrated" connectionString="Server=db;Integrated Security=SSPI" />
<add name="Ef" connectionString="metadata=res://*/M.csdl;provider connection string=&quot;data source=db;user id=app;pwd=Tr0ub4dor;&quot;" />
</connectionStrings>
<appSettings>
<add key="SmtpPassword" value="mail-pa55" />
<add key="PasswordMinLength" value="12" />
<add key="ApiKey" value="" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.8" />
<customErrors mode="Off" />
<httpCookies httpOnlyCookies="true" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Plain" />
<binding name="Tls"><security mode="Transport" /></binding>
</basicHttpBinding>
<wsHttpBinding>
<binding name="Open"><security mode="None" /></binding>
</wsHttpBinding>
<netNamedPipeBinding>
<binding name="Local"><security mode="None" /></binding>
</netNamedPipeBinding>
</bindings>
<services>
<service name="Plant.Service">
<endpoint address="" binding="basicHttpBinding" contract="IPlant" />
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="Tls" contract="IPlant" />
</service>
</services>
</system.serviceModel>
</configuration>"#;
#[test]
fn a_web_config_yields_each_check_once() {
let t = tree(&[("Web/Web.config", WEB_CONFIG.as_bytes())]);
assert_eq!(
rules(&check_tree(&t.0, today())),
[
"dotnet-config-cleartext-password Web/Web.config:11",
"dotnet-config-cleartext-password Web/Web.config:4",
"dotnet-config-cleartext-password Web/Web.config:8",
"dotnet-config-custom-errors-off Web/Web.config:17",
"dotnet-config-debug-compilation Web/Web.config:16",
"dotnet-config-insecure-cookies Web/Web.config:18",
"dotnet-config-wcf-insecure-binding Web/Web.config:23",
"dotnet-config-wcf-insecure-binding Web/Web.config:27",
"dotnet-config-wcf-insecure-binding Web/Web.config:35",
]
);
}
#[test]
fn a_release_transform_clears_the_development_settings() {
let t = tree(&[
(
"Web/Web.config",
br#"<configuration><system.web>
<compilation debug="true" />
<customErrors mode="Off" />
</system.web></configuration>"#,
),
(
"Web/Web.Release.config",
br#"<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"><system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
<customErrors mode="RemoteOnly" xdt:Transform="Replace" />
</system.web></configuration>"#,
),
]);
assert!(check_tree(&t.0, today()).is_empty());
}
#[test]
fn build_output_and_packages_are_not_read() {
let config = br#"<configuration><system.web><compilation debug="true" /></system.web></configuration>"#;
let t = tree(&[
("Web/bin/Web.dll.config", config),
("Web/obj/Debug/Web.config", config),
("packages/Some.Pkg.1.0.0/content/web.config", config),
("packages/Some.Pkg.1.0.0/Some.Pkg.snk", &[0u8; 596]),
]);
assert!(check_tree(&t.0, today()).is_empty());
}
#[test]
fn key_and_publish_files_are_reported() {
let t = tree(&[
("Signing/Plant.snk", &[7u8; 596]),
("Signing/PublicOnly.snk", &[7u8; 160]),
("Certs/device.pfx", b"\x30\x82"),
("android/app/release.keystore", b"\xfe\xed\xfe\xed"),
(
"Web/Properties/PublishProfiles/Prod.pubxml",
b"<Project><PropertyGroup><UserName>deploy</UserName></PropertyGroup></Project>",
),
(
"Web/Properties/PublishProfiles/Test.pubxml",
b"<Project><PropertyGroup><Password>hunter22</Password></PropertyGroup></Project>",
),
("Web/Prod.PublishSettings", b"<publishData userPWD=\"x\" />"),
]);
assert_eq!(
rules(&check_tree(&t.0, today())),
[
"secret-file-private-key Certs/device.pfx:0",
"secret-file-private-key android/app/release.keystore:0",
"secret-file-publish-profile Web/Prod.PublishSettings:0",
"secret-file-publish-profile Web/Properties/PublishProfiles/Test.pubxml:0",
"secret-file-signing-key Signing/Plant.snk:0",
]
);
}
#[test]
fn frameworks_past_their_support_are_reported() {
let project = |v: &str| {
format!(
"<Project ToolsVersion=\"15.0\">\n<PropertyGroup>\n<TargetFrameworkVersion>{v}</TargetFrameworkVersion>\n</PropertyGroup>\n</Project>"
)
};
let (old, new) = (project("v4.5"), project("v4.8"));
let t = tree(&[
("Legacy/Legacy.csproj", old.as_bytes()),
("Hmi/Hmi.csproj", new.as_bytes()),
]);
let hits = check_tree(&t.0, today());
assert_eq!(
rules(&hits),
["dotnet-framework-end-of-support Legacy/Legacy.csproj:3"]
);
assert_eq!(hits[0].cwe, "CWE-1104");
assert!(
hits[0].title.contains(".NET Framework 4.5"),
"{}",
hits[0].title
);
}
#[test]
fn placeholders_are_not_passwords() {
for p in [
"",
"***REDACTED***",
"${DB_PASSWORD}",
"#{DbPassword}#",
"__DbPassword__",
"%DB_PW%",
"xxxx",
"<password>",
] {
assert!(is_placeholder(p), "{p}");
}
assert!(!is_placeholder("S3cret!2019"));
assert_eq!(
connection_string_password("Server=a;User Id=b;Password=hunter2;"),
Some("hunter2")
);
assert_eq!(
connection_string_password("Server=a;Integrated Security=true"),
None
);
}
}
@@ -0,0 +1,143 @@
//! The .NET Framework 4.8 fixture (`fixtures/dotnet/framework48`) end to end,
//! without a build and without network: inventory, NuGet SBOM, the
//! unresolved-dependency warning, configuration and key-file findings, and
//! what is not own code (#445). The C# rules run when semgrep is installed.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use std::path::{Path, PathBuf};
use compliance_core::traits::Scanner;
use super::config::check_tree;
use super::{inventory, Runtime};
fn fixture() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/dotnet/framework48")
}
#[test]
fn projects_and_runtime_are_detected() {
let inv = inventory(&fixture());
assert_eq!(inv.solutions, ["Plant.sln"]);
let projects: Vec<String> = inv
.projects
.iter()
.map(|p| {
let tfms: Vec<&str> = p.frameworks.iter().map(|f| f.moniker.as_str()).collect();
format!("{} {} {}", p.path, p.sdk_style, tfms.join(","))
})
.collect();
assert_eq!(
projects,
[
"Plant.Hmi/Plant.Hmi.csproj false net48",
"Plant.Legacy/Plant.Legacy.csproj false net40",
"Plant.Web/Plant.Web.csproj false net48",
]
);
assert_eq!(inv.runtimes(), [Runtime::Framework]);
}
#[test]
fn nuget_components_and_the_unresolved_warning() {
let mut purls: Vec<String> = crate::pipeline::sbom::nuget_components(&fixture(), "r")
.into_iter()
.filter_map(|e| e.purl)
.collect();
purls.sort();
assert_eq!(
purls,
[
"pkg:nuget/BouncyCastle@1.8.5",
"pkg:nuget/EntityFramework@6.2.0",
"pkg:nuget/Newtonsoft.Json@12.0.1",
"pkg:nuget/log4net@2.0.8",
]
);
// packages.config lists transitive packages too; the PackageReference
// project without a lockfile does not.
let unresolved: Vec<String> = crate::pipeline::sbom::unlocked_ecosystems(&fixture())
.into_iter()
.map(|u| u.manifest)
.collect();
assert_eq!(unresolved, ["Plant.Web/Plant.Web.csproj"]);
}
#[test]
fn configuration_key_file_and_lifecycle_findings() {
let today = chrono::NaiveDate::from_ymd_opt(2026, 10, 5).unwrap();
let mut hits: Vec<String> = check_tree(&fixture(), today)
.into_iter()
.map(|h| {
format!(
"{} {} {}:{} {}",
h.scanner,
h.rule_id,
h.path,
h.line.unwrap_or(0),
h.cwe
)
})
.collect();
hits.sort();
assert_eq!(
hits,
[
"dotnet-config dotnet-config-cleartext-password Plant.Web/Web.config:4 CWE-260",
"dotnet-config dotnet-config-debug-compilation Plant.Web/Web.config:7 CWE-489",
"dotnet-config dotnet-config-wcf-insecure-binding Plant.Web/Web.config:14 CWE-319",
"dotnet-lifecycle dotnet-framework-end-of-support Plant.Legacy/Plant.Legacy.csproj:6 CWE-1104",
"secret-files secret-file-signing-key Signing/Plant.snk:0 CWE-321",
]
);
}
#[test]
fn build_output_and_restored_packages_are_not_own_code() {
assert_eq!(
crate::pipeline::vendor::vendor_dirs(&fixture()),
["Plant.Hmi/bin", "packages"]
);
}
#[tokio::test]
async fn the_csharp_rules_find_the_planted_weaknesses() {
let installed = std::process::Command::new("semgrep")
.arg("--version")
.output()
.is_ok_and(|o| o.status.success());
if !installed {
eprintln!("semgrep not installed; skipping");
return;
}
let root = fixture();
let vendor = crate::pipeline::vendor::vendor_dirs(&root);
let output = crate::pipeline::semgrep::SemgrepScanner::new(vendor)
.scan(&root, "r")
.await
.expect("semgrep");
let mut found: Vec<String> = output
.findings
.iter()
.map(|f| {
let rule = f.rule_id.as_deref().unwrap_or_default();
let rule = rule.rsplit('.').next().unwrap_or(rule);
format!(
"{rule} {}:{}",
f.file_path.as_deref().unwrap_or_default(),
f.line_number.unwrap_or(0)
)
})
.collect();
found.sort();
assert_eq!(
found,
[
"cra-ai-13-csharp-broken-hash-or-cipher Plant.Web/OrderService.svc.cs:33",
"cra-ai-15-csharp-cert-validation-disabled Plant.Web/OrderService.svc.cs:16",
"cra-ai-20-csharp-sql-string Plant.Web/OrderService.svc.cs:21",
"cra-ai-20-csharp-unsafe-deserialization Plant.Web/OrderService.svc.cs:27",
]
);
}
+461
View File
@@ -0,0 +1,461 @@
//! .NET solutions and projects in a source tree (#445).
//!
//! Read without a build and without `dotnet restore`: the solution and project
//! files are XML and text, and everything here comes from them. Nothing of the
//! customer's is executed, and no package source is contacted.
//!
//! - [`inventory`] lists the solutions (`.sln`) and projects (`.csproj`,
//! `.vbproj`, `.fsproj`) with their project style and target frameworks;
//! - [`end_of_support`] says whether a target framework is past Microsoft's
//! end of support;
//! - [`config`] checks configuration files and committed key files.
pub mod config;
#[cfg(test)]
mod fixture_tests;
use std::path::Path;
/// Directories that hold build output, IDE state, restored packages or test
/// results, never a project's own project files.
pub(crate) const SKIPPED_DIRS: &[&str] = &[
".git",
".vs",
"bin",
"obj",
"packages",
"node_modules",
"TestResults",
];
/// How deep project files are looked for.
const MAX_DEPTH: usize = 16;
/// Largest XML file read (a project file is a few kilobytes; a generated
/// `project.assets.json` can reach a few megabytes).
pub(crate) const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
/// Which .NET a target framework belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Runtime {
/// The Windows-only .NET Framework (1.0 to 4.8.1).
Framework,
/// .NET Core and .NET 5 and later.
Modern,
/// .NET Standard: a contract, not a runtime of its own.
Standard,
}
impl Runtime {
/// The value recorded on the target (`dotnet-framework`, `dotnet`,
/// `dotnet-standard`).
pub fn as_str(self) -> &'static str {
match self {
Runtime::Framework => "dotnet-framework",
Runtime::Modern => "dotnet",
Runtime::Standard => "dotnet-standard",
}
}
}
/// One target framework of a project, as a target framework moniker
/// (`net48`, `net8.0`, `netstandard2.0`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetFramework {
/// The moniker, lower-case, without a platform suffix (`-windows`).
pub moniker: String,
/// The line of the project file that names it (1-based).
pub line: u32,
}
/// A .NET project file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DotnetProject {
/// Relative to the tree, `/`-separated.
pub path: String,
/// SDK style (`<Project Sdk="Microsoft.NET.Sdk">`), as opposed to the old,
/// verbose style of .NET Framework projects.
pub sdk_style: bool,
/// The target frameworks it names; empty when it inherits them (from a
/// `Directory.Build.props`) or names them through a property.
pub frameworks: Vec<TargetFramework>,
}
/// The .NET solutions and projects of a tree.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Inventory {
/// Solution files, relative and sorted. Each one is a component of its own.
pub solutions: Vec<String>,
/// Project files, sorted by path.
pub projects: Vec<DotnetProject>,
}
impl Inventory {
/// Whether the tree holds any .NET solution or project.
pub fn is_empty(&self) -> bool {
self.solutions.is_empty() && self.projects.is_empty()
}
/// The runtimes the projects target, without repeats, in a fixed order.
pub fn runtimes(&self) -> Vec<Runtime> {
let all: Vec<Runtime> = self
.projects
.iter()
.flat_map(|p| &p.frameworks)
.filter_map(|f| runtime_of(&f.moniker))
.collect();
[Runtime::Framework, Runtime::Modern, Runtime::Standard]
.into_iter()
.filter(|r| all.contains(r))
.collect()
}
}
/// Whether `name` is a .NET project file.
pub(crate) fn is_project_file(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
[".csproj", ".vbproj", ".fsproj"]
.iter()
.any(|ext| lower.ends_with(ext))
}
/// Every file under `root` outside [`SKIPPED_DIRS`], to [`MAX_DEPTH`].
pub(crate) fn walk_sources(root: &Path) -> impl Iterator<Item = walkdir::DirEntry> {
walkdir::WalkDir::new(root)
.min_depth(1)
.max_depth(MAX_DEPTH)
.sort_by_file_name()
.into_iter()
.filter_entry(|e| {
!(e.file_type().is_dir()
&& SKIPPED_DIRS
.iter()
.any(|d| e.file_name().to_string_lossy().eq_ignore_ascii_case(d)))
})
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file())
}
/// `path` relative to `root`, `/`-separated.
pub(crate) fn relative(root: &Path, path: &Path) -> String {
path.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.replace('\\', "/")
}
/// The text of a file that may start with a byte-order mark (Visual Studio
/// writes UTF-8 with BOM, older tools UTF-16). `None` for a file too large or
/// unreadable.
pub(crate) fn read_text(path: &Path) -> Option<String> {
let meta = std::fs::metadata(path).ok()?;
if meta.len() > MAX_FILE_BYTES {
return None;
}
let bytes = std::fs::read(path).ok()?;
let utf16 = |bytes: &[u8], le: bool| {
let units: Vec<u16> = bytes
.chunks_exact(2)
.map(|c| {
if le {
u16::from_le_bytes([c[0], c[1]])
} else {
u16::from_be_bytes([c[0], c[1]])
}
})
.collect();
String::from_utf16(&units).ok()
};
match bytes.as_slice() {
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8(rest.to_vec()).ok(),
[0xFF, 0xFE, rest @ ..] => utf16(rest, true),
[0xFE, 0xFF, rest @ ..] => utf16(rest, false),
_ => String::from_utf8(bytes).ok(),
}
}
/// Parse XML the way project and configuration files need: a DTD is allowed
/// (some old `.config` files carry one) but never expanded beyond the
/// parser's limits.
pub(crate) fn parse_xml(text: &str) -> Option<roxmltree::Document<'_>> {
let options = roxmltree::ParsingOptions {
allow_dtd: true,
..roxmltree::ParsingOptions::default()
};
roxmltree::Document::parse_with_options(text, options).ok()
}
/// The 1-based line `node` starts on.
pub(crate) fn line_of(doc: &roxmltree::Document<'_>, node: roxmltree::Node<'_, '_>) -> u32 {
doc.text_pos_at(node.range().start).row
}
/// The .NET solutions and projects under `root`.
pub fn inventory(root: &Path) -> Inventory {
let mut inv = Inventory::default();
for entry in walk_sources(root) {
let name = entry.file_name().to_string_lossy();
if name.to_ascii_lowercase().ends_with(".sln") {
inv.solutions.push(relative(root, entry.path()));
} else if is_project_file(&name) {
let path = relative(root, entry.path());
let project = read_text(entry.path())
.and_then(|text| parse_project(&path, &text))
.unwrap_or(DotnetProject {
path,
sdk_style: false,
frameworks: Vec::new(),
});
inv.projects.push(project);
}
}
inv.solutions.sort();
inv.projects.sort_by(|a, b| a.path.cmp(&b.path));
inv
}
/// Read a project file's style and target frameworks.
fn parse_project(path: &str, text: &str) -> Option<DotnetProject> {
let doc = parse_xml(text)?;
let root = doc.root_element();
let sdk_style = root.attribute("Sdk").is_some()
|| root
.children()
.any(|c| c.is_element() && c.tag_name().name() == "Sdk");
let mut frameworks: Vec<TargetFramework> = Vec::new();
for node in root.descendants().filter(|n| n.is_element()) {
let monikers: Vec<String> = match node.tag_name().name() {
"TargetFramework" | "TargetFrameworks" => node
.text()
.unwrap_or_default()
.split(';')
.filter_map(normalise_moniker)
.collect(),
"TargetFrameworkVersion" => node
.text()
.and_then(framework_version_moniker)
.into_iter()
.collect(),
_ => continue,
};
let line = line_of(&doc, node);
for moniker in monikers {
if !frameworks.iter().any(|f| f.moniker == moniker) {
frameworks.push(TargetFramework { moniker, line });
}
}
}
Some(DotnetProject {
path: path.to_string(),
sdk_style,
frameworks,
})
}
/// A `<TargetFramework>` value as a moniker: lower-case, without the platform
/// suffix (`net8.0-windows` is `net8.0`). `None` for an MSBuild property
/// reference or an empty value.
fn normalise_moniker(raw: &str) -> Option<String> {
let value = raw.trim();
if value.is_empty() || value.contains("$(") {
return None;
}
let base = value.split('-').next().unwrap_or(value);
Some(base.to_ascii_lowercase())
}
/// An old-style `<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>` as
/// a moniker (`net452`).
fn framework_version_moniker(raw: &str) -> Option<String> {
let version = raw.trim().trim_start_matches(['v', 'V']);
if version.is_empty() || !version.chars().all(|c| c.is_ascii_digit() || c == '.') {
return None;
}
Some(format!("net{}", version.replace('.', "")))
}
/// Which runtime a moniker targets; `None` for one this does not know
/// (`uap10.0`, `xamarinios10`, …).
pub fn runtime_of(moniker: &str) -> Option<Runtime> {
if moniker.starts_with("netstandard") {
return Some(Runtime::Standard);
}
if moniker.starts_with("netcoreapp") {
return Some(Runtime::Modern);
}
let rest = moniker.strip_prefix("net")?;
if rest.is_empty() || !rest.chars().all(|c| c.is_ascii_digit() || c == '.') {
return None;
}
// `net5.0` and later carry a dot; .NET Framework monikers never do.
Some(if rest.contains('.') {
Runtime::Modern
} else {
Runtime::Framework
})
}
/// Microsoft's end of support for each target framework that has one, as an
/// ISO date and the name customers know it by. Versions not listed are
/// supported (.NET Framework 4.8 and 4.8.1 follow the Windows they ship with).
///
/// Sources: the .NET Framework and .NET lifecycle pages on
/// learn.microsoft.com (.NET Framework 4.5.2, 4.6 and 4.6.1 ended
/// 2022-04-26, 4.6.2 ends 2027-01-12; .NET 8 and .NET 9 end 2026-11-10).
const END_OF_SUPPORT: &[(&str, &str, &str)] = &[
("net11", "2011-07-12", ".NET Framework 1.1"),
("net20", "2011-07-12", ".NET Framework 2.0"),
("net30", "2011-07-12", ".NET Framework 3.0"),
("net35", "2029-01-09", ".NET Framework 3.5 SP1"),
("net40", "2016-01-12", ".NET Framework 4.0"),
("net403", "2016-01-12", ".NET Framework 4.0.3"),
("net45", "2016-01-12", ".NET Framework 4.5"),
("net451", "2016-01-12", ".NET Framework 4.5.1"),
("net452", "2022-04-26", ".NET Framework 4.5.2"),
("net46", "2022-04-26", ".NET Framework 4.6"),
("net461", "2022-04-26", ".NET Framework 4.6.1"),
("net462", "2027-01-12", ".NET Framework 4.6.2"),
("netcoreapp1.0", "2019-06-27", ".NET Core 1.0"),
("netcoreapp1.1", "2019-06-27", ".NET Core 1.1"),
("netcoreapp2.0", "2018-10-01", ".NET Core 2.0"),
("netcoreapp2.1", "2021-08-21", ".NET Core 2.1"),
("netcoreapp2.2", "2019-12-23", ".NET Core 2.2"),
("netcoreapp3.0", "2020-03-03", ".NET Core 3.0"),
("netcoreapp3.1", "2022-12-13", ".NET Core 3.1"),
("net5.0", "2022-05-10", ".NET 5"),
("net6.0", "2024-11-12", ".NET 6"),
("net7.0", "2024-05-14", ".NET 7"),
("net8.0", "2026-11-10", ".NET 8"),
("net9.0", "2026-11-10", ".NET 9"),
("net10.0", "2028-11-14", ".NET 10"),
];
/// When `moniker` lost (or loses) Microsoft's support, and its product name.
/// `None` for a version without an announced end, or one not known here.
pub fn end_of_support(moniker: &str) -> Option<(chrono::NaiveDate, &'static str)> {
END_OF_SUPPORT
.iter()
.find(|(m, _, _)| *m == moniker)
.and_then(|(_, date, name)| {
chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d")
.ok()
.map(|d| (d, *name))
})
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
/// A scratch tree holding `files` (relative path, content), removed on drop.
pub(crate) struct Tree(pub std::path::PathBuf);
impl Tree {
pub(crate) fn new(files: &[(&str, &str)]) -> Self {
let dir = std::env::temp_dir().join(format!("cs-dotnet-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).expect("mkdir");
for (path, content) in files {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
std::fs::write(full, content).expect("write");
}
Tree(dir)
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
const OLD_STYLE: &str = "\u{feff}<?xml version=\"1.0\" encoding=\"utf-8\"?>
<Project ToolsVersion=\"15.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
</PropertyGroup>
</Project>";
const SDK_STYLE: &str = r#"<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net8.0-windows;net48;$(ExtraTfm)</TargetFrameworks>
</PropertyGroup>
</Project>"#;
#[test]
fn projects_and_solutions_are_found_at_any_depth() {
let tree = Tree::new(&[
("Tools.sln", ""),
("src/Plant/Plant.sln", ""),
("src/Plant/Hmi/Hmi.csproj", OLD_STYLE),
("src/Plant/Service/Service.vbproj", SDK_STYLE),
("src/Plant/Hmi/bin/Debug/Copy.csproj", SDK_STYLE),
("src/Plant/Hmi/obj/Hmi.csproj.nuget.g.props", ""),
]);
let inv = inventory(&tree.0);
assert_eq!(inv.solutions, ["Tools.sln", "src/Plant/Plant.sln"]);
let paths: Vec<&str> = inv.projects.iter().map(|p| p.path.as_str()).collect();
assert_eq!(
paths,
[
"src/Plant/Hmi/Hmi.csproj",
"src/Plant/Service/Service.vbproj"
]
);
let old = &inv.projects[0];
assert!(!old.sdk_style);
assert_eq!(
old.frameworks,
[TargetFramework {
moniker: "net452".into(),
line: 5
}]
);
let sdk = &inv.projects[1];
assert!(sdk.sdk_style);
let monikers: Vec<&str> = sdk.frameworks.iter().map(|f| f.moniker.as_str()).collect();
assert_eq!(monikers, ["net8.0", "net48"]);
assert_eq!(inv.runtimes(), [Runtime::Framework, Runtime::Modern]);
}
#[test]
fn monikers_belong_to_their_runtime() {
assert_eq!(runtime_of("net48"), Some(Runtime::Framework));
assert_eq!(runtime_of("net35"), Some(Runtime::Framework));
assert_eq!(runtime_of("net8.0"), Some(Runtime::Modern));
assert_eq!(runtime_of("netcoreapp3.1"), Some(Runtime::Modern));
assert_eq!(runtime_of("netstandard2.0"), Some(Runtime::Standard));
assert_eq!(runtime_of("uap10.0"), None);
assert_eq!(runtime_of("net"), None);
}
#[test]
fn old_framework_versions_have_ended() {
let today = chrono::NaiveDate::from_ymd_opt(2026, 10, 5).unwrap();
for ended in [
"net40", "net45", "net451", "net452", "net46", "net461", "net6.0",
] {
let (date, _) = end_of_support(ended).expect(ended);
assert!(date <= today, "{ended}");
}
assert!(end_of_support("net48").is_none());
assert!(end_of_support("net481").is_none());
let (net8, name) = end_of_support("net8.0").unwrap();
assert!(net8 > today);
assert_eq!(name, ".NET 8");
}
#[test]
fn utf16_project_files_are_read() {
let tree = Tree::new(&[]);
let path = tree.0.join("Legacy.csproj");
let mut bytes = vec![0xFF, 0xFE];
for unit in "<Project><PropertyGroup><TargetFrameworkVersion>v4.0</TargetFrameworkVersion></PropertyGroup></Project>".encode_utf16() {
bytes.extend(unit.to_le_bytes());
}
std::fs::write(&path, bytes).unwrap();
let inv = inventory(&tree.0);
assert_eq!(inv.projects[0].frameworks[0].moniker, "net40");
}
}
+1
View File
@@ -2,6 +2,7 @@ pub mod code_review;
pub mod cppcheck;
pub mod cve;
pub mod dedup;
pub mod dotnet;
pub mod embedded_versions;
pub mod finding_store;
pub mod firmware_sbom;
@@ -436,6 +436,20 @@ impl PipelineOrchestrator {
}
Err(e) => tracing::warn!("[{repo_id}] OAuth pattern scan failed: {e}"),
}
// .NET configuration, committed key files and end-of-support
// target frameworks (#445), under three scanner names.
let dotnet = crate::pipeline::dotnet::config::DotnetConfigScanner::default();
match dotnet.scan(&repo_path, &repo_id).await {
Ok(output) => {
completed.extend(
crate::pipeline::dotnet::config::SCANNERS
.iter()
.map(|s| s.to_string()),
);
findings.extend(output.findings);
}
Err(e) => tracing::warn!("[{repo_id}] .NET configuration scan failed: {e}"),
}
(findings, completed)
}
.instrument(tracing::info_span!("stage_pattern_scanning"))
+12 -1
View File
@@ -1,6 +1,11 @@
mod cargo_audit;
mod gradle;
mod mobile;
mod nuget;
pub(crate) use nuget::is_restored_package;
#[cfg(test)]
pub(crate) use nuget::nuget_components;
mod syft;
use std::path::Path;
@@ -57,6 +62,10 @@ impl Scanner for SbomScanner {
}
}
// NuGet packages from packages.config, project files and restored
// package folders, which Syft does not read (#445).
nuget::merge_nuget(&mut entries, nuget::nuget_components(repo_path, repo_id));
// Enrich Cargo entries with license info from cargo metadata
enrich_cargo_licenses(repo_path, &mut entries, self.exec).await;
@@ -106,7 +115,8 @@ const NPM_LOCKFILES: &[&str] = &[
///
/// npm, Python and Cargo are checked at the root, where their workspaces keep
/// the lockfile; the mobile package managers anywhere in the tree (see
/// [`mobile`]).
/// [`mobile`]), and every .NET project with `<PackageReference>` items (see
/// [`nuget`]).
pub(crate) fn unlocked_ecosystems(repo_path: &Path) -> Vec<UnlockedEcosystem> {
let has = |name: &str| repo_path.join(name).exists();
let mut out = Vec::new();
@@ -151,6 +161,7 @@ pub(crate) fn unlocked_ecosystems(repo_path: &Path) -> Vec<UnlockedEcosystem> {
});
}
out.extend(mobile::unlocked_mobile_ecosystems(repo_path));
out.extend(nuget::unresolved_projects(repo_path));
out
}
+603
View File
@@ -0,0 +1,603 @@
//! NuGet packages of a .NET tree, read without a build or a restore (#445).
//!
//! Syft reads `packages.lock.json` and `*.deps.json`, which a typical .NET
//! Framework codebase has neither of: its packages are in `packages.config`
//! files, `<PackageReference>` items and the `packages/` folder NuGet restores
//! into (often committed). This reads all of them:
//!
//! - `packages.config`: every package the project installed, transitive ones
//! included (NuGet writes them all there), so such a project is resolved;
//! - `<PackageReference>` in project files, with its version as an attribute,
//! a child element, a `VersionOverride`, or from the central
//! `Directory.Packages.props`; only the direct dependencies;
//! - `packages.lock.json` and `obj/project.assets.json`: the full resolution;
//! - `packages/<Id>.<Version>/` folders: what was restored (and committed).
//!
//! A project with `<PackageReference>` items and neither a lockfile nor an
//! assets file beside it has unknown transitive dependencies:
//! [`unresolved_projects`] reports it, so the SBOM does not look complete.
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use compliance_core::models::SbomEntry;
use super::UnlockedEcosystem;
use crate::pipeline::dotnet::{is_project_file, parse_xml, read_text, relative, walk_sources};
/// The package manager name SBOM entries carry, as Syft names it.
const NUGET: &str = "nuget";
/// One NuGet package as a source names it.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Package {
id: String,
/// The exact version, or `None` when only a range is known.
version: Option<String>,
/// The declared range, when it is not an exact version.
requirement: Option<String>,
}
/// Every NuGet package the tree under `root` names, as SBOM entries with a
/// `pkg:nuget/<id>@<version>` purl for the CVE lookup. A package with only a
/// version range gets no purl (it would match the advisories of every
/// version) and carries the range as its requirement.
pub(crate) fn nuget_components(root: &Path, repo_id: &str) -> Vec<SbomEntry> {
let mut packages: Vec<Package> = Vec::new();
let central = central_versions(root);
for entry in walk_sources(root) {
let name = entry.file_name().to_string_lossy();
let lower = name.to_ascii_lowercase();
if lower == "packages.config" {
packages.extend(read_packages_config(entry.path()));
} else if lower == "packages.lock.json" {
packages.extend(read_lock_file(entry.path()));
} else if is_project_file(&name) {
packages.extend(read_package_references(entry.path(), &central));
// `obj/` is skipped by the walk; the assets file in it is read here.
if let Some(dir) = entry.path().parent() {
packages.extend(read_assets_file(&dir.join("obj/project.assets.json")));
}
}
}
packages.extend(restored_packages(root));
let mut seen: HashSet<(String, String)> = HashSet::new();
let mut out = Vec::new();
for p in packages {
let key = (
p.id.to_ascii_lowercase(),
p.version
.clone()
.or_else(|| p.requirement.clone())
.unwrap_or_default()
.to_ascii_lowercase(),
);
if !seen.insert(key) {
continue;
}
let mut entry = SbomEntry::new(
repo_id.to_string(),
p.id.clone(),
p.version.clone().unwrap_or_default(),
NUGET.to_string(),
);
entry.purl = p
.version
.as_ref()
.map(|v| format!("pkg:nuget/{}@{}", p.id, v));
entry.version_requirement = p.requirement;
out.push(entry);
}
out
}
/// Add the [`nuget_components`] not already in `entries` (Syft reads
/// `packages.lock.json` too). Matched by name and version, case-insensitively,
/// as NuGet ids are.
pub(crate) fn merge_nuget(entries: &mut Vec<SbomEntry>, nuget: Vec<SbomEntry>) {
for n in nuget {
let known = entries.iter().any(|e| {
e.package_manager == NUGET
&& e.name.eq_ignore_ascii_case(&n.name)
&& e.version.eq_ignore_ascii_case(&n.version)
});
if !known {
entries.push(n);
}
}
}
/// The projects whose transitive NuGet dependencies are unknown: they declare
/// `<PackageReference>` items and have no `packages.lock.json` and no
/// `obj/project.assets.json` beside them. A `packages.config` project is
/// never one: its file lists the transitive packages too.
pub(crate) fn unresolved_projects(root: &Path) -> Vec<UnlockedEcosystem> {
walk_sources(root)
.filter(|e| is_project_file(&e.file_name().to_string_lossy()))
.filter(|e| {
read_text(e.path()).is_some_and(|text| text.contains("<PackageReference"))
&& e.path().parent().is_some_and(|dir| {
!dir.join("packages.lock.json").is_file()
&& !dir.join("obj/project.assets.json").is_file()
})
})
.map(|e| UnlockedEcosystem {
manifest: relative(root, e.path()),
problem: "declares NuGet packages with <PackageReference>, but neither a \
packages.lock.json nor an obj/project.assets.json lists the \
transitive ones",
remedy: "set <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile> \
(in the project or a Directory.Build.props), restore once and commit \
packages.lock.json",
})
.collect()
}
/// A version NuGet would restore exactly: `1.2.3`, `[1.2.3]`, `1.2.3-beta`.
/// `None` for a floating version or a range (`1.*`, `[1.0,2.0)`).
fn exact_version(raw: &str) -> Option<String> {
let v = raw.trim();
let v = v
.strip_prefix('[')
.and_then(|s| s.strip_suffix(']'))
.unwrap_or(v)
.trim();
let valid = !v.is_empty()
&& v.chars().next().is_some_and(|c| c.is_ascii_digit())
&& v.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+'))
&& !v.contains('*');
valid.then(|| v.to_string())
}
/// A package from an id and a declared version (exact or a range).
fn package(id: &str, declared: &str) -> Option<Package> {
let id = id.trim();
if id.is_empty() || id.contains("$(") || declared.contains("$(") {
return None;
}
let version = exact_version(declared);
let requirement =
(version.is_none() && !declared.trim().is_empty()).then(|| declared.trim().to_string());
Some(Package {
id: id.to_string(),
version,
requirement,
})
}
/// `<package id="…" version="…" />` entries of a `packages.config`.
fn read_packages_config(path: &Path) -> Vec<Package> {
let Some(text) = read_text(path) else {
return Vec::new();
};
let Some(doc) = parse_xml(&text) else {
return Vec::new();
};
doc.descendants()
.filter(|n| n.is_element() && n.tag_name().name() == "package")
.filter_map(|n| package(n.attribute("id")?, n.attribute("version")?))
.collect()
}
/// The central versions of every `Directory.Packages.props` in the tree, by
/// its directory: `<PackageVersion Include="…" Version="…" />`.
fn central_versions(root: &Path) -> Vec<(PathBuf, HashMap<String, String>)> {
let mut out = Vec::new();
for entry in walk_sources(root) {
if !entry
.file_name()
.to_string_lossy()
.eq_ignore_ascii_case("Directory.Packages.props")
{
continue;
}
let Some(text) = read_text(entry.path()) else {
continue;
};
let Some(doc) = parse_xml(&text) else {
continue;
};
let versions = doc
.descendants()
.filter(|n| n.is_element() && n.tag_name().name() == "PackageVersion")
.filter_map(|n| {
let id = n.attribute("Include").or(n.attribute("Update"))?;
let version = n
.attribute("Version")
.map(str::to_string)
.or_else(|| child_text(n, "Version").map(str::to_string))?;
Some((id.to_ascii_lowercase(), version))
})
.collect();
if let Some(dir) = entry.path().parent() {
out.push((dir.to_path_buf(), versions));
}
}
// Deepest first: the nearest file above a project is the one that applies.
out.sort_by_key(|(dir, _)| std::cmp::Reverse(dir.components().count()));
out
}
/// The text of `node`'s child element `name`.
fn child_text<'a>(node: roxmltree::Node<'a, '_>, name: &str) -> Option<&'a str> {
node.children()
.find(|c| c.is_element() && c.tag_name().name() == name)
.and_then(|c| c.text())
}
/// The `<PackageReference>` items of a project file.
fn read_package_references(
path: &Path,
central: &[(PathBuf, HashMap<String, String>)],
) -> Vec<Package> {
let Some(text) = read_text(path) else {
return Vec::new();
};
let Some(doc) = parse_xml(&text) else {
return Vec::new();
};
let central_for = |id: &str| {
central
.iter()
.find(|(dir, _)| path.starts_with(dir))
.and_then(|(_, versions)| versions.get(&id.to_ascii_lowercase()))
.cloned()
};
doc.descendants()
.filter(|n| n.is_element() && n.tag_name().name() == "PackageReference")
.filter_map(|n| {
let id = n.attribute("Include")?;
let declared = n
.attribute("VersionOverride")
.or(n.attribute("Version"))
.map(str::to_string)
.or_else(|| child_text(n, "VersionOverride").map(str::to_string))
.or_else(|| child_text(n, "Version").map(str::to_string))
.or_else(|| central_for(id))
.unwrap_or_default();
package(id, &declared)
})
.collect()
}
/// The packages of a `packages.lock.json`, every target framework, without
/// the project-to-project references.
fn read_lock_file(path: &Path) -> Vec<Package> {
#[derive(serde::Deserialize)]
struct Lock {
#[serde(default)]
dependencies: HashMap<String, HashMap<String, Locked>>,
}
#[derive(serde::Deserialize)]
struct Locked {
#[serde(rename = "type", default)]
kind: String,
#[serde(default)]
resolved: Option<String>,
}
let Some(lock) = read_text(path).and_then(|t| serde_json::from_str::<Lock>(&t).ok()) else {
return Vec::new();
};
let mut out: Vec<Package> = lock
.dependencies
.into_values()
.flatten()
.filter(|(_, l)| !l.kind.eq_ignore_ascii_case("project"))
.filter_map(|(id, l)| package(&id, l.resolved.as_deref()?))
.collect();
out.sort_by(|a, b| a.id.cmp(&b.id));
out
}
/// The packages of an `obj/project.assets.json` (keys `Id/Version` of its
/// `libraries`), without the project references.
fn read_assets_file(path: &Path) -> Vec<Package> {
#[derive(serde::Deserialize)]
struct Assets {
#[serde(default)]
libraries: HashMap<String, Library>,
}
#[derive(serde::Deserialize)]
struct Library {
#[serde(rename = "type", default)]
kind: String,
}
if !path.is_file() {
return Vec::new();
}
let Some(assets) = read_text(path).and_then(|t| serde_json::from_str::<Assets>(&t).ok()) else {
return Vec::new();
};
let mut out: Vec<Package> = assets
.libraries
.into_iter()
.filter(|(_, l)| l.kind == "package")
.filter_map(|(key, _)| {
let (id, version) = key.split_once('/')?;
package(id, version)
})
.collect();
out.sort_by(|a, b| a.id.cmp(&b.id));
out
}
/// The packages restored into (and often committed with) a `packages/`
/// folder: `packages/<Id>.<Version>/` holding a `.nupkg` or the package's
/// `lib/`. Folders are found next to any solution or project, at any depth.
fn restored_packages(root: &Path) -> Vec<Package> {
let mut out = Vec::new();
let walker = walkdir::WalkDir::new(root)
.min_depth(1)
.max_depth(16)
.sort_by_file_name()
.into_iter()
.filter_entry(|e| {
let name = e.file_name().to_string_lossy();
!(e.file_type().is_dir()
&& [".git", "node_modules", "bin", "obj", ".vs"]
.iter()
.any(|d| name.eq_ignore_ascii_case(d)))
});
let mut walker = walker;
while let Some(entry) = walker.next() {
let Ok(entry) = entry else {
continue;
};
if !entry.file_type().is_dir() || !entry.file_name().eq_ignore_ascii_case("packages") {
continue;
}
let Ok(children) = std::fs::read_dir(entry.path()) else {
continue;
};
let mut found: Vec<Package> = children
.filter_map(Result::ok)
.filter(|c| c.file_type().is_ok_and(|t| t.is_dir()))
.filter(|c| is_restored_package(&c.path()))
.filter_map(|c| split_package_folder(&c.file_name().to_string_lossy()))
.collect();
if !found.is_empty() {
found.sort_by(|a, b| a.id.cmp(&b.id));
out.extend(found);
walker.skip_current_dir();
}
}
out
}
/// Whether `dir` is a package NuGet restored: named `<Id>.<Version>`, and
/// holding a `.nupkg` or the `lib/`, `build/` or `tools/` folder of one. Both
/// are needed: a JavaScript workspace package has a `lib/` too, but not a
/// version in its folder name.
pub(crate) fn is_restored_package(dir: &Path) -> bool {
dir.file_name()
.is_some_and(|n| split_package_folder(&n.to_string_lossy()).is_some())
&& holds_package_content(dir)
}
/// Whether `dir` holds a `.nupkg`, or the `lib/`, `build/` or `tools/` folder
/// of one.
fn holds_package_content(dir: &Path) -> bool {
std::fs::read_dir(dir).is_ok_and(|entries| {
entries.filter_map(Result::ok).any(|e| {
let name = e.file_name().to_string_lossy().to_ascii_lowercase();
name.ends_with(".nupkg")
|| (e.file_type().is_ok_and(|t| t.is_dir())
&& matches!(name.as_str(), "lib" | "build" | "tools"))
})
})
}
/// `Newtonsoft.Json.12.0.1` as id `Newtonsoft.Json` and version `12.0.1`:
/// the version is the shortest dotted tail that is one.
fn split_package_folder(name: &str) -> Option<Package> {
name.match_indices('.').find_map(|(i, _)| {
let (id, rest) = (&name[..i], &name[i + 1..]);
let numeric = rest.split(['-', '+']).next().unwrap_or(rest);
let parts: Vec<&str> = numeric.split('.').collect();
let is_version = (2..=4).contains(&parts.len())
&& parts
.iter()
.all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()));
(is_version && !id.is_empty()).then(|| Package {
id: id.to_string(),
version: Some(rest.to_string()),
requirement: None,
})
})
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
struct Tree(PathBuf);
impl Drop for Tree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn tree(files: &[(&str, &str)]) -> Tree {
let dir = std::env::temp_dir().join(format!("cs-nuget-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).expect("mkdir");
for (path, content) in files {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
std::fs::write(full, content).expect("write");
}
Tree(dir)
}
fn purls(root: &Path) -> Vec<String> {
let mut out: Vec<String> = nuget_components(root, "r")
.into_iter()
.map(|e| {
e.purl
.unwrap_or_else(|| format!("{} {}", e.name, e.version_requirement.unwrap()))
})
.collect();
out.sort();
out
}
#[test]
fn packages_config_lists_its_packages() {
let t = tree(&[(
"Hmi/packages.config",
r#"<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="12.0.1" targetFramework="net48" />
<package id="log4net" version="2.0.8" targetFramework="net48" />
</packages>"#,
)]);
assert_eq!(
purls(&t.0),
[
"pkg:nuget/Newtonsoft.Json@12.0.1",
"pkg:nuget/log4net@2.0.8"
]
);
}
#[test]
fn package_references_take_every_version_form() {
let t = tree(&[
(
"Directory.Packages.props",
r#"<Project><ItemGroup>
<PackageVersion Include="Serilog" Version="2.10.0" />
</ItemGroup></Project>"#,
),
(
"src/App/App.csproj",
r#"<Project Sdk="Microsoft.NET.Sdk"><ItemGroup>
<PackageReference Include="Dapper" Version="2.0.4" />
<PackageReference Include="BouncyCastle">
<Version>1.8.5</Version>
</PackageReference>
<PackageReference Include="Serilog" />
<PackageReference Include="Polly" Version="7.*" />
<PackageReference Include="Exact" Version="[3.1.0]" />
</ItemGroup></Project>"#,
),
]);
assert_eq!(
purls(&t.0),
[
"Polly 7.*",
"pkg:nuget/BouncyCastle@1.8.5",
"pkg:nuget/Dapper@2.0.4",
"pkg:nuget/Exact@3.1.0",
"pkg:nuget/Serilog@2.10.0",
]
);
// Direct references only: the project is reported as unresolved.
let unresolved = unresolved_projects(&t.0);
assert_eq!(unresolved.len(), 1);
assert_eq!(unresolved[0].manifest, "src/App/App.csproj");
}
#[test]
fn lockfiles_and_assets_resolve_the_transitive_packages() {
let t = tree(&[
(
"A/A.csproj",
r#"<Project Sdk="Microsoft.NET.Sdk"><ItemGroup><PackageReference Include="Dapper" Version="2.0.4" /></ItemGroup></Project>"#,
),
(
"A/packages.lock.json",
r#"{"version":1,"dependencies":{"net48":{
"Dapper":{"type":"Direct","requested":"[2.0.4, )","resolved":"2.0.4"},
"System.Memory":{"type":"Transitive","resolved":"4.5.4"},
"B":{"type":"Project"}}}}"#,
),
(
"B/B.csproj",
r#"<Project Sdk="Microsoft.NET.Sdk"><ItemGroup><PackageReference Include="Polly" Version="7.2.1" /></ItemGroup></Project>"#,
),
(
"B/obj/project.assets.json",
r#"{"libraries":{"Polly/7.2.1":{"type":"package"},"A/1.0.0":{"type":"project"}}}"#,
),
]);
assert_eq!(
purls(&t.0),
[
"pkg:nuget/Dapper@2.0.4",
"pkg:nuget/Polly@7.2.1",
"pkg:nuget/System.Memory@4.5.4",
]
);
assert!(unresolved_projects(&t.0).is_empty());
}
#[test]
fn restored_package_folders_are_components() {
let t = tree(&[
("Plant.sln", ""),
(
"packages/Newtonsoft.Json.12.0.1/Newtonsoft.Json.12.0.1.nupkg",
"",
),
(
"packages/EntityFramework.6.2.0/lib/net45/EntityFramework.dll",
"",
),
// Not a restored package: no .nupkg, no lib/.
("packages/widgets/package.json", "{}"),
]);
assert_eq!(
purls(&t.0),
[
"pkg:nuget/EntityFramework@6.2.0",
"pkg:nuget/Newtonsoft.Json@12.0.1",
]
);
}
#[test]
fn package_folder_names_split_at_the_version() {
let split = |n: &str| {
let p = split_package_folder(n).unwrap();
(p.id, p.version.unwrap())
};
assert_eq!(
split("Microsoft.AspNet.Mvc.5.2.7"),
("Microsoft.AspNet.Mvc".into(), "5.2.7".into())
);
assert_eq!(
split("Foo.2.Bar.1.0.0-beta1"),
("Foo.2.Bar".into(), "1.0.0-beta1".into())
);
assert!(split_package_folder("NoVersion").is_none());
}
#[test]
fn syft_entries_are_not_repeated() {
let mut entries = vec![SbomEntry::new(
"r".into(),
"newtonsoft.json".into(),
"12.0.1".into(),
"nuget".into(),
)];
let t = tree(&[(
"packages.config",
r#"<packages><package id="Newtonsoft.Json" version="12.0.1" /><package id="Dapper" version="2.0.4" /></packages>"#,
)]);
merge_nuget(&mut entries, nuget_components(&t.0, "r"));
assert_eq!(entries.len(), 2);
}
#[test]
fn a_packages_config_project_is_resolved() {
let t = tree(&[
(
"Hmi/Hmi.csproj",
"<Project ToolsVersion=\"15.0\"></Project>",
),
("Hmi/packages.config", "<packages />"),
]);
assert!(unresolved_projects(&t.0).is_empty());
}
}
+91 -37
View File
@@ -10,39 +10,55 @@ use crate::pipeline::source_text::{read_lines, relative_path};
/// What open-source semgrep writes in place of the matched code.
const REDACTED_LINES: &str = "requires login";
/// Our own CRA-control rules, bundled into the binary and staged to a temp
/// file at scan time. They are the only rules semgrep runs: the Semgrep
/// registry rules (`--config=auto`, `p/...`) are licensed for internal use
/// only, not for a service offered to others, and `auto` cannot run without
/// sending metrics to Semgrep. Each rule id is keyed back to its control by the
/// `control-map` LUT.
const CRA_RULES: &str = include_str!("../../rules/cra_semgrep.yaml");
/// Our own CRA-control rules, bundled into the binary and staged to temp
/// files at scan time: every `rules/*.yaml` pack, one per language family
/// (a test keeps this list complete). They are the only rules semgrep runs:
/// the Semgrep registry rules (`--config=auto`, `p/...`) are licensed for
/// internal use only, not for a service offered to others, and `auto` cannot
/// run without sending metrics to Semgrep. Each rule id is keyed back to its
/// control by the `control-map` LUT.
///
/// Each pack is staged under its own fixed name: semgrep prefixes a rule's
/// check_id with the config path, and the check_id is part of a finding's
/// fingerprint, so the first pack keeps the name it always had.
const RULE_PACKS: &[(&str, &str)] = &[
(
"compliance-cra-semgrep.yaml",
include_str!("../../rules/cra_semgrep.yaml"),
),
(
"compliance-cra-semgrep-csharp.yaml",
include_str!("../../rules/cra_semgrep_csharp.yaml"),
),
];
/// Write the bundled CRA rules to a stable temp path (atomic: unique tmp +
/// Write the bundled rule packs to stable temp paths (atomic: unique tmp +
/// rename). The tmp name is unique per call, not per process: scans run
/// concurrently in one agent, and a shared tmp file let one scan rename it
/// away while another was still writing it, failing that scan's SAST stage.
///
/// # Errors
///
/// Returns `CoreError::Scanner` when the file cannot be written: without it
/// semgrep has no rules to run, and the stage must read as failed, not clean.
async fn stage_cra_rules() -> Result<PathBuf, CoreError> {
/// Returns `CoreError::Scanner` when a file cannot be written: without it
/// semgrep would skip those rules, and the stage must read as failed, not
/// clean.
async fn stage_cra_rules() -> Result<Vec<PathBuf>, CoreError> {
let dir = std::env::temp_dir();
let path = dir.join("compliance-cra-semgrep.yaml");
let tmp = dir.join(format!(
"compliance-cra-semgrep.{}.tmp",
uuid::Uuid::new_v4()
));
let staged = async {
tokio::fs::write(&tmp, CRA_RULES).await?;
tokio::fs::rename(&tmp, &path).await
};
staged.await.map_err(|e| CoreError::Scanner {
scanner: "semgrep".to_string(),
source: format!("could not stage the CRA rules: {e}").into(),
})?;
Ok(path)
let mut staged_paths = Vec::with_capacity(RULE_PACKS.len());
for (name, rules) in RULE_PACKS {
let path = dir.join(name);
let tmp = dir.join(format!("{name}.{}.tmp", uuid::Uuid::new_v4()));
let staged = async {
tokio::fs::write(&tmp, rules).await?;
tokio::fs::rename(&tmp, &path).await
};
staged.await.map_err(|e| CoreError::Scanner {
scanner: "semgrep".to_string(),
source: format!("could not stage the CRA rules ({name}): {e}").into(),
})?;
staged_paths.push(path);
}
Ok(staged_paths)
}
/// semgrep over a tree, skipping vendor directories.
@@ -70,13 +86,15 @@ impl Scanner for SemgrepScanner {
#[tracing::instrument(skip_all)]
async fn scan(&self, repo_path: &Path, repo_id: &str) -> Result<ScanOutput, CoreError> {
let cra_rules = stage_cra_rules().await?;
let rule_packs = stage_cra_rules().await?;
// Empty environment + kill-on-drop: semgrep only needs to find itself
// and write temp files, and a timed-out run must actually die. No
// metrics and no version check: nothing about a customer's code leaves
// the scan.
let mut command = crate::pipeline::tool_cmd::tool("semgrep", &[]);
command.arg(format!("--config={}", cra_rules.display()));
for pack in &rule_packs {
command.arg(format!("--config={}", pack.display()));
}
command.args([
"--metrics=off",
"--disable-version-check",
@@ -214,21 +232,16 @@ fn extract_cwe(metadata: &serde_json::Value) -> Option<String> {
mod tests {
use super::*;
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_scans_all_get_the_rules() {
let tasks: Vec<_> = (0..32).map(|_| tokio::spawn(stage_cra_rules())).collect();
for task in tasks {
let path = task.await.unwrap().expect("staged");
assert_eq!(std::fs::read_to_string(path).unwrap(), CRA_RULES);
}
}
/// The `languages:` of each rule in our pack, by id. The pack is flat
/// (`- id:` then `languages: [..]`), so lines are enough.
fn rule_languages() -> std::collections::HashMap<String, Vec<String>> {
let mut out = std::collections::HashMap::new();
let mut id = None;
for line in CRA_RULES.lines().map(str::trim) {
for line in RULE_PACKS
.iter()
.flat_map(|(_, rules)| rules.lines())
.map(str::trim)
{
if let Some(rest) = line.strip_prefix("- id:") {
id = Some(rest.trim().to_string());
} else if let (Some(rest), Some(rule)) = (line.strip_prefix("languages:"), id.take()) {
@@ -273,6 +286,47 @@ mod tests {
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_scans_all_get_the_rules() {
let tasks: Vec<_> = (0..32).map(|_| tokio::spawn(stage_cra_rules())).collect();
for task in tasks {
let paths = task.await.unwrap().expect("staged");
assert_eq!(paths.len(), RULE_PACKS.len());
for (path, (_, rules)) in paths.iter().zip(RULE_PACKS) {
assert_eq!(std::fs::read_to_string(path).unwrap(), *rules);
}
}
}
#[test]
fn every_rule_file_is_bundled() {
// A pack added to rules/ but not to RULE_PACKS would never run.
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("rules");
let mut on_disk: Vec<String> = std::fs::read_dir(&dir)
.unwrap_or_else(|e| panic!("{}: {e}", dir.display()))
.filter_map(Result::ok)
.map(|e| e.file_name().to_string_lossy().to_string())
.filter(|n| n.ends_with(".yaml") || n.ends_with(".yml"))
.collect();
on_disk.sort();
let mut bundled: Vec<String> = RULE_PACKS
.iter()
.map(|(_, rules)| {
std::fs::read_dir(&dir)
.unwrap_or_else(|e| panic!("{e}"))
.filter_map(Result::ok)
.find(|e| std::fs::read_to_string(e.path()).is_ok_and(|t| t == *rules))
.map(|e| e.file_name().to_string_lossy().to_string())
.unwrap_or_default()
})
.collect();
bundled.sort();
assert_eq!(on_disk, bundled);
// The first pack keeps its staged name: check_ids, and with them the
// fingerprints of existing findings, depend on it.
assert_eq!(RULE_PACKS[0].0, "compliance-cra-semgrep.yaml");
}
#[test]
fn extract_cwe_handles_list_and_normalises() {
let md = serde_json::json!({"cwe": ["CWE-798: Use of Hard-coded Credentials"]});
+78 -2
View File
@@ -13,7 +13,10 @@
//! `Core/`, `Middlewares/`, and `Middleware/` next to `Drivers/` (the
//! FreeRTOS/ST reference projects);
//! - a vendored library wherever it sits, recognised by the files it always
//! ships (Mbed TLS, lwIP, the FreeRTOS kernel, wolfSSL, FatFs).
//! ships (Mbed TLS, lwIP, the FreeRTOS kernel, wolfSSL, FatFs);
//! - .NET build output and restored packages: `bin/` and `obj/` beside a
//! project or solution, `packages/` holding restored NuGet packages, `.vs/`,
//! `.nuget/` and `TestResults/` (#445).
use std::path::Path;
@@ -137,7 +140,7 @@ fn is_vendor_dir(name: &str, path: &Path) -> bool {
{
return true;
}
is_mobile_build_dir(name, path)
is_mobile_build_dir(name, path) || is_dotnet_build_dir(name, path)
}
/// Unity's generated folders, next to its `ProjectSettings/`.
@@ -173,6 +176,45 @@ fn is_mobile_build_dir(name: &str, path: &Path) -> bool {
}
}
/// .NET directories that are never the project's own code (#445), compared
/// lower-case: Visual Studio's state, NuGet's old tool folder and test
/// results always; `bin/` and `obj/` next to a project file; `packages/`
/// only when it holds restored NuGet packages (a JavaScript monorepo's
/// `packages/` is its own code).
const DOTNET_ALWAYS_DIRS: &[&str] = &[".vs", ".nuget", "testresults"];
/// Whether the directory `name` (lower-cased) at `path` is .NET build output,
/// IDE state or restored NuGet packages.
fn is_dotnet_build_dir(name: &str, path: &Path) -> bool {
if DOTNET_ALWAYS_DIRS.contains(&name) {
return true;
}
let beside_project = || {
path.parent().is_some_and(|parent| {
std::fs::read_dir(parent).is_ok_and(|entries| {
entries.filter_map(Result::ok).any(|e| {
let file = e.file_name().to_string_lossy().to_string();
crate::pipeline::dotnet::is_project_file(&file)
|| file.to_ascii_lowercase().ends_with(".sln")
})
})
})
};
match name {
"bin" | "obj" => beside_project(),
"packages" => {
path.join("repositories.config").is_file()
|| std::fs::read_dir(path).is_ok_and(|entries| {
entries.filter_map(Result::ok).any(|e| {
e.file_type().is_ok_and(|t| t.is_dir())
&& crate::pipeline::sbom::is_restored_package(&e.path())
})
})
}
_ => false,
}
}
/// Whether `path` is one of ST's generated vendor folders, by ST's own
/// capitalisation (a customer's lower-case `middleware/` is their code):
/// `Middlewares/` always, `Middleware/` and `Drivers/` when they sit together.
@@ -388,4 +430,38 @@ mod tests {
]
);
}
#[test]
fn dotnet_build_output_and_restored_packages_are_not_own_code() {
let t = Tree::new(&[
"Plant/Hmi/bin/Debug",
"Plant/Hmi/obj/Debug",
"Plant/.vs/Plant/v17",
"Plant/TestResults/run1",
// A JavaScript monorepo's packages/ (even with compiled lib/) and
// a script bin/ are own code.
"web/packages/widgets/src",
"web/packages/widgets/lib",
"tools/bin",
])
.with_files(&[
"Plant/Plant.sln",
"Plant/Hmi/Hmi.csproj",
"Plant/packages/Newtonsoft.Json.12.0.1/Newtonsoft.Json.12.0.1.nupkg",
"web/packages/widgets/package.json",
"web/packages/widgets/lib/index.js",
"web/package.json",
"tools/bin/deploy.sh",
]);
assert_eq!(
vendor_dirs(&t.0),
[
"Plant/.vs",
"Plant/Hmi/bin",
"Plant/Hmi/obj",
"Plant/TestResults",
"Plant/packages"
]
);
}
}
+135
View File
@@ -37,6 +37,19 @@
"CWE-284"
],
"rules": []
},
{
"tool": "dotnet-config",
"scan_type": "sast",
"languages": [
"csharp"
],
"cwe": [],
"rules": [
"dotnet-config-debug-compilation",
"dotnet-config-custom-errors-off"
],
"check": "The shipped configuration must be secure by default; ASP.NET debug compilation or detailed errors shown to every client violates it."
}
],
"note": null,
@@ -177,6 +190,18 @@
],
"rules": [],
"check": "No credential (password, key, token) may be written into the product's source or configuration: every installation would ship the same secret."
},
{
"tool": "semgrep",
"scan_type": "sast",
"languages": [
"csharp"
],
"cwe": [],
"rules": [
"cra-ai-8-csharp-hardcoded-credential"
],
"check": "No password, key or secret may be written into the source; a real credential assigned to a password- or key-like name violates it."
}
],
"note": null,
@@ -206,6 +231,28 @@
],
"rules": [],
"check": "Credentials must not be kept in plain text in the source or configuration; a real secret committed to the repository violates it."
},
{
"tool": "dotnet-config",
"scan_type": "sast",
"languages": [
"csharp"
],
"cwe": [],
"rules": [
"dotnet-config-cleartext-password"
],
"check": "Credentials must not be kept in plain text in the configuration; a real password in a connection string or application setting violates it."
},
{
"tool": "secret-files",
"scan_type": "secret_detection",
"languages": [],
"cwe": [],
"rules": [
"secret-file-publish-profile"
],
"check": "Credentials must not be kept in the repository; a publish profile with deployment credentials (.publishsettings, .pubxml.user, a .pubxml with a password) violates it."
}
],
"note": null,
@@ -229,6 +276,18 @@
"cra-ai-10-express-cookie-insecure"
],
"check": "Session cookies must be protected: set Secure and HttpOnly (and SameSite). A session cookie configured without them violates it."
},
{
"tool": "dotnet-config",
"scan_type": "sast",
"languages": [
"csharp"
],
"cwe": [],
"rules": [
"dotnet-config-insecure-cookies"
],
"check": "Session and authentication cookies must be Secure and HttpOnly; httpCookies without requireSSL or httpOnlyCookies violates it."
}
],
"note": null,
@@ -329,6 +388,19 @@
],
"rules": [],
"check": "Data must not be protected with a broken algorithm: MD5, SHA-1 or DES used for integrity or confidentiality violates it. A non-security use (a cache key, a checksum of public data) does not."
},
{
"tool": "semgrep",
"scan_type": "sast",
"languages": [
"csharp"
],
"cwe": [],
"rules": [
"cra-ai-13-csharp-broken-hash-or-cipher",
"cra-ai-13-csharp-ecb-mode"
],
"check": "Sensitive data must be protected with current algorithms; MD5, SHA-1, DES, 3DES, RC2 or ECB mode used for it violates it."
}
],
"note": null,
@@ -410,6 +482,30 @@
],
"rules": [],
"check": "Network traffic must use TLS 1.2 or newer with certificate checking; plain HTTP for sensitive data, disabled verification or old protocol versions violate it."
},
{
"tool": "semgrep",
"scan_type": "sast",
"languages": [
"csharp"
],
"cwe": [],
"rules": [
"cra-ai-15-csharp-cert-validation-disabled"
],
"check": "TLS connections must validate the server certificate; a validation callback that accepts every certificate violates it."
},
{
"tool": "dotnet-config",
"scan_type": "sast",
"languages": [
"csharp"
],
"cwe": [],
"rules": [
"dotnet-config-wcf-insecure-binding"
],
"check": "Network traffic must be encrypted; a WCF binding with security mode None or TransportCredentialOnly, or a basicHttpBinding without transport security, violates it."
}
],
"note": null,
@@ -457,6 +553,17 @@
],
"rules": [],
"check": "Keys must not be committed to the source: a private key or secret key in the repository violates it."
},
{
"tool": "secret-files",
"scan_type": "secret_detection",
"languages": [],
"cwe": [],
"rules": [
"secret-file-private-key",
"secret-file-signing-key"
],
"check": "Keys must not be committed to the source: a private-key store (.pfx, .p12, .jks, .keystore) or strong-name key pair (.snk) in the repository violates it."
}
],
"note": null,
@@ -565,6 +672,22 @@
],
"rules": [],
"check": "Untrusted input must not reach a shell, an SQL statement or an HTML response unencoded, and the code must not write past a buffer or let input control a format string: a command or query built from a variable, request input echoed into a response, strcpy, strcat, sprintf, gets, scanf(\"%s\") or a non-literal format argument violates it."
},
{
"tool": "semgrep",
"scan_type": "sast",
"languages": [
"csharp"
],
"cwe": [],
"rules": [
"cra-ai-20-csharp-sql-string",
"cra-ai-20-csharp-process-start",
"cra-ai-20-csharp-unsafe-deserialization",
"cra-ai-20-csharp-xxe",
"cra-ai-20-csharp-path-traversal"
],
"check": "Input from outside must not reach SQL, the command line, a type-resolving deserializer, an XML parser with external entities, or a file path unchecked; such a flow in C# code violates it."
}
],
"note": null,
@@ -594,6 +717,18 @@
"languages": [],
"cwe": [],
"rules": []
},
{
"tool": "dotnet-lifecycle",
"scan_type": "sbom",
"languages": [
"csharp"
],
"cwe": [],
"rules": [
"dotnet-framework-end-of-support"
],
"check": "Components must still receive security updates; a project targeting a .NET or .NET Framework version past Microsoft's end of support violates it."
}
],
"note": null,
+42 -1
View File
@@ -250,6 +250,44 @@ mod tests {
assert!(memory_safety.checked_for(&["cpp".to_string()]));
// gitleaks reads any file, so no language is needed.
assert!(secrets.checked_for(&[]));
// C# is checked for secure defaults by its own rules and the .NET
// configuration checks.
assert!(secure_defaults.checked_for(&["csharp".to_string()]));
assert!(memory_safety.checked_for(&["csharp".to_string()]));
}
#[test]
fn dotnet_findings_attach_to_their_controls() {
let map = ControlMap::cra().expect("map");
let controls = |tool: &str, rule: &str| -> Vec<String> {
map.controls_for_finding(tool, None, Some(rule))
.iter()
.map(|c| c.control.clone())
.collect()
};
assert_eq!(
controls(
"semgrep",
"tmp.compliance-cra-semgrep-csharp.cra-ai-20-csharp-sql-string"
),
["cra-ai-20"]
);
assert_eq!(
controls("dotnet-config", "dotnet-config-cleartext-password"),
["cra-ai-9"]
);
assert_eq!(
controls("dotnet-config", "dotnet-config-wcf-insecure-binding"),
["cra-ai-15"]
);
assert_eq!(
controls("secret-files", "secret-file-private-key"),
["cra-ai-16"]
);
assert_eq!(
controls("dotnet-lifecycle", "dotnet-framework-end-of-support"),
["cra-ai-22"]
);
}
#[test]
@@ -259,7 +297,10 @@ mod tests {
let map = ControlMap::cra().expect("map");
for control in &map.controls {
for scan in &control.scans {
let reads_code = !matches!(scan.tool.as_str(), "gitleaks" | "syft" | "osv");
let reads_code = !matches!(
scan.tool.as_str(),
"gitleaks" | "secret-files" | "syft" | "osv"
);
assert_eq!(
reads_code,
!scan.languages.is_empty(),
+2
View File
@@ -43,6 +43,8 @@ export default withMermaid(defineConfig({
{ text: 'Prüfobjekte anlegen', link: '/guide/repositories' },
{ text: 'Prüfungen', link: '/guide/scanning' },
{ text: 'SPS / PLC (CODESYS)', link: '/guide/plc' },
{ text: '.NET-Projekte', link: '/guide/dotnet' },
{ text: '.NET projects (English)', link: '/guide/dotnet-en' },
{ text: 'Befunde', link: '/guide/findings' },
{ text: 'Befunde aus manuellen Tests', link: '/guide/manual-findings' },
{ text: 'Stückliste (SBOM) und Lizenzen', link: '/guide/sbom' },
+100
View File
@@ -0,0 +1,100 @@
---
title: .NET projects
---
# .NET projects
Prüfwerk checks C# codebases on the classic **.NET Framework** (4.x, old
project style) and on **.NET** (Core, 5 and later, SDK project style).
Everything is read from the files: Prüfwerk builds nothing, runs no
`dotnet restore` and downloads no packages.
## What is checked
**Detection.** Solutions (`.sln`) and projects (`.csproj`, `.vbproj`,
`.fsproj`) at any depth, with their project style (old or SDK) and target
framework(s) (`TargetFrameworkVersion`, `TargetFramework`,
`TargetFrameworks`). The target records them as detected facts:
`dotnet_runtime` (`dotnet-framework`, `dotnet`, `dotnet-standard`), every
solution as a component of its own (`dotnet_solution`) and every project
(`dotnet_project`, e.g. `Plant.Hmi/Plant.Hmi.csproj (legacy; net48)`).
**NuGet SBOM and CVEs.** Packages come from
- `packages.config` (which lists the transitive packages too),
- `<PackageReference>` in project files, with the version as an attribute, a
child element, a `VersionOverride`, or centrally from
`Directory.Packages.props`,
- `packages.lock.json` and `obj/project.assets.json` (the full resolution),
- committed package folders `packages/<Id>.<Version>/`.
Every package with an exact version gets the purl `pkg:nuget/<Id>@<Version>`
and is matched against OSV (ecosystem NuGet). A version range (`7.*`,
`[1.0,2.0)`) is listed without a purl, with the range as its requirement.
**Dependencies not fully resolved.** A project with `<PackageReference>` items
and neither `packages.lock.json` nor `obj/project.assets.json` names only its
direct packages. The scan lists it under **Nicht ausgeführt**
(`sbom_dependencies`), and the SBOM requirements of the CRA view stay **Nicht
bewertet** until a lockfile is committed.
**Recommendation:** switch lockfiles on and commit them:
```xml
<!-- in each project, or once in Directory.Build.props -->
<PropertyGroup>
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
</PropertyGroup>
```
Then restore once (`dotnet restore`, or in Visual Studio) and commit the
`packages.lock.json` files.
**Target framework out of support.** A project targeting a .NET Framework or
.NET version Microsoft no longer ships security updates for (e.g. .NET
Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1; .NET Core 3.1; .NET 5, 6, 7) is
a finding (CWE-1104, CRA requirement dependency monitoring `cra-ai-22`). .NET
Framework 4.6.2 ends on 2027-01-12, .NET 8 and 9 on 2026-11-10; the scan
reports them from then on.
**C# code (our own Semgrep rules):** SQL built by concatenation, interpolation
or `String.Format` (CWE-89), `Process.Start` with a composed command line
(CWE-78), `BinaryFormatter` and friends or JSON.NET `TypeNameHandling` other
than `None` (CWE-502), XML parsing with DTDs or an external resolver (CWE-611),
file paths from `Request` input (CWE-22), MD5/SHA-1/DES/3DES/RC2 and ECB mode
(CWE-327), certificate validation switched off (CWE-295), and hard-coded
passwords and keys (CWE-798). The rule ids and CRA controls are listed on the
[German page](/guide/dotnet).
**Configuration** (`web.config`, `app.config`, other `*.config`): clear-text
passwords in `connectionStrings` and secret-like `appSettings` (not empty,
`***REDACTED***` or deployment placeholders; CWE-260, cra-ai-9), `<compilation
debug="true">` and `<customErrors mode="Off">` unless a `Web.Release.config`
transform fixes them (CWE-489/CWE-209, cra-ai-1), `<httpCookies>` without
`requireSSL`/`httpOnlyCookies` (CWE-614, cra-ai-10), and WCF bindings with
`security mode="None"`/`TransportCredentialOnly` or a `basicHttpBinding`
without transport security (CWE-319, cra-ai-15).
**Keys and publish profiles in the repository** (tool `secret-files`):
`.pfx`/`.p12`, `.jks`/`.keystore` and `.snk` key pairs (CWE-321, cra-ai-16),
`.publishsettings`, `.pubxml.user` and `.pubxml` with a password (CWE-260,
cra-ai-9).
## What does not count as own code
Build output and restored packages: `bin/` and `obj/` beside a project or
solution, `packages/` holding NuGet packages, `.vs/`, `.nuget/` and
`TestResults/`. SAST, patterns, secrets and lint skip them (the scan names
them under **Nicht ausgeführt**); the SBOM still reads `packages/`.
`*.Designer.cs` and generated XAML code stay own code.
## What is not checked (yet)
- No build and no Roslyn analyzers (Security Code Scan): they need a build
that runs project code.
- No data flow across methods: the C# rules see patterns within a method.
- Committed DLLs outside `packages/` (e.g. `lib/`) are not listed as
components with a hash; installers and binaries are not scanned.
- No code graph for C# (tree-sitter), no C# lint rules.
- VB.NET and F# projects are detected and their packages read, but their code
is not checked by rules.
+112
View File
@@ -0,0 +1,112 @@
---
title: .NET-Projekte
---
# .NET-Projekte
Prüfwerk prüft C#-Codebasen mit dem klassischen **.NET Framework** (4.x, alter
Projektstil) und mit **.NET** (Core, 5 und neuer, SDK-Projektstil). Alles wird
aus den Dateien gelesen: Prüfwerk baut nichts, führt kein `dotnet restore` aus
und lädt keine Pakete aus dem Netz.
## Was geprüft wird
**Erkennung.** Solutions (`.sln`) und Projekte (`.csproj`, `.vbproj`,
`.fsproj`) in jeder Verzeichnistiefe, mit Projektstil (alt oder SDK) und
Zielframework(s) (`TargetFrameworkVersion`, `TargetFramework`,
`TargetFrameworks`). Am Prüfobjekt stehen als erkannte Fakten:
`dotnet_runtime` (`dotnet-framework`, `dotnet`, `dotnet-standard`), jede
Solution als eigene Komponente (`dotnet_solution`) und jedes Projekt
(`dotnet_project`, z. B. `Plant.Hmi/Plant.Hmi.csproj (legacy; net48)`).
**NuGet-Stückliste (SBOM) und CVEs.** Die Pakete kommen aus
- `packages.config` (enthält auch die transitiven Pakete),
- `<PackageReference>` in den Projektdateien, mit der Version als Attribut,
als Unterelement, als `VersionOverride` oder zentral aus
`Directory.Packages.props`,
- `packages.lock.json` und `obj/project.assets.json` (vollständige Auflösung),
- eingecheckten Paketordnern `packages/<Id>.<Version>/`.
Jedes Paket mit fester Version erhält die purl `pkg:nuget/<Id>@<Version>` und
wird gegen OSV (Ökosystem NuGet) abgeglichen. Ein Versionsbereich (`7.*`,
`[1.0,2.0)`) steht ohne purl in der Stückliste, mit dem Bereich als
Anforderung.
**Unvollständig aufgelöste Abhängigkeiten.** Ein Projekt mit
`<PackageReference>` ohne `packages.lock.json` und ohne
`obj/project.assets.json` nennt nur seine direkten Pakete. Die Prüfung führt
es unter **Nicht ausgeführt** (`sbom_dependencies`), und die SBOM-Anforderungen
der CRA-Ansicht sind **Nicht bewertet**, bis eine Lockdatei vorliegt.
**Empfehlung:** Lockdateien einschalten und einchecken:
```xml
<!-- in jedem Projekt oder einmal in Directory.Build.props -->
<PropertyGroup>
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
</PropertyGroup>
```
Danach einmal `dotnet restore` (bzw. in Visual Studio wiederherstellen) und die
entstandenen `packages.lock.json` einchecken.
**Zielframework ohne Support.** Ein Projekt, das ein .NET Framework oder .NET
ohne Sicherheitsupdates von Microsoft anspricht (z. B. .NET Framework 4.0,
4.5, 4.5.1, 4.5.2, 4.6, 4.6.1; .NET Core 3.1; .NET 5, 6, 7), ist ein Befund
(CWE-1104, CRA-Anforderung Dependency-Monitoring `cra-ai-22`). .NET Framework
4.6.2 endet am 12.01.2027, .NET 8 und 9 am 10.11.2026; danach meldet die
Prüfung auch sie.
**C#-Code (eigene Semgrep-Regeln).**
| Regel | Was | CWE | CRA |
|---|---|---|---|
| `cra-ai-20-csharp-sql-string` | SQL per Verkettung, Interpolation oder `String.Format` in `SqlCommand`, `CommandText`, `ExecuteSqlCommand`, `FromSqlRaw`, `SqlQuery` | CWE-89 | cra-ai-20 |
| `cra-ai-20-csharp-process-start` | `Process.Start`/`ProcessStartInfo` mit zusammengesetzter Kommandozeile | CWE-78 | cra-ai-20 |
| `cra-ai-20-csharp-unsafe-deserialization` | `BinaryFormatter`, `NetDataContractSerializer`, `LosFormatter`, `SoapFormatter`, `ObjectStateFormatter`, JSON.NET `TypeNameHandling` ≠ `None` | CWE-502 | cra-ai-20 |
| `cra-ai-20-csharp-xxe` | `XmlDocument`/`XmlTextReader` ohne `XmlResolver = null`/`DtdProcessing.Prohibit`, `DtdProcessing.Parse`, `XmlUrlResolver` | CWE-611 | cra-ai-20 |
| `cra-ai-20-csharp-path-traversal` | Dateipfad aus `Request`-Eingaben (`File.*`, `Path.Combine`, `FileStream`) | CWE-22 | cra-ai-20 |
| `cra-ai-13-csharp-broken-hash-or-cipher` | MD5, SHA-1, DES, 3DES, RC2 | CWE-327 | cra-ai-13 |
| `cra-ai-13-csharp-ecb-mode` | `CipherMode.ECB` | CWE-327 | cra-ai-13 |
| `cra-ai-15-csharp-cert-validation-disabled` | Zertifikatsprüfung abgeschaltet (`ServerCertificateValidationCallback … => true`, `DangerousAcceptAnyServerCertificateValidator`) | CWE-295 | cra-ai-15 |
| `cra-ai-8-csharp-hardcoded-credential` | Passwort/Schlüssel als String-Literal | CWE-798 | cra-ai-8 |
**Konfiguration** (`web.config`, `app.config`, weitere `*.config`):
| Regel | Was | CWE | CRA |
|---|---|---|---|
| `dotnet-config-cleartext-password` | `Password=`/`Pwd=` im Klartext in `connectionStrings`; Passwort-/Schlüssel-Einträge in `appSettings` (nicht: leer, `***REDACTED***`, Platzhalter wie `#{…}#`, `${…}`, `__…__`) | CWE-260 | cra-ai-9 |
| `dotnet-config-debug-compilation` | `<compilation debug="true">` (außer eine `Web.Release.config` entfernt es) | CWE-489 | cra-ai-1 |
| `dotnet-config-custom-errors-off` | `<customErrors mode="Off">` (außer die Release-Transformation setzt es) | CWE-209 | cra-ai-1 |
| `dotnet-config-insecure-cookies` | `<httpCookies>` ohne `requireSSL="true"` oder `httpOnlyCookies="true"` | CWE-614 | cra-ai-10 |
| `dotnet-config-wcf-insecure-binding` | WCF-Binding mit `security mode="None"` oder `TransportCredentialOnly`, `basicHttpBinding` ohne Transportsicherheit (Named Pipes ausgenommen) | CWE-319 | cra-ai-15 |
**Schlüssel und Veröffentlichungsprofile im Repository** („Geheimnis im
Repository“, Werkzeug `secret-files`): `.pfx`/`.p12`, `.jks`/`.keystore`
(cra-ai-16, CWE-321), Strong-Name-Schlüsselpaare `.snk` (nur Schlüsselpaare;
eine Datei mit nur dem öffentlichen Schlüssel ist kein Befund),
`.publishsettings`, `.pubxml.user` und `.pubxml` mit Passwort (cra-ai-9,
CWE-260).
## Was nicht als eigener Code zählt
Build-Ausgaben und wiederhergestellte Pakete sind nicht Ihr Code: `bin/` und
`obj/` neben einem Projekt oder einer Solution, `packages/` mit
NuGet-Paketen, `.vs/`, `.nuget/` und `TestResults/`. SAST, Muster, Geheimnisse
und Lint überspringen sie (die Prüfung nennt sie unter **Nicht ausgeführt**);
die Stückliste liest `packages/` trotzdem. `*.Designer.cs` und generierter
XAML-Code bleiben eigener Code.
## Was (noch) nicht geprüft wird
- Kein Build, keine Roslyn-Analyzer (Security Code Scan): sie bräuchten einen
Build mit Ausführung von Projektcode.
- Keine Datenflussanalyse über Methoden hinweg: die C#-Regeln sehen Muster
innerhalb einer Methode.
- Eingecheckte DLLs außerhalb von `packages/` (z. B. `lib/`) werden nicht als
Komponenten mit Hash erfasst; Installer und Binärdateien werden nicht
gescannt.
- Kein Code-Graph für C# (tree-sitter), keine C#-Lint-Regeln.
- VB.NET- und F#-Projekte werden erkannt und ihre Pakete gelesen, aber ihr
Code nicht mit Regeln geprüft.
+4
View File
@@ -31,6 +31,10 @@ Prüfwerk builds the SBOM during each scan:
**Nicht ausgeführt** and the SBOM requirements of the CRA view are
**Nicht bewertet**: an app whose dependencies are unknown is not shown as
clean.
- **.NET / NuGet** -- `packages.config`, `<PackageReference>` (also with
central versions in `Directory.Packages.props`), `packages.lock.json`,
`obj/project.assets.json` and committed `packages/<Id>.<Version>/` folders,
read without a build; see [.NET-Projekte](/guide/dotnet).
- **Libraries copied into a firmware tree** -- microcontroller projects carry
their RTOS, TCP/IP stack and TLS library as source, with no manifest. Prüfwerk
recognises **FreeRTOS**, **FreeRTOS+TCP**, **lwIP**, **Mbed TLS**, **wolfSSL**
+23
View File
@@ -0,0 +1,23 @@
# .NET fixtures (#445)
Source trees standing for a .NET codebase, read by the unit test in
`compliance-agent/src/pipeline/dotnet/fixture_tests.rs` (no build, no network).
## `framework48`
A .NET Framework 4.8 solution in the old project style, the way an industrial
Windows codebase often looks: a WPF client, an ASP.NET/WCF service and an old
tool, NuGet packages in `packages.config` and committed under `packages/`.
| What | Expected |
|---|---|
| `Plant.sln`, three legacy `.csproj` (`v4.8`, `v4.8`, `v4.0`) | one solution, three projects, runtime `dotnet-framework` |
| `Plant.Hmi/packages.config` (EntityFramework 6.2.0, log4net 2.0.8, Newtonsoft.Json 12.0.1) | three NuGet components; Newtonsoft.Json 12.0.1 has GHSA-5crp-9r3c-p9vr |
| `packages/Newtonsoft.Json.12.0.1/` | the same component, not repeated; `packages/` is not own code |
| `Plant.Web/Plant.Web.csproj` with `<PackageReference>` BouncyCastle 1.8.5, no lockfile | the component, and a `sbom_dependencies` skip: transitive packages unknown |
| `Plant.Web/Web.config` | clear-text password, debug compilation, WCF `basicHttpBinding` with `security mode="None"` |
| `Plant.Hmi/App.config` | nothing: integrated security, and a masked password |
| `Plant.Hmi/bin/Debug/Plant.Hmi.exe.config` | nothing: build output |
| `Plant.Legacy` targeting `v4.0` | .NET Framework 4.0 out of support since 2016-01-12 |
| `Signing/Plant.snk` (a 596-byte key pair; dummy bytes) | signing key committed to the repository |
| `Plant.Web/OrderService.svc.cs` | C# rules: SQL by concatenation, BinaryFormatter, MD5, certificate validation off |
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="PlantDb" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Plant;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="Reporting" connectionString="Server=reports;User Id=report;Password=***REDACTED***" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
@@ -0,0 +1,12 @@
using System.Windows;
namespace Plant.Hmi
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<RootNamespace>Plant.Hmi</RootNamespace>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json">
<HintPath>..\packages\Newtonsoft.Json.12.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<Compile Include="MainWindow.xaml.cs" />
<None Include="packages.config" />
<None Include="App.config" />
</ItemGroup>
</Project>
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Build output: a copy of App.config from an old build. Not own code, never reported. -->
<configuration>
<connectionStrings>
<add name="PlantDb" connectionString="Server=plc-db;User Id=sa;Password=BuildCopy2018" />
</connectionStrings>
</configuration>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.2.0" targetFramework="net48" />
<package id="log4net" version="2.0.8" targetFramework="net48" />
<package id="Newtonsoft.Json" version="12.0.1" targetFramework="net48" />
</packages>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<OutputType>Exe</OutputType>
<RootNamespace>Plant.Legacy</RootNamespace>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
</Project>
@@ -0,0 +1,39 @@
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
namespace Plant.Web
{
public class OrderService : IOrderService
{
private readonly SqlConnection _conn;
public OrderService(SqlConnection conn)
{
_conn = conn;
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, errors) => true;
}
public int CountOrders(string customer)
{
var cmd = new SqlCommand("SELECT COUNT(*) FROM Orders WHERE Customer = '" + customer + "'", _conn);
return (int)cmd.ExecuteScalar();
}
public object ReadState(Stream body)
{
var formatter = new BinaryFormatter();
return formatter.Deserialize(body);
}
public byte[] Checksum(byte[] data)
{
using (var md5 = MD5.Create())
{
return md5.ComputeHash(data);
}
}
}
}
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>Plant.Web</RootNamespace>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BouncyCastle">
<Version>1.8.5</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Compile Include="OrderService.svc.cs" />
<Content Include="Web.config" />
</ItemGroup>
</Project>
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="Orders" connectionString="Data Source=db01;Initial Catalog=Orders;User ID=orders;Password=Orders#2019" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.8" />
<httpRuntime targetFramework="4.8" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="OrdersBinding">
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="Plant.Web.OrderService">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="OrdersBinding" contract="Plant.Web.IOrderService" />
</service>
</services>
</system.serviceModel>
</configuration>
+11
View File
@@ -0,0 +1,11 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Plant.Hmi", "Plant.Hmi\Plant.Hmi.csproj", "{6F1B1C1E-1111-4A11-8111-000000000001}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Plant.Web", "Plant.Web\Plant.Web.csproj", "{6F1B1C1E-1111-4A11-8111-000000000002}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Plant.Legacy", "Plant.Legacy\Plant.Legacy.csproj", "{6F1B1C1E-1111-4A11-8111-000000000003}"
EndProject
Global
EndGlobal
Binary file not shown.
@@ -0,0 +1 @@
placeholder for the restored package archive (never opened)
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<repositories>
<repository path="..\Plant.Hmi\packages.config" />
</repositories>