feat(sast): DevSkim for .NET without a build (#494)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 8m32s
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 8m32s
Legacy .NET Framework code often cannot be built outside the customer's Windows toolchain, so no Roslyn analyser applies. DevSkim (MIT, Microsoft) matches its rules on the source text and now runs as the sast_dotnet stage on every tree with C# or VB.NET code: .cs, .vb, Razor/ASP.NET pages and .config files, skipping bin/, obj/, packages/ and vendor directories (anchored at the tree root). - Only DevSkim's own rules at Critical/Important/Moderate (its ManualReview and BestPractice hints are not findings); DS205000 (NuGet feed mapping), DS184626 (controller base class) and DS440000 (generic twin of DS440020) are left out, and two that flood real C# (OpenRA, eShopOnWeb): DS148264 matches any method named Random (71 hits in OpenRA), DS126858 the bare words md5/sha1, identifiers included (35). DS168931 and our own semgrep rules still cover broken hashes and System.Random. What remains: 3 hits in OpenRA (test vectors), 14 Low http:// hits in eShopOnWeb seed data; each run took about 2 s. - SARIF is read with import::sarif::parse; findings are normalised like the other scanners (relative path, whole source line as snippet, one finding per rule/file/line), severity from DevSkim's own Critical/Important/ Moderate (its SARIF level says "error" for both of the first two). - DevSkim's SARIF names no CWE, so pipeline/devskim.rs gives each rule one; the control map binds the devskim tool by CWE to cra-ai-1, 8, 10, 13, 14, 15, 16 and 20 for csharp and vb. A test checks every mapped rule reaches a control. A failed run is a sast_dotnet skip, so those controls read "not assessed" instead of clean. - languages.rs now records VB.NET (vb). Image: the CLI is published as a .NET tool on nuget.org only (no release binaries). Dockerfile.agent pins the 1.0.100 nupkg by sha256 and the .NET 10.0.12 runtime (no SDK) by sha512, keeps only the linux-x64 natives, and runs it through docker/devskim.sh with invariant globalisation (no ICU). The tools stage grows from 1.525 GB to 1.623 GB (+98.5 MB: runtime 80 MB, DevSkim 16 MB). Checked in that image as the unprivileged user with an empty environment and --network none: it runs offline. tool-versions.json lists devskim and dotnet-runtime. Fixtures: fixtures/dotnet/legacy-sample, a small vulnerable C#/VB.NET library with a Web.config (SSL 3, certificate validation off, DES, XXE, BinaryFormatter in VB.NET, tracing, cookies without Secure), and nightly targets for it and for framework48; their baselines need a bless run after deploy. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
This commit is contained in:
1 parent
e51a790d59
commit
05fa4975d8
18 files changed
+902
-3
No files matched your search
+33
-2
@@ -16,6 +16,12 @@ ARG RUFF_VERSION=0.16.8
|
||||
# mobsfscan pins an older semgrep; it is installed without its dependencies so
|
||||
# it runs on the semgrep above, and its other dependencies are pinned here.
|
||||
ARG MOBSFSCAN_VERSION=1.0.1
|
||||
# DevSkim (MIT) is published as a .NET tool on nuget.org, not as a release
|
||||
# binary: the package is pinned by checksum and run on the .NET runtime (MIT).
|
||||
ARG DEVSKIM_VERSION=1.0.100
|
||||
ARG DEVSKIM_SHA256=11a08ca73ef1020c4dd8efaf4e34ce0d59df75eed4fcef478724bc6be28f04fd
|
||||
ARG DOTNET_RUNTIME_VERSION=10.0.12
|
||||
ARG DOTNET_RUNTIME_SHA512=58388fdde4f13bd703c7a6f7defb3300b17e42ba5fe8bca50066f80f64ac7406620dcdfb4acc1eff7992750c8cc5cff8369dd12d09730c8a9e8760d6032f7f6e
|
||||
|
||||
FROM rust:1.94-bookworm AS builder
|
||||
|
||||
@@ -57,6 +63,10 @@ ARG SBOMQS_SHA256
|
||||
ARG SEMGREP_VERSION
|
||||
ARG RUFF_VERSION
|
||||
ARG MOBSFSCAN_VERSION
|
||||
ARG DEVSKIM_VERSION
|
||||
ARG DEVSKIM_SHA256
|
||||
ARG DOTNET_RUNTIME_VERSION
|
||||
ARG DOTNET_RUNTIME_SHA512
|
||||
|
||||
# No recommended packages: python3-pip would otherwise pull in a full C
|
||||
# toolchain, which nothing at runtime needs.
|
||||
@@ -105,11 +115,32 @@ RUN pip3 install --break-system-packages --no-cache-dir --no-deps \
|
||||
"tabulate==0.10.0" "xmltodict==1.0.4"
|
||||
COPY docker/pruefwerk_mobsfscan.py /opt/pruefwerk/pruefwerk_mobsfscan.py
|
||||
|
||||
# .NET SAST without a build (#494): DevSkim on C#, VB.NET and .config files.
|
||||
# The .NET runtime only (no SDK), with invariant globalisation so it needs no
|
||||
# ICU; of DevSkim's bundled native libraries only the linux-x64 ones are kept.
|
||||
# The licence texts stay next to each (LICENSE.txt, ThirdPartyNotices.txt).
|
||||
RUN curl -sSfL -o /tmp/dotnet.tar.gz \
|
||||
"https://builds.dotnet.microsoft.com/dotnet/Runtime/${DOTNET_RUNTIME_VERSION}/dotnet-runtime-${DOTNET_RUNTIME_VERSION}-linux-x64.tar.gz" \
|
||||
&& echo "${DOTNET_RUNTIME_SHA512} /tmp/dotnet.tar.gz" | sha512sum -c - \
|
||||
&& mkdir -p /opt/dotnet \
|
||||
&& tar -xzf /tmp/dotnet.tar.gz -C /opt/dotnet \
|
||||
&& rm /tmp/dotnet.tar.gz \
|
||||
&& curl -sSfL -o /tmp/devskim.nupkg \
|
||||
"https://api.nuget.org/v3-flatcontainer/microsoft.cst.devskim.cli/${DEVSKIM_VERSION}/microsoft.cst.devskim.cli.${DEVSKIM_VERSION}.nupkg" \
|
||||
&& echo "${DEVSKIM_SHA256} /tmp/devskim.nupkg" | sha256sum -c - \
|
||||
&& python3 -c "import zipfile; z = zipfile.ZipFile('/tmp/devskim.nupkg'); \
|
||||
[z.extract(n, '/tmp/devskim') for n in z.namelist() if n.startswith('tools/net10.0/any/') or n == 'LICENSE.txt']" \
|
||||
&& mv /tmp/devskim/tools/net10.0/any /opt/devskim \
|
||||
&& mv /tmp/devskim/LICENSE.txt /opt/devskim/LICENSE.txt \
|
||||
&& rm -rf /tmp/devskim /tmp/devskim.nupkg /opt/devskim/x86 /opt/devskim/amd64 /opt/devskim/arm64 /opt/devskim/*.pdb \
|
||||
&& find /opt/devskim/runtimes -mindepth 1 -maxdepth 1 ! -name linux-x64 -exec rm -rf {} +
|
||||
COPY --chmod=0755 docker/devskim.sh /usr/local/bin/devskim
|
||||
|
||||
RUN mkdir -p /opt/pruefwerk \
|
||||
&& printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","gitleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s","mobsfscan":"%s","sbomqs":"%s"}\n' \
|
||||
&& printf '{"rust":"%s","cargo-audit":"%s","syft":"%s","gitleaks":"%s","semgrep":"%s","ruff":"%s","cppcheck":"%s","mobsfscan":"%s","sbomqs":"%s","devskim":"%s","dotnet-runtime":"%s"}\n' \
|
||||
"${RUST_VERSION}" "${CARGO_AUDIT_VERSION}" "${SYFT_VERSION}" "${GITLEAKS_VERSION}" \
|
||||
"${SEMGREP_VERSION}" "${RUFF_VERSION}" "$(cppcheck --version | cut -d' ' -f2)" \
|
||||
"${MOBSFSCAN_VERSION}" "${SBOMQS_VERSION}" \
|
||||
"${MOBSFSCAN_VERSION}" "${SBOMQS_VERSION}" "${DEVSKIM_VERSION}" "${DOTNET_RUNTIME_VERSION}" \
|
||||
> /opt/pruefwerk/tool-versions.json
|
||||
|
||||
# The agent runs unprivileged. It writes only to its home (tool caches), the
|
||||
|
||||
@@ -71,6 +71,7 @@ pub fn tool_of_stage(stage: &str) -> Option<&'static str> {
|
||||
"sast" => Some("semgrep"),
|
||||
"sast_c_cpp" => Some("cppcheck"),
|
||||
"sast_mobile" => Some("mobsfscan"),
|
||||
"sast_dotnet" => Some("devskim"),
|
||||
"cve_lookup" => Some("osv"),
|
||||
"sbom" => Some("syft"),
|
||||
_ => None,
|
||||
@@ -454,6 +455,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(tool_of_stage("cve_lookup"), Some("osv"));
|
||||
assert_eq!(tool_of_stage("sast_mobile"), Some("mobsfscan"));
|
||||
assert_eq!(tool_of_stage("sast_dotnet"), Some("devskim"));
|
||||
assert_eq!(tool_of_stage("sast_vendor_code"), None);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,506 @@
|
||||
//! .NET SAST without a build: DevSkim (MIT, Microsoft), #494.
|
||||
//!
|
||||
//! Legacy .NET Framework code often cannot be built outside the customer's
|
||||
//! Windows toolchain, so the analysers that need a compilation (Roslyn) do not
|
||||
//! apply. DevSkim matches its rules on the source text: weak hashes and
|
||||
//! ciphers, disabled certificate validation, `BinaryFormatter` and other
|
||||
//! unsafe deserialisers, XXE-prone XML settings, outdated TLS versions,
|
||||
//! secrets in source, and `Web.config` settings (insecure cookies, tracing).
|
||||
//!
|
||||
//! It runs on C#, VB.NET, Razor/ASP.NET pages and `.config` files, with
|
||||
//! DevSkim's default rules at severity Critical, Important or Moderate (its
|
||||
//! ManualReview and BestPractice rules are review hints, not weaknesses). The
|
||||
//! CLI runs offline on the .NET runtime in the agent image
|
||||
//! (`/usr/local/bin/devskim`, see `Dockerfile.agent`) and writes SARIF, read
|
||||
//! with the SARIF import's parser. DevSkim's SARIF carries no CWE, so each rule
|
||||
//! id gets one here ([`cwe_of`]); the control map binds the `devskim` tool by
|
||||
//! CWE.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use compliance_core::models::{Finding, ScanType, Severity};
|
||||
use compliance_core::traits::{ScanOutput, Scanner};
|
||||
use compliance_core::CoreError;
|
||||
|
||||
use crate::import::sarif;
|
||||
use crate::pipeline::dedup;
|
||||
use crate::pipeline::source_text::read_lines;
|
||||
|
||||
/// The wrapper the agent image installs.
|
||||
const DEVSKIM: &str = "devskim";
|
||||
|
||||
/// Source languages DevSkim is run for, by the names
|
||||
/// [`crate::pipeline::languages`] records.
|
||||
const DOTNET_LANGUAGES: [&str; 2] = ["csharp", "vb"];
|
||||
|
||||
/// The files DevSkim reads: .NET code, ASP.NET and Razor pages, and the
|
||||
/// XML configuration (`Web.config`, `App.config`, `NuGet.config`).
|
||||
const INCLUDE_GLOBS: &[&str] = &[
|
||||
"**/*.cs",
|
||||
"**/*.vb",
|
||||
"**/*.cshtml",
|
||||
"**/*.vbhtml",
|
||||
"**/*.razor",
|
||||
"**/*.aspx",
|
||||
"**/*.ascx",
|
||||
"**/*.asmx",
|
||||
"**/*.asax",
|
||||
"**/*.master",
|
||||
"**/*.config",
|
||||
];
|
||||
|
||||
/// Build output and restored packages, wherever they are: not the
|
||||
/// customer's code. Vendor directories are added per tree.
|
||||
const SKIPPED_GLOBS: &[&str] = &[
|
||||
"**/.git/**",
|
||||
"**/bin/**",
|
||||
"**/obj/**",
|
||||
"**/packages/**",
|
||||
"**/node_modules/**",
|
||||
];
|
||||
|
||||
/// DevSkim rules left out on purpose. DS205000 asks for a restricted NuGet
|
||||
/// package source (supply chain configuration; the SBOM stage covers the
|
||||
/// packages themselves), DS184626 for every ASP.NET controller to derive from
|
||||
/// `Controller` (structure, not a weakness).
|
||||
///
|
||||
/// DS440000 is the language-independent twin of DS440020 (a hard-coded TLS
|
||||
/// version) and would report the same line twice.
|
||||
///
|
||||
/// Two flood real C# code (measured on OpenRA and eShopOnWeb, #494): DS148264
|
||||
/// matches any method named `Random` (71 hits in OpenRA, none a security
|
||||
/// value), DS126858 the bare words md5/sha1, also in identifiers such as
|
||||
/// `SHA1Hash` (35). DS168931 still reports .NET's broken hash classes, and
|
||||
/// our own semgrep rules weak hashes and `System.Random`.
|
||||
const IGNORED_RULES: &[&str] = &["DS205000", "DS184626", "DS440000", "DS148264", "DS126858"];
|
||||
|
||||
/// How long a scan may take before it is stopped and recorded as failed.
|
||||
const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);
|
||||
|
||||
/// DevSkim over a tree, skipping vendor and build directories.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct DevskimScanner {
|
||||
/// Directories (relative to the tree) left out of the analysis.
|
||||
excluded: Vec<String>,
|
||||
}
|
||||
|
||||
impl DevskimScanner {
|
||||
/// A scanner for a tree whose source `languages` include C# or VB.NET;
|
||||
/// none otherwise.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `languages` - the source languages found outside vendor code
|
||||
/// * `excluded` - vendor directories relative to the tree
|
||||
pub fn for_languages(languages: &[String], excluded: &[String]) -> Option<Self> {
|
||||
languages
|
||||
.iter()
|
||||
.any(|l| DOTNET_LANGUAGES.contains(&l.as_str()))
|
||||
.then(|| Self {
|
||||
excluded: excluded.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The arguments of the run over `repo_path`, writing SARIF to `report`.
|
||||
fn args(&self, repo_path: &Path, report: &Path) -> Vec<std::ffi::OsString> {
|
||||
// Anchored at the tree: a vendor directory `Drivers` must not also
|
||||
// skip a customer's own `src/Drivers/`.
|
||||
let root = repo_path.to_string_lossy();
|
||||
let root = root.trim_end_matches('/');
|
||||
let ignore: Vec<String> = SKIPPED_GLOBS
|
||||
.iter()
|
||||
.map(|g| (*g).to_string())
|
||||
.chain(self.excluded.iter().map(|dir| format!("{root}/{dir}/**")))
|
||||
.collect();
|
||||
let mut args: Vec<std::ffi::OsString> = vec!["analyze".into(), "-I".into()];
|
||||
args.push(repo_path.into());
|
||||
args.extend(["-O".into(), report.into()]);
|
||||
args.extend(
|
||||
[
|
||||
"-f",
|
||||
"sarif",
|
||||
"--include-globs",
|
||||
&INCLUDE_GLOBS.join(","),
|
||||
"-g",
|
||||
&ignore.join(","),
|
||||
"-s",
|
||||
"Critical,Important,Moderate",
|
||||
"--confidence",
|
||||
"High,Medium",
|
||||
"--ignore-rule-ids",
|
||||
&IGNORED_RULES.join(","),
|
||||
"--skip-excerpts",
|
||||
"--disable-console",
|
||||
]
|
||||
.map(std::ffi::OsString::from),
|
||||
);
|
||||
args
|
||||
}
|
||||
}
|
||||
|
||||
impl Scanner for DevskimScanner {
|
||||
fn name(&self) -> &str {
|
||||
"devskim"
|
||||
}
|
||||
|
||||
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 report = Report::new().map_err(|e| failed(Box::new(e)))?;
|
||||
let mut cmd = crate::pipeline::tool_cmd::tool(DEVSKIM, &[]);
|
||||
cmd.args(self.args(repo_path, &report.0));
|
||||
let output = tokio::time::timeout(TIMEOUT, cmd.output())
|
||||
.await
|
||||
.map_err(|_| failed("timed out after 10 minutes".into()))?
|
||||
.map_err(|e| failed(Box::new(e)))?;
|
||||
if !output.status.success() {
|
||||
// Its log lines name the tool's own state, not the scanned code.
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let tail: String = stderr.lines().rev().take(3).collect::<Vec<_>>().join(" / ");
|
||||
return Err(failed(
|
||||
format!("exited with {}: {tail}", output.status).into(),
|
||||
));
|
||||
}
|
||||
// No report is a failed run, not a clean one.
|
||||
let sarif = std::fs::read(&report.0).map_err(|e| failed(Box::new(e)))?;
|
||||
Ok(ScanOutput {
|
||||
findings: findings(&sarif, repo_path, repo_id)?,
|
||||
sbom_entries: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A scanner error with `source` as its cause.
|
||||
fn failed(source: Box<dyn std::error::Error + Send + Sync>) -> CoreError {
|
||||
CoreError::Scanner {
|
||||
scanner: "devskim".to_string(),
|
||||
source,
|
||||
}
|
||||
}
|
||||
|
||||
/// The SARIF file of one run, removed afterwards.
|
||||
struct Report(PathBuf);
|
||||
|
||||
impl Report {
|
||||
fn new() -> std::io::Result<Self> {
|
||||
let dir = std::env::temp_dir().join("pruefwerk-devskim");
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(Self(dir.join(format!("{}.sarif", uuid::Uuid::new_v4()))))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Report {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The findings of a DevSkim SARIF report on the tree at `root`: one per
|
||||
/// rule, file and line (DevSkim reports each match in a line, e.g. `MD5` and
|
||||
/// `md5` twice).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When the report is not SARIF.
|
||||
fn findings(sarif: &[u8], root: &Path, repo_id: &str) -> Result<Vec<Finding>, CoreError> {
|
||||
let mut seen = HashSet::new();
|
||||
let severities = devskim_severities(sarif)?;
|
||||
let parsed = sarif::parse(sarif)?;
|
||||
Ok(parsed
|
||||
.into_iter()
|
||||
.zip(severities.into_iter().chain(std::iter::repeat(None)))
|
||||
.filter_map(|((_, m), devskim_severity)| {
|
||||
let rule = m.rule_id.clone()?;
|
||||
let (file, line) = split_location(m.location.as_deref()?)?;
|
||||
let fingerprint =
|
||||
dedup::compute_fingerprint(&[repo_id, "devskim", &rule, &file, &line.to_string()]);
|
||||
if !seen.insert(fingerprint.clone()) {
|
||||
return None;
|
||||
}
|
||||
let mut finding = Finding::new(
|
||||
repo_id.to_string(),
|
||||
fingerprint,
|
||||
"devskim".to_string(),
|
||||
ScanType::Sast,
|
||||
m.title,
|
||||
m.description,
|
||||
devskim_severity.map_or(m.severity, severity),
|
||||
);
|
||||
finding.code_snippet = read_lines(root, &file, line, line);
|
||||
finding.cwe = cwe_of(&rule).map(str::to_string);
|
||||
finding.remediation = m.remediation;
|
||||
finding.rule_id = Some(rule);
|
||||
finding.line_number = Some(line);
|
||||
finding.file_path = Some(file);
|
||||
Some(finding)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// DevSkim writes `error` for its Critical and its Important rules alike;
|
||||
/// its own severity, in each result's properties, tells them apart.
|
||||
fn severity(devskim: String) -> Severity {
|
||||
match devskim.as_str() {
|
||||
"Critical" => Severity::High,
|
||||
"Important" => Severity::Medium,
|
||||
"Moderate" => Severity::Low,
|
||||
_ => Severity::Info,
|
||||
}
|
||||
}
|
||||
|
||||
/// Each result's `DevSkimSeverity`, in the order [`sarif::parse`] returns the
|
||||
/// results (runs in order, results in order).
|
||||
fn devskim_severities(sarif: &[u8]) -> Result<Vec<Option<String>>, serde_json::Error> {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Log {
|
||||
runs: Vec<Run>,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Run {
|
||||
#[serde(default)]
|
||||
results: Vec<Entry>,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Entry {
|
||||
#[serde(default)]
|
||||
properties: Option<Properties>,
|
||||
}
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Properties {
|
||||
#[serde(default, rename = "DevSkimSeverity")]
|
||||
severity: Option<String>,
|
||||
}
|
||||
let log: Log = serde_json::from_slice(sarif)?;
|
||||
Ok(log
|
||||
.runs
|
||||
.into_iter()
|
||||
.flat_map(|run| run.results)
|
||||
.map(|r| r.properties.and_then(|p| p.severity))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// `path:line` as the SARIF import writes a location, back into its parts.
|
||||
/// A path outside the tree (absolute, or climbing out) is not a finding of it.
|
||||
fn split_location(location: &str) -> Option<(String, u32)> {
|
||||
let (path, line) = location.rsplit_once(':')?;
|
||||
let line: u32 = line.parse().ok()?;
|
||||
let path = path.trim_start_matches("./").replace('\\', "/");
|
||||
let outside = path.is_empty()
|
||||
|| path.starts_with('/')
|
||||
|| path.contains("://")
|
||||
|| path.split('/').any(|part| part == "..");
|
||||
(!outside).then_some((path, line))
|
||||
}
|
||||
|
||||
/// The CWE of a DevSkim rule (its SARIF names none), for the control map.
|
||||
/// Rules not listed keep no CWE: reported, but bound to no control.
|
||||
pub fn cwe_of(rule: &str) -> Option<&'static str> {
|
||||
Some(match rule {
|
||||
// Outdated or hard-coded TLS versions, encryption marked optional.
|
||||
"DS440000" | "DS440010" | "DS440017" | "DS440020" | "DS440071" | "DS144436"
|
||||
| "DS169125" | "DS169126" => "CWE-757",
|
||||
"DS114352" => "CWE-319",
|
||||
// Plain http:// URLs.
|
||||
"DS137138" => "CWE-319",
|
||||
// Certificate validation switched off.
|
||||
"DS126187" | "DS101155" => "CWE-295",
|
||||
// Broken ciphers and modes.
|
||||
"DS106863" | "DS106864" | "DS109501" | "DS156431" | "DS187371" => "CWE-327",
|
||||
// Broken hashes.
|
||||
"DS126858" | "DS168931" | "DS109733" | "DS197836" => "CWE-328",
|
||||
// Predictable randomness.
|
||||
"DS148264" | "DS149435" => "CWE-338",
|
||||
// Unsafe deserialisers.
|
||||
"DS425040" | "DS425070" | "DS425080" => "CWE-502",
|
||||
// XML external entities.
|
||||
"DS132782" | "DS132783" => "CWE-611",
|
||||
// Tokens, keys and access keys in source.
|
||||
"DS117838" | "DS173237" | "DS173239" | "DS173240" => "CWE-798",
|
||||
"DS173238" => "CWE-321",
|
||||
// Web.config: cookies without Secure, tracing on.
|
||||
"DS450001" => "CWE-614",
|
||||
"DS450002" => "CWE-489",
|
||||
// DPAPI without additional entropy.
|
||||
"DS112266" => "CWE-311",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// What DevSkim 1.0.100 writes for the framework48 fixture (trimmed).
|
||||
const SARIF: &str = r#"{
|
||||
"version": "2.1.0",
|
||||
"runs": [{
|
||||
"tool": {"driver": {"name": "devskim", "rules": [
|
||||
{"id": "DS126858", "name": "WeakbrokenHashAlgorithm",
|
||||
"fullDescription": {"text": "Weak/Broken Hash Algorithm: A weak or broken hash algorithm was detected."},
|
||||
"help": {"text": "Consider switching to use SHA-256 or SHA-512 instead."},
|
||||
"shortDescription": {"text": "A weak or broken hash algorithm was detected."},
|
||||
"properties": {"tags": ["Cryptography.BannedHashAlgorithm"]}},
|
||||
{"id": "DS425070", "shortDescription": {"text": "Do not deserialize untrusted data."}}
|
||||
]}},
|
||||
"results": [
|
||||
{"ruleId": "DS126858", "level": "error", "message": {"text": "Weak/Broken Hash Algorithm"},
|
||||
"locations": [{"physicalLocation": {"artifactLocation": {"uri": "Plant.Web/OrderService.svc.cs"},
|
||||
"region": {"startLine": 33, "snippet": {"text": "MD5"}}}}],
|
||||
"properties": {"DevSkimSeverity": "Critical"}},
|
||||
{"ruleId": "DS126858", "level": "error", "message": {"text": "Weak/Broken Hash Algorithm"},
|
||||
"locations": [{"physicalLocation": {"artifactLocation": {"uri": "Plant.Web/OrderService.svc.cs"},
|
||||
"region": {"startLine": 33, "snippet": {"text": "md5"}}}}]},
|
||||
{"ruleId": "DS425070", "level": "error", "message": {"text": "Do not deserialize untrusted data."},
|
||||
"locations": [{"physicalLocation": {"artifactLocation": {"uri": "Plant.Web/OrderService.svc.cs"},
|
||||
"region": {"startLine": 27}}}],
|
||||
"properties": {"DevSkimSeverity": "Important"}},
|
||||
{"ruleId": "DS137138", "level": "warning", "message": {"text": "Insecure URL"},
|
||||
"locations": [{"physicalLocation": {"artifactLocation": {"uri": "/etc/elsewhere.cs"},
|
||||
"region": {"startLine": 1}}}]}
|
||||
]
|
||||
}]
|
||||
}"#;
|
||||
|
||||
#[test]
|
||||
fn findings_are_normalised_and_deduplicated() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/dotnet/framework48");
|
||||
let found = findings(SARIF.as_bytes(), &root, "repo-1").expect("sarif");
|
||||
// Two matches in one line are one finding; a path outside the tree none.
|
||||
assert_eq!(found.len(), 2, "{found:#?}");
|
||||
let hash = &found[0];
|
||||
assert_eq!(hash.scanner, "devskim");
|
||||
assert_eq!(hash.rule_id.as_deref(), Some("DS126858"));
|
||||
assert_eq!(
|
||||
hash.file_path.as_deref(),
|
||||
Some("Plant.Web/OrderService.svc.cs")
|
||||
);
|
||||
assert_eq!(hash.line_number, Some(33));
|
||||
assert_eq!(hash.cwe.as_deref(), Some("CWE-328"));
|
||||
assert_eq!(hash.severity, Severity::High);
|
||||
assert_eq!(hash.title, "A weak or broken hash algorithm was detected.");
|
||||
assert!(hash
|
||||
.remediation
|
||||
.as_deref()
|
||||
.is_some_and(|r| r.contains("SHA-256")));
|
||||
// The whole line from the tree, not DevSkim's three-letter excerpt.
|
||||
assert!(hash
|
||||
.code_snippet
|
||||
.as_deref()
|
||||
.is_some_and(|s| s.contains("MD5")));
|
||||
assert_eq!(
|
||||
hash.fingerprint,
|
||||
dedup::compute_fingerprint(&[
|
||||
"repo-1",
|
||||
"devskim",
|
||||
"DS126858",
|
||||
"Plant.Web/OrderService.svc.cs",
|
||||
"33"
|
||||
])
|
||||
);
|
||||
assert_eq!(found[1].cwe.as_deref(), Some("CWE-502"));
|
||||
// DevSkim's own severity, not the SARIF level (`error` for both).
|
||||
assert_eq!(found[1].severity, Severity::Medium);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_report_that_is_not_sarif_is_an_error() {
|
||||
assert!(findings(b"{}", Path::new("/tmp"), "r").is_err());
|
||||
assert!(findings(b"not json", Path::new("/tmp"), "r").is_err());
|
||||
// An empty run is a clean result.
|
||||
let empty = r#"{"runs":[{"tool":{"driver":{"name":"devskim"}},"results":[]}]}"#;
|
||||
assert!(findings(empty.as_bytes(), Path::new("/tmp"), "r")
|
||||
.expect("sarif")
|
||||
.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locations_stay_inside_the_tree() {
|
||||
assert_eq!(
|
||||
split_location("a b/W.cs:12"),
|
||||
Some(("a b/W.cs".to_string(), 12))
|
||||
);
|
||||
assert_eq!(
|
||||
split_location("./Web.config:3"),
|
||||
Some(("Web.config".to_string(), 3))
|
||||
);
|
||||
assert_eq!(split_location("/etc/passwd:1"), None);
|
||||
assert_eq!(split_location("../x.cs:1"), None);
|
||||
assert_eq!(split_location("file:///x.cs:1"), None);
|
||||
assert_eq!(split_location("x.cs"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_only_on_dotnet_trees() {
|
||||
let has = |l: &[&str]| {
|
||||
DevskimScanner::for_languages(
|
||||
&l.iter().map(|s| (*s).to_string()).collect::<Vec<_>>(),
|
||||
&[],
|
||||
)
|
||||
.is_some()
|
||||
};
|
||||
assert!(has(&["csharp"]));
|
||||
assert!(has(&["python", "vb"]));
|
||||
assert!(!has(&["python", "c"]));
|
||||
assert!(!has(&[]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_run_is_offline_scoped_and_anchored() {
|
||||
let scanner = DevskimScanner {
|
||||
excluded: vec!["Drivers".to_string(), "third_party/lib".to_string()],
|
||||
};
|
||||
let args: Vec<String> = scanner
|
||||
.args(Path::new("/work/repo/"), Path::new("/tmp/r.sarif"))
|
||||
.iter()
|
||||
.map(|a| a.to_string_lossy().into_owned())
|
||||
.collect();
|
||||
let after = |flag: &str| {
|
||||
let i = args.iter().position(|a| a == flag).expect(flag);
|
||||
args[i + 1].clone()
|
||||
};
|
||||
assert_eq!(args[0], "analyze");
|
||||
assert_eq!(after("-I"), "/work/repo/");
|
||||
assert_eq!(after("-f"), "sarif");
|
||||
assert_eq!(after("-O"), "/tmp/r.sarif");
|
||||
let ignore = after("-g");
|
||||
assert!(ignore.contains("/work/repo/Drivers/**"), "{ignore}");
|
||||
assert!(ignore.contains("/work/repo/third_party/lib/**"), "{ignore}");
|
||||
assert!(ignore.contains("**/bin/**") && ignore.contains("**/obj/**"));
|
||||
assert!(after("--include-globs").contains("**/*.config"));
|
||||
assert_eq!(after("-s"), "Critical,Important,Moderate");
|
||||
// Its own rules only: no rule file from the tree or anywhere else.
|
||||
assert!(!args.iter().any(|a| a == "-r"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_mapped_rule_counts_for_a_control() {
|
||||
// A CWE given here that no `devskim` binding names would leave the
|
||||
// finding without a control.
|
||||
let map = control_map::ControlMap::cra().expect("map");
|
||||
let rules = [
|
||||
"DS440000", "DS440010", "DS440017", "DS440020", "DS440071", "DS144436", "DS169125",
|
||||
"DS169126", "DS114352", "DS137138", "DS126187", "DS101155", "DS106863", "DS106864",
|
||||
"DS109501", "DS156431", "DS187371", "DS126858", "DS168931", "DS109733", "DS197836",
|
||||
"DS148264", "DS149435", "DS425040", "DS425070", "DS425080", "DS132782", "DS132783",
|
||||
"DS117838", "DS173237", "DS173239", "DS173240", "DS173238", "DS450001", "DS450002",
|
||||
"DS112266",
|
||||
];
|
||||
for rule in rules {
|
||||
let cwe = cwe_of(rule).unwrap_or_else(|| panic!("{rule}: no CWE"));
|
||||
let controls = map.controls_for_finding("devskim", Some(cwe), Some(rule));
|
||||
assert!(!controls.is_empty(), "{rule} ({cwe}) maps to no control");
|
||||
}
|
||||
// Every devskim binding claims the .NET languages DevSkim runs on.
|
||||
for control in &map.controls {
|
||||
for binding in control.scans.iter().filter(|b| b.tool == "devskim") {
|
||||
assert_eq!(binding.languages, ["csharp", "vb"], "{}", control.control);
|
||||
}
|
||||
}
|
||||
assert_eq!(cwe_of("DS000000"), None);
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ fn language_of(extension: &str) -> Option<&'static str> {
|
||||
"php" => "php",
|
||||
"rs" => "rust",
|
||||
"cs" => "csharp",
|
||||
"vb" => "vb",
|
||||
"swift" => "swift",
|
||||
// Objective-C; `.m` is also MATLAB's extension, which only means
|
||||
// mobsfscan looks at a tree it finds nothing in.
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod cve;
|
||||
pub(crate) mod cve_enrichment;
|
||||
pub(crate) mod cve_issues;
|
||||
pub mod dedup;
|
||||
pub mod devskim;
|
||||
pub mod dotnet;
|
||||
pub mod embedded_versions;
|
||||
pub mod finding_store;
|
||||
|
||||
@@ -13,6 +13,7 @@ use crate::llm::LlmClient;
|
||||
use crate::pipeline::cppcheck::CppcheckScanner;
|
||||
use crate::pipeline::cve::CveScanner;
|
||||
use crate::pipeline::cve_enrichment::ExploitCache;
|
||||
use crate::pipeline::devskim::DevskimScanner;
|
||||
use crate::pipeline::git::GitOps;
|
||||
use crate::pipeline::gitleaks::GitleaksScanner;
|
||||
use crate::pipeline::grouping::{group_repetitive, GroupingPolicy};
|
||||
@@ -306,6 +307,33 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
}
|
||||
}
|
||||
// C# and VB.NET without a build: DevSkim reads the code, the ASP.NET
|
||||
// pages and the .config files (#494).
|
||||
if let Some(devskim) = DevskimScanner::for_languages(&languages, &vendor) {
|
||||
match devskim
|
||||
.scan(&repo_path, &repo_id)
|
||||
.instrument(tracing::info_span!("stage_sast_dotnet"))
|
||||
.await
|
||||
{
|
||||
Ok(output) => {
|
||||
run_findings.completed("devskim");
|
||||
all_findings.extend(output.findings);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("[{repo_id}] DevSkim failed: {e}");
|
||||
self.skip_stage(
|
||||
scan_run_id,
|
||||
SkippedStage::new(
|
||||
"sast_dotnet",
|
||||
SkipCode::ToolFailed,
|
||||
"DevSkim did not complete",
|
||||
)
|
||||
.about("devskim"),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
run_findings.label(&mut all_findings);
|
||||
group_repetitive(&mut all_findings, &grouping);
|
||||
run_findings.save_new(&self.db, &mut all_findings).await?;
|
||||
|
||||
@@ -427,6 +427,10 @@ pub mod scans {
|
||||
de: "Mobile-App-Analyse (mobsfscan)",
|
||||
en: "Mobile app analysis (mobsfscan)",
|
||||
},
|
||||
"sast_dotnet" => Text {
|
||||
de: ".NET-Analyse (DevSkim)",
|
||||
en: ".NET analysis (DevSkim)",
|
||||
},
|
||||
"lfs_objects" => Text {
|
||||
de: "Git-LFS-Dateien",
|
||||
en: "Git LFS files",
|
||||
|
||||
@@ -90,6 +90,19 @@
|
||||
"elttam-struts-xml-always-select-full-namespace"
|
||||
],
|
||||
"check": "Vendored rules (GitLab, elttam): the shipped configuration must be secure by default; a development mode left on (Struts devMode or dynamic method invocation), permissive CORS, world-writable file permissions, a service bound to all interfaces or a missing input-validation framework violates it."
|
||||
},
|
||||
{
|
||||
"tool": "devskim",
|
||||
"scan_type": "sast",
|
||||
"languages": [
|
||||
"csharp",
|
||||
"vb"
|
||||
],
|
||||
"cwe": [
|
||||
"CWE-489"
|
||||
],
|
||||
"rules": [],
|
||||
"check": "The shipped configuration must be secure by default; ASP.NET tracing switched on in Web.config violates it."
|
||||
}
|
||||
],
|
||||
"note": null,
|
||||
@@ -282,6 +295,19 @@
|
||||
],
|
||||
"rules": [],
|
||||
"check": "Vendored rules (GitLab): no password or key may be written into the source; a real credential assigned in code violates it. A placeholder or an empty value does not."
|
||||
},
|
||||
{
|
||||
"tool": "devskim",
|
||||
"scan_type": "sast",
|
||||
"languages": [
|
||||
"csharp",
|
||||
"vb"
|
||||
],
|
||||
"cwe": [
|
||||
"CWE-798"
|
||||
],
|
||||
"rules": [],
|
||||
"check": "No credential (password, key, token) may be written into the product's source or configuration: every installation would ship the same secret. A placeholder does not violate it."
|
||||
}
|
||||
],
|
||||
"note": null,
|
||||
@@ -385,6 +411,19 @@
|
||||
],
|
||||
"rules": [],
|
||||
"check": "Vendored rules (GitLab, elttam): session state must be protected; cookies without Secure, HttpOnly or a safe SameSite value, and state-changing handlers without CSRF protection violate it."
|
||||
},
|
||||
{
|
||||
"tool": "devskim",
|
||||
"scan_type": "sast",
|
||||
"languages": [
|
||||
"csharp",
|
||||
"vb"
|
||||
],
|
||||
"cwe": [
|
||||
"CWE-614"
|
||||
],
|
||||
"rules": [],
|
||||
"check": "Session and authentication cookies must be Secure; a Web.config that turns the Secure flag off violates it."
|
||||
}
|
||||
],
|
||||
"note": null,
|
||||
@@ -518,6 +557,20 @@
|
||||
"elttam-gcm-static-iv"
|
||||
],
|
||||
"check": "Vendored rules (GitLab, elttam): sensitive data must be protected with current algorithms; DES, RC4, MD5, SHA-1, ECB, RSA without padding, short keys, a static GCM nonce or a timing-unsafe comparison of secrets violates it. A non-security use (a cache key, a checksum of public data) does not."
|
||||
},
|
||||
{
|
||||
"tool": "devskim",
|
||||
"scan_type": "sast",
|
||||
"languages": [
|
||||
"csharp",
|
||||
"vb"
|
||||
],
|
||||
"cwe": [
|
||||
"CWE-327",
|
||||
"CWE-328"
|
||||
],
|
||||
"rules": [],
|
||||
"check": "Data must not be protected with a broken algorithm: MD5, SHA-1, DES, 3DES, RC2 or ECB mode used for integrity or confidentiality violates it. A non-security use (a cache key, a checksum of public data) does not."
|
||||
}
|
||||
],
|
||||
"note": null,
|
||||
@@ -575,6 +628,19 @@
|
||||
"cra-ai-14-objc-secret-in-userdefaults"
|
||||
],
|
||||
"check": "An iOS app must keep passwords, tokens and keys in the Keychain; storing them in UserDefaults (also through @AppStorage), an unencrypted plist in the app container, violates it. The Objective-C rule is a regex pattern (semgrep has no Objective-C parser), hence the regex language."
|
||||
},
|
||||
{
|
||||
"tool": "devskim",
|
||||
"scan_type": "sast",
|
||||
"languages": [
|
||||
"csharp",
|
||||
"vb"
|
||||
],
|
||||
"cwe": [
|
||||
"CWE-311"
|
||||
],
|
||||
"rules": [],
|
||||
"check": "Data protected with DPAPI (ProtectedData) needs additional entropy; without it any process of the same user can read it."
|
||||
}
|
||||
],
|
||||
"note": null,
|
||||
@@ -658,6 +724,21 @@
|
||||
],
|
||||
"rules": [],
|
||||
"check": "Vendored rules (GitLab): network traffic must use TLS 1.2 or newer with certificate and host checking; disabled verification, plain-text protocols (HTTP, FTP, SMTP, telnet) for sensitive data or an old protocol version violates it."
|
||||
},
|
||||
{
|
||||
"tool": "devskim",
|
||||
"scan_type": "sast",
|
||||
"languages": [
|
||||
"csharp",
|
||||
"vb"
|
||||
],
|
||||
"cwe": [
|
||||
"CWE-295",
|
||||
"CWE-319",
|
||||
"CWE-757"
|
||||
],
|
||||
"rules": [],
|
||||
"check": "Network traffic must use TLS 1.2 or newer with certificate checking; a disabled certificate check, an outdated or hard-coded old protocol version, or plain http:// for data that needs protection violates it."
|
||||
}
|
||||
],
|
||||
"note": null,
|
||||
@@ -736,6 +817,20 @@
|
||||
],
|
||||
"rules": [],
|
||||
"check": "Vendored rules (GitLab, 0xdea): keys, tokens and nonces need a cryptographically secure random generator; rand(), java.util.Random, Math.random or the random module for them violates it."
|
||||
},
|
||||
{
|
||||
"tool": "devskim",
|
||||
"scan_type": "sast",
|
||||
"languages": [
|
||||
"csharp",
|
||||
"vb"
|
||||
],
|
||||
"cwe": [
|
||||
"CWE-338",
|
||||
"CWE-321"
|
||||
],
|
||||
"rules": [],
|
||||
"check": "Keys, tokens and nonces need a cryptographic random generator (RandomNumberGenerator), and private keys must not be committed; System.Random or a time-based seed for them violates it."
|
||||
}
|
||||
],
|
||||
"note": null,
|
||||
@@ -942,6 +1037,20 @@
|
||||
"elttam-UnsafeHttpInvokerServiceExporter-XML"
|
||||
],
|
||||
"check": "Vendored rules (GitLab, 0xdea, elttam): untrusted input must not reach an interpreter, the file system, a deserialiser or a fixed-size buffer unchecked; injection (SQL, OS command, LDAP, XPath, XSS, template), path traversal, unsafe deserialisation, XXE, SSRF, open redirects, and memory errors (unbounded copies, off-by-one, use after free, double free, integer wraparound) violate it."
|
||||
},
|
||||
{
|
||||
"tool": "devskim",
|
||||
"scan_type": "sast",
|
||||
"languages": [
|
||||
"csharp",
|
||||
"vb"
|
||||
],
|
||||
"cwe": [
|
||||
"CWE-502",
|
||||
"CWE-611"
|
||||
],
|
||||
"rules": [],
|
||||
"check": "Untrusted input must not reach an unsafe deserialiser (BinaryFormatter, NetDataContractSerializer, SoapFormatter, LosFormatter) or an XML parser that resolves external entities."
|
||||
}
|
||||
],
|
||||
"note": null,
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
# DevSkim CLI (MIT, Microsoft) on the .NET runtime installed by Dockerfile.agent
|
||||
# (#494). Invariant globalisation: the image has no ICU, and DevSkim matches
|
||||
# patterns, it formats nothing for a locale. It makes no network calls.
|
||||
export DOTNET_ROOT=/opt/dotnet
|
||||
export DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1
|
||||
export DOTNET_CLI_TELEMETRY_OPTOUT=1
|
||||
export DOTNET_NOLOGO=1
|
||||
exec /opt/dotnet/dotnet /opt/devskim/devskim.dll "$@"
|
||||
@@ -29,6 +29,7 @@ For the **CRA** framework (40 controls) the split is **21 covered · 0 needs_too
|
||||
- for C and C++ firmware: `cra-ai-8`, `13`, `16`, `20` (hard-coded credentials including `#define` macros, broken hash/cipher, `rand()`, unbounded string functions and non-literal format strings), next to cppcheck for memory safety.
|
||||
- **Vendored semgrep packs** (GitLab, 0xdea, elttam; #492), bound **by CWE** like off-the-shelf tools, on a semgrep binding of their own per control whose `languages` are exactly those of the vendored rules under those CWEs (a test checks every vendored rule maps to a control that claims its languages). The few elttam rules without a CWE are bound by rule id. Because these bindings are `semgrep` bindings, a CWE they list also attaches our own semgrep findings with that CWE to the control.
|
||||
- **mobsfscan** for Android and iOS apps, bound **by CWE** (a mobsfscan binding only ever attaches mobsfscan findings): `cra-ai-1` (debuggable, exported components, outdated `minSdkVersion`), `7`, `8`, `9`, `13`, `14`, `15` (cleartext, TLS, App Transport Security), `16` and `20`. Each binding lists only the languages mobsfscan has rules for under those CWEs, so `cra-ai-1` covers Java and Kotlin (its manifest checks) but not Swift.
|
||||
- **DevSkim** for C# and VB.NET (#494), bound **by CWE** (each DevSkim rule gets its CWE in `pipeline/devskim.rs`; its SARIF carries none): `cra-ai-1` (tracing), `8`, `10` (cookies without Secure), `13`, `14` (DPAPI without entropy), `15`, `16` and `20` (deserialisation, XXE).
|
||||
- **8 grounded surface checks** (`cra-ai-6`, `11`, `12`, `24`, `27`, `28`, `29`, `30`): the absence-based controls (no rate limiting, no security logging, no update-signature check…) that have no syntactic pattern.
|
||||
- **Marked not_code_checkable** (`cra-ai-2`, `3`, `4`, `5`, among the 19): minimal attack surface, secure architecture, least privilege, tamper protection.
|
||||
|
||||
@@ -36,7 +37,7 @@ For the **CRA** framework (40 controls) the split is **21 covered · 0 needs_too
|
||||
|
||||
Each binding in the control map names the **languages** its rules run on (`languages`, empty for language-independent tools such as gitleaks, syft and osv). A test keeps these in step with the rule pack. Each scan run records the source languages it saw outside vendor code (`ScanRun.languages`).
|
||||
|
||||
The CRA status calls a covered control **"no violation found"** only when one of its bindings applies to those languages *and* no tool it relies on failed in that scan (a skipped `sast`, `sast_c_cpp`, `sast_mobile` or `cve_lookup` stage). Otherwise the control is **not assessed**, with the reason: not scanned yet, no rule for the languages found, a tool that did not complete, or languages unknown (a run from before they were recorded). A C-only firmware repo therefore never reads "no violation found" for controls only Python rules check (#368, #387).
|
||||
The CRA status calls a covered control **"no violation found"** only when one of its bindings applies to those languages *and* no tool it relies on failed in that scan (a skipped `sast`, `sast_c_cpp`, `sast_mobile`, `sast_dotnet` or `cve_lookup` stage). Otherwise the control is **not assessed**, with the reason: not scanned yet, no rule for the languages found, a tool that did not complete, or languages unknown (a run from before they were recorded). A C-only firmware repo therefore never reads "no violation found" for controls only Python rules check (#368, #387).
|
||||
|
||||
At scale, the **master-controls** corpus (breakpilot's deduped clusters, exported as OSCAL) currently provides **~2,882 code-checkable controls** (2,143 `network` + 739 `source_code`), matched semantically.
|
||||
|
||||
|
||||
@@ -102,6 +102,36 @@ Not reported: the app-wide "missing protection" hints (no certificate pinning,
|
||||
no root or jailbreak detection, no screenshot protection). They name no place in
|
||||
the code and are heuristics. Dart code (Flutter) has no rules yet.
|
||||
|
||||
## DevSkim -- .NET Without a Build
|
||||
|
||||
[DevSkim](https://github.com/microsoft/DevSkim) (MIT, Microsoft) runs on trees
|
||||
with C# or VB.NET code (#494). Legacy .NET Framework solutions often cannot be
|
||||
built outside the customer's Windows toolchain, which rules out the Roslyn
|
||||
analysers; DevSkim matches its rules on the source text instead. It reads `.cs`,
|
||||
`.vb`, Razor and ASP.NET pages (`.cshtml`, `.vbhtml`, `.razor`, `.aspx`,
|
||||
`.ascx`, `.asmx`, `.asax`, `.master`) and `.config` files, and finds:
|
||||
|
||||
- broken hash classes and ciphers (`MD5CryptoServiceProvider`, `SHA1Managed`,
|
||||
DES, 3DES, RC2, ECB);
|
||||
- certificate validation switched off, outdated or hard-coded TLS versions,
|
||||
plain `http://` URLs;
|
||||
- unsafe deserialisers (`BinaryFormatter`, `NetDataContractSerializer`,
|
||||
`SoapFormatter` …) and XML parsers that resolve external entities;
|
||||
- tokens and private keys in source;
|
||||
- `Web.config`: cookies without `Secure`, tracing switched on.
|
||||
|
||||
Only DevSkim's own rules at severity Critical, Important or Moderate are used;
|
||||
its ManualReview and BestPractice hints are not reported, nor two rules that
|
||||
flooded real C# code with false positives (any method named `Random`, the bare
|
||||
words md5/sha1 in identifiers); our own Semgrep rules cover weak hashes and
|
||||
`System.Random` precisely. `bin/`, `obj/`,
|
||||
`packages/` and vendor directories are skipped. DevSkim's SARIF names no CWE,
|
||||
so Prüfwerk gives each rule one, which ties it to its CRA control. The CLI runs
|
||||
in the agent image on the .NET runtime, offline: nothing about the code leaves
|
||||
the scan. Its findings are **Codeanalyse (SAST)** findings with the tool name
|
||||
`devskim`; a run that fails is listed under *Nicht ausgeführt* as
|
||||
`sast_dotnet`, and the controls it checks are then not assessed.
|
||||
|
||||
## Vendor Code Exclusion
|
||||
|
||||
Firmware projects carry their silicon vendor's SDK (HAL, CMSIS, board support)
|
||||
|
||||
@@ -23,6 +23,7 @@ together on stage in one pass before the next prod promotion.
|
||||
| #492 | Vendored MIT semgrep packs (GitLab, 0xdea, elttam); guard against registry rules |
|
||||
| #495 | Binary depth: PE/ELF hardening, signatures, .NET references, CPE/purl candidates, Intel HEX checks |
|
||||
| #498 (1/4) | VEX status on CVE alerts, OpenVEX and CycloneDX VEX, a valid CycloneDX SBOM |
|
||||
| #494 | DevSkim: .NET SAST without a build (C#, VB.NET, .config) |
|
||||
|
||||
**Customer-visible on the next prod rescan** is marked **[visible]**: these
|
||||
change what a customer sees on their existing targets, without them doing
|
||||
@@ -495,6 +496,28 @@ alerts (e.g. the log4j/gson target of check 19).
|
||||
- **[visible]** SBOM-Qualität card on the SBOM page, the score on cra-ai-23,
|
||||
`sbom-quality.json` in the evidence pack. Expect a low BSI grade until the
|
||||
export carries CycloneDX 1.6 and the TR's fields.
|
||||
### 25. #494 DevSkim for .NET
|
||||
|
||||
- **Do:** upload `fixtures/dotnet/legacy-sample` and `fixtures/dotnet/framework48`
|
||||
as **Archiv** and scan.
|
||||
- **Expect:** Codeanalyse findings with the tool `devskim`: in the legacy
|
||||
sample SSL 3 pinned (DS440020, DS144436), certificate validation off
|
||||
(DS126187), DES (DS106864), `XmlUrlResolver` (DS132783),
|
||||
`BinaryFormatter` in the VB file (DS425070), and in `Web.config`
|
||||
tracing (DS450002) and cookies without Secure (DS450001); each with a CWE
|
||||
and a CRA control (cra-ai-15, 13, 20, 1, 10). In framework48 the
|
||||
`BinaryFormatter` in `OrderService.svc.cs`; nothing from `packages/` or
|
||||
`bin/`. Severities follow DevSkim's (Critical High, Important Medium).
|
||||
**Nicht ausgeführt** has no `sast_dotnet` entry; a Python-only target gets
|
||||
no DevSkim run at all.
|
||||
- **Log:** `DevSkim failed` must not appear. The image's
|
||||
`/opt/pruefwerk/tool-versions.json` lists `devskim` 1.0.100 and
|
||||
`dotnet-runtime` 10.0.12.
|
||||
- **Offline:** the scan runs with the agent's egress as before; DevSkim opens
|
||||
no connection (checked with `--network none`).
|
||||
- **[visible]** on the next prod rescan: C# and VB.NET targets get new
|
||||
Codeanalyse findings from DevSkim, and VB.NET code is now counted as a
|
||||
language (controls DevSkim checks are assessed for it).
|
||||
|
||||
## After the pass
|
||||
|
||||
|
||||
@@ -21,3 +21,23 @@ tool, NuGet packages in `packages.config` and committed under `packages/`.
|
||||
| `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 |
|
||||
|
||||
## `legacy-sample`
|
||||
|
||||
A small .NET Framework 4.8 library in C# and VB.NET with a `Web.config`,
|
||||
planted for DevSkim (#494), which reads it without a build. Also a nightly
|
||||
target (`dotnet-legacy-sample`), as is `framework48` (`dotnet-framework48`).
|
||||
|
||||
| What | Expected (DevSkim rule) |
|
||||
|---|---|
|
||||
| `TelemetryClient.cs`: `SecurityProtocolType.Ssl3` | outdated / hard-coded TLS version (DS440020, DS144436), CWE-757 |
|
||||
| `TelemetryClient.cs`: `ServerCertificateValidationCallback = … => true` | certificate validation off (DS126187), CWE-295 |
|
||||
| `TelemetryClient.cs`: `DESCryptoServiceProvider` | broken cipher (DS106864), CWE-327 |
|
||||
| `TelemetryClient.cs`: `XmlResolver = new XmlUrlResolver()` | XML external entities (DS132783), CWE-611 |
|
||||
| `LegacyLink.vb`: `SHA1.Create()` | nothing from DevSkim (its word match DS126858 is switched off as too noisy) |
|
||||
| `LegacyLink.vb`: `BinaryFormatter.Deserialize` | unsafe deserialisation (DS425070), CWE-502 |
|
||||
| `Web.config`: `<trace enabled="true">`, `requireSSL="false"` | tracing on (DS450002, CWE-489), cookies without Secure (DS450001, CWE-614) |
|
||||
|
||||
In `framework48`, DevSkim finds the `BinaryFormatter` (DS425070) in
|
||||
`OrderService.svc.cs` (the MD5 hash there is our own semgrep rule's);
|
||||
`packages/` and `bin/` are not read.
|
||||
@@ -0,0 +1,15 @@
|
||||
' Fixture for #494: VB.NET part of the legacy gateway. Not real code.
|
||||
Imports System.Security.Cryptography
|
||||
Imports System.Runtime.Serialization.Formatters.Binary
|
||||
|
||||
Public Class LegacyLink
|
||||
Public Function Checksum(data As Byte()) As Byte()
|
||||
Dim sha As SHA1 = SHA1.Create()
|
||||
Return sha.ComputeHash(data)
|
||||
End Function
|
||||
|
||||
Public Function Restore(stream As IO.Stream) As Object
|
||||
Dim formatter As New BinaryFormatter()
|
||||
Return formatter.Deserialize(stream)
|
||||
End Function
|
||||
End Class
|
||||
@@ -0,0 +1,12 @@
|
||||
<?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.Gateway</RootNamespace>
|
||||
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="LegacyLink.vb" />
|
||||
<Compile Include="TelemetryClient.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,47 @@
|
||||
// Fixture for #494: a legacy .NET Framework client with the weaknesses
|
||||
// DevSkim finds without a build. Not real code; never deployed.
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using System.Xml;
|
||||
|
||||
namespace Plant.Gateway
|
||||
{
|
||||
public class TelemetryClient
|
||||
{
|
||||
private static readonly Random Rng = new Random();
|
||||
|
||||
public TelemetryClient()
|
||||
{
|
||||
// Old protocol pinned for an old PLC gateway.
|
||||
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
|
||||
// Every certificate accepted.
|
||||
ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, errors) => true;
|
||||
}
|
||||
|
||||
public string NewSessionToken()
|
||||
{
|
||||
var bytes = new byte[16];
|
||||
Rng.NextBytes(bytes);
|
||||
return Convert.ToBase64String(bytes);
|
||||
}
|
||||
|
||||
public byte[] Encrypt(byte[] data, byte[] key)
|
||||
{
|
||||
using (var des = new DESCryptoServiceProvider())
|
||||
{
|
||||
des.Key = key;
|
||||
return des.CreateEncryptor().TransformFinalBlock(data, 0, data.Length);
|
||||
}
|
||||
}
|
||||
|
||||
public XmlDocument LoadConfig(Stream input)
|
||||
{
|
||||
var doc = new XmlDocument();
|
||||
doc.XmlResolver = new XmlUrlResolver();
|
||||
doc.Load(input);
|
||||
return doc;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<system.web>
|
||||
<compilation debug="false" targetFramework="4.8" />
|
||||
<trace enabled="true" localOnly="false" />
|
||||
<httpCookies requireSSL="false" httpOnlyCookies="true" />
|
||||
</system.web>
|
||||
</configuration>
|
||||
@@ -835,6 +835,58 @@
|
||||
"expect": {
|
||||
"min_sbom_components": 20
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "dotnet-framework48",
|
||||
"name": ".NET Framework 4.8 solution (no build)",
|
||||
"target_type": "backend_service",
|
||||
"description": "fixtures/dotnet/framework48: legacy WPF/WCF solution with packages.config, a committed signing key and an insecure Web.config. DevSkim (#494) must find the BinaryFormatter in OrderService.svc.cs; packages/ and bin/ stay out of it.",
|
||||
"artifacts": [
|
||||
{
|
||||
"kind": "source_archive",
|
||||
"upload": "fixtures/dotnet/framework48"
|
||||
}
|
||||
],
|
||||
"expect": {
|
||||
"sast_rule_ids": [
|
||||
"DS425070"
|
||||
],
|
||||
"cwes": [
|
||||
"CWE-502"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "dotnet-legacy-sample",
|
||||
"name": ".NET legacy gateway, C# and VB.NET (DevSkim)",
|
||||
"target_type": "backend_service",
|
||||
"description": "fixtures/dotnet/legacy-sample: a small vulnerable C#/VB.NET library and Web.config for DevSkim (#494): SSL 3 pinned, certificate validation off, DES, XXE-prone XmlResolver, BinaryFormatter (VB.NET), tracing on and cookies without Secure.",
|
||||
"artifacts": [
|
||||
{
|
||||
"kind": "source_archive",
|
||||
"upload": "fixtures/dotnet/legacy-sample"
|
||||
}
|
||||
],
|
||||
"expect": {
|
||||
"sast_rule_ids": [
|
||||
"DS126187",
|
||||
"DS106864",
|
||||
"DS132783",
|
||||
"DS440020",
|
||||
"DS425070",
|
||||
"DS450001",
|
||||
"DS450002"
|
||||
],
|
||||
"cwes": [
|
||||
"CWE-295",
|
||||
"CWE-327",
|
||||
"CWE-611",
|
||||
"CWE-757",
|
||||
"CWE-502",
|
||||
"CWE-614",
|
||||
"CWE-489"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user