We are going to design a system for auto-remediation of dependency vulnerabilities with the ability to handle exceptions.
Steps:
- Scan dependencies for known vulnerabilities (using a tool like OWASP Dependency Check, Snyk, or similar).
- For each vulnerability, attempt to auto-remediate by updating the dependency to a non-vulnerable version (if available).
- Allow for exceptions: some vulnerabilities might be accepted (e.g., because they are in a test scope, or the fix introduces breaking changes, or the vulnerability is not exploitable in the context).
- The system should be able to:
- Apply automatic updates where possible and safe.
- Record exceptions for vulnerabilities that are not fixed automatically.
- Generate a report of actions taken and exceptions.
We'll design this as a CLI tool that can be integrated into a CI/CD pipeline.
Components:
- Vulnerability Scanner: We assume we have a way to get a list of vulnerabilities (from a scanner output, e.g., JSON).
- Remediation Engine: For each vulnerability, determine if we can update the dependency to a safe version.
- Exception Manager: Allows the user to specify exceptions (e.g., via a configuration file or command line) and records them.
- Report Generator: Outputs what was fixed and what was exceptioned.
Steps in the tool:
- Parse the scanner output (we assume a standard format, e.g., JSON from OWASP Dependency Check).
- For each vulnerability, check if there's a fix (newer version without the vulnerability). We might need to consult a vulnerability database or the package manager's version info.
- If a fix exists and is allowed (not in exception list and passes any other criteria), then update the dependency in the manifest file (e.g., pom.xml, package.json, etc.).
- If no fix exists or the fix is not allowed (due to exception or other reasons), then record as exception.
- After processing all vulnerabilities, generate a report.
We'll need to consider:
- The tool should be language-agnostic? Or at least support multiple package managers? We'll design for a specific ecosystem (e.g., Java/Maven) but with extensibility.
However, note: the problem says "dependency vulnerability", so we are focusing on dependencies (libraries) of an application.
Let's assume we are building for Maven (Java) for simplicity, but the design can be extended.
Implementation:
We'll have:
- A configuration file (e.g., .remediation-exceptions.json) that lists exceptions by:
- dependency (groupId:artifactId)
- vulnerability ID (e.g., CVE)
- reason (text)
- maybe a timestamp and who approved?
But note: we might want to exception by:
- A specific dependency and version (the vulnerable version we are using) and vulnerability.
- Or by dependency and vulnerability (any version? but that doesn't make sense because if we update, the vulnerability might be fixed).
Actually, we want to exception the current vulnerable version? Or the vulnerability in general for that dependency?
Let's think: if we have a dependency X with version 1.0 that has CVE-2020-1234, and we decide to exception it, then if we update to 1.1 (which is safe) we don't need the exception anymore.
So the exception should be tied to the specific vulnerable version? Or to the dependency and vulnerability, and then we check if the current version is vulnerable and if we have an exception for that dependency and vulnerability.
But note: if we update the dependency to a safe version, then the exception is no longer relevant. So we can store exceptions in a way that they are active only when the vulnerable version is present.
Alternatively, we can have the exception be for a dependency and a vulnerability, and then when we update the dependency to a safe version, we can remove the exception? But that might be risky because someone might have added the exception for a reason that still applies (e.g., the fix breaks functionality). So maybe we don't remove exceptions automatically.
However, the tool should be able to re-evaluate: if the dependency is updated to a safe version, then we don't need to apply the exception. But the exception record might still be there for historical reasons.
So in the configuration, we can have:
{
"exceptions": [
{
"dependency": "org.apache.logging.log4j:log4j-core",
"vulnerability": "CVE-2021-44228",
"reason": "We are not using the vulnerable code path.",
"approvedBy": "security-team",
"approvedDate": "2021-12-10"
}
]
}
Then, when we scan, if we find that we are using log4j-core:2.14.0 (vulnerable to CVE-2021-44228) and we have an exception for that dependency and vulnerability, then we skip updating.
But note: what if we are using a version that is not vulnerable? Then we don't care about the exception.
So the logic:
For each vulnerability found in the current dependencies:
Let D = dependency (with version) and V = vulnerability.
Check if there is an exception for D's group:artifact and V.
If yes, then skip and record as exception.
If no, then check if there is a safe version (without V) available.
If there is, then update to the latest safe version (or at least a version that fixes V).
If there isn't, then we cannot fix, so we record as exception? Or maybe we leave it as a vulnerability that needs manual attention.
But note: the tool is for auto-remediation. So we only auto-remediate if we can and there's no exception.
We also might have a threshold: we might only want to update minor versions? Or only patch? We can have configuration for that.
Let's add:
- Update strategy:
* "safe" (only updates that fix vulnerabilities, no other changes) -> we look for the next version that fixes the vulnerability and is within the same major version?
* "latest" (update to the latest version, but must fix the vulnerability). But note: latest might be a major version change.
We can let the user specify:
In configuration:
{
"strategy": "safe", // or "latest"
"exceptions": [...]
}
How do we find the safe version?
We need to query the package manager's repository or a vulnerability database that tells us which versions are affected.
For Maven, we can use the Maven Metadata and the vulnerability data from NVD or similar.
But note: the scanner (like OWASP Dependency Check) already tells us which versions are vulnerable. So we can use that.
Example from OWASP Dependency Check JSON:
{
"vulnerabilities": [
{
"dependency": "log4j-core-2.14.0.jar",
"cve": "CVE-2021-44228",
"vulnerableVersions": ["2.0-beta9", "2.14.1"],
...
}
]
}
Actually, the vulnerableVersions might be a range. We can parse that and then find the next version that is not in the range.
But note: the scanner might not give the full range? It might just say the version is vulnerable.
Alternatively, we can use the Maven repository to get all versions and then check each version against the vulnerability data? That's heavy.
Another idea: use the package manager's update command? But we want to control the update.
For simplicity, we assume that the scanner tells us the fixed version? Actually, some scanners do.
Let's assume we have a function:
get_fixed_versions(dependency, vulnerability) -> list of versions that are not vulnerable.
Then, from the current version, we choose:
If strategy is "safe":
Choose the smallest version that is greater than the current version and in the same major version?
But what if the fix is in the next major version? Then we might not want to update for "safe" strategy? Or maybe we do because the vulnerability is critical.
Actually, the "safe" strategy might be defined as: update to the next version that fixes the vulnerability and does not change the major version (if possible). But if the fix is only in the next major version, then we might update to that? That's a breaking change.
So maybe we have two strategies:
- "conservative": only update within the same major version (if available) to fix the vulnerability.
- "latest": update to the latest version that fixes the vulnerability (even if major version changes).
But note: the user might want to update to a specific version? That might be too complex.
Alternatively, we can let the user specify:
"updateRules": {
"org.apache.logging.log4j:log4j-core": {
"strategy": "latest"
}
}
But for simplicity, we'll have a global strategy.
Steps:
-
Load configuration (exceptions and strategy).
-
Read the scanner output.
-
For each vulnerability in the current dependencies:
a. Check if the current version of the dependency is vulnerable (the scanner already says so).
b. Check if there's an exception for this dependency and vulnerability. If yes, skip.
c. Else, get the list of safe versions (that fix the vulnerability) from the scanner or another source.
d. If there are safe versions:
- Choose the version to update to based on strategy.
- Update the manifest file (e.g., pom.xml) to that version.
- Record the update.
e. If no safe version, then record as exception (or just leave as vulnerability?).
-
Write the updated manifest file.
-
Generate a report.
We'll need to be careful: updating a dependency might introduce other vulnerabilities? We are only fixing one at a time. But the scanner might have multiple vulnerabilities for the same dependency.
We should fix all vulnerabilities for a dependency in one go? Because if we update to a version that fixes one vulnerability but introduces another? That's possible but rare.
Actually, we should update to a version that fixes all known vulnerabilities for that dependency? But that might be too restrictive.
Alternatively, we can update to the version that fixes the current vulnerability and then re-scan? But that would require multiple passes.
Since this is an auto-remediation tool, we might run it in a loop until no more fixes? But that could be dangerous.
Let's stick to: for each vulnerability, update to a version that fixes that specific vulnerability. Then after all updates, we might have fixed multiple for the same dependency, but we might have updated multiple times (inefficient). We can group by dependency and then find a version that fixes all the vulnerabilities for that dependency? That's more complex.
For now, we'll do:
Group vulnerabilities by dependency.
For each dependency, we have a set of vulnerabilities.
We want to find a version that is not vulnerable to any of these.
So we can:
For dependency D, let V_set be the set of vulnerabilities.
We want to find the smallest version (according to strategy) that is not vulnerable to any V in V_set.
How to check if a version is vulnerable to a given vulnerability? We need the vulnerable ranges for each vulnerability.
We can get from the scanner output the vulnerable version ranges for each CVE.
Then for a candidate version, we check if it falls within any of the vulnerable ranges for the dependency.
If not, then it's safe.
So we change:
Instead of per vulnerability, we per dependency.
Steps for a dependency:
Let current_version = the version we are using.
Let vulnerabilities = list of vulnerabilities for this dependency (from scanner).
Let excluded_versions = set of versions that are vulnerable to at least one of these vulnerabilities.
Then we want to find a version that is not in excluded_versions and is greater than current_version (if we are updating) and matches the strategy.
We can get all versions of the dependency from the package manager? Or from the scanner? The scanner might not list all versions.
Alternatively, we can use the package manager to get the list of available versions? That might be heavy and slow.
Another idea: use the vulnerability data to get the fixed version? Each vulnerability might have a fixed version? But note: a vulnerability might be fixed in multiple versions.
Actually, the scanner might give us:
"vulnerableVersions": [ "2.0-beta9", "2.14.1" ] // meaning versions >=2.0-beta9 and <=2.14.1 are vulnerable? Not exactly.
The format might be a range string. We can parse that.
But we don't have a standard way.
Given the complexity, let's simplify:
We assume that for each vulnerability, we can get a list of versions that are not vulnerable? Or at least the minimum fixed version.
Actually, many vulnerability databases (like NVD) provide the fixed version.
So we can:
For each vulnerability, get the fixed version (or versions). Then the safe versions are those that are >= the fixed version? But note: sometimes a later version might reintroduce the vulnerability? Unlikely.
So for a dependency, we can take the maximum of the fixed versions for all vulnerabilities? That would be the version that fixes all.
But wait: if vulnerability A is fixed in 1.2 and vulnerability B is fixed in 1.3, then 1.3 fixes both.
So we can:
fixed_versions = []
for each vulnerability in vulnerabilities:
fixed_versions.extend(get_fixed_versions_for_vulnerability(dependency, vulnerability))
Then we want the smallest version that is >= max(fixed_versions) and within the same major version (if strategy is conservative) or any version (if latest).
But note: what if the fixed versions are not in order? We need to compare versions.
We can use semantic versioning.
So we need a version comparison library.
Alternatively, we can let the package manager decide? We can run mvn versions:use-dep-version or similar? But we want to control.
Given the time, we'll assume:
We have a function that, given a dependency and a list of vulnerabilities, returns the recommended version to update to (according to strategy) or null if none.
How to implement that function?
We can:
Step 1: Get all available versions of the dependency (from the package manager's repository). But note: we might not have access to the repository? We can use the local repository? Or we can use the scanner's data?
Step 2: For each available version, check if it is vulnerable to any of the vulnerabilities.
Step 3: Filter out the vulnerable ones.
Step 4: From the safe versions, choose:
if strategy == "conservative":
choose the safe version that is >= current_version and has the same major version, and is the smallest such version.
if strategy == "latest":
choose the latest safe version (by semantic versioning) that is >= current_version.
But getting all available versions might be heavy. We can try to get the list from the package manager's metadata.
For Maven, we can use the Maven Metadata XML from the repository.
But note: we are updating the pom.xml, so we are using Maven. We can use Maven's version range resolution? That might be complex.
Given the complexity and time, we will make a simplifying assumption:
We will rely on the scanner to tell us the fixed version for each vulnerability. Then we take the maximum fixed version (by semantic version) that is within the same major version (for conservative) or any (for latest).
But note: the fixed version might not be the only safe version. There might be multiple fixed versions.
Actually, the fixed version is the first version that fixes the vulnerability. So any version after that (until the next vulnerability) is safe.
So if we have two vulnerabilities:
CVE1 fixed in 1.2
CVE2 fixed in 1.3
Then 1.3 is safe for both.
But what if there's a CVE3 that affects versions 1.3 and above? Then 1.3 is not safe.
So we need to check the safe version against all vulnerabilities.
Therefore, we cannot just take the maximum fixed version and assume it's safe for all.
We must check the candidate version against all vulnerability ranges.
So we need:
For each vulnerability, we have a range of vulnerable versions (or a set of versions). We can represent as:
vulnerable_versions[vuln] = set of versions (or a range)
Then for a candidate version, we check if it is in any of the vulnerable_versions sets.
How to get the vulnerable versions for a vulnerability? The scanner might give a string like:
"vulnerableVersions": "(,2.14.1]"
meaning versions <=2.14.1 are vulnerable.
Or:
"vulnerableVersions": "[2.0-beta9,2.14.1]"
meaning between 2.0-beta9 and 2.14.1 (inclusive) are vulnerable.
We can parse these ranges.
But note: the scanner might not give the full range? It might just give the version we are using and say it's vulnerable? We need the full range to know if a candidate version is safe.
Alternatively, we can use the CVSS score and the fixed version? Not enough.
Given the complexity, and since this is a design, we'll assume we have a way to get the vulnerable version ranges for each vulnerability for a given dependency.
We can use the OWASP Dependency Check's data? It uses the NVD data.
But note: the NVD data might not have the fixed version for every vulnerability.
So we might have to rely on the package manager's metadata? Not always available.
We'll design the system with:
A "VulnerabilityDataSource" interface that can tell for a given dependency and vulnerability:
- Is a given version vulnerable?
- What are the vulnerable version ranges?
And we can have a implementation that uses the scanner's output (which we already have) and maybe other sources.
Since we are building on top of a scanner, we assume the scanner output includes the vulnerable ranges.
Let's assume the scanner output for a vulnerability includes:
"vulnerableVersions": ">=2.0-beta9,<=2.14.1"
We can parse that into a range.
Then for a candidate version, we can check if it falls within any of the vulnerable ranges for the dependency's vulnerabilities.
Steps for a dependency:
Let current_version = the version in the manifest.
Let vulnerabilities = list of vulnerability objects for this dependency (each with a vulnerableVersions range).
We want to find a safe version:
safe_versions = []
for each available version (we need to get the list of available versions from somewhere) of the dependency:
if version is not in any of the vulnerable ranges (for the vulnerabilities we have) and version >= current_version (we are updating, so we don't want to downgrade) then it's safe.
Then choose from safe_versions according to strategy.
But getting all available versions: we can get from the package manager's repository. For Maven, we can use:
https://repo1.maven.org/maven2/groupId/artifactId/maven-metadata.xml
We can parse that to get the list of versions.
But note: we might have multiple repositories? We can use the ones defined in the pom.xml? That's complex.
Given the time, we'll assume we have a way to get the list of all versions for a dependency (maybe from a cache or from the local repository?).
Alternatively, we can start from the current version and then try the next version, then the next, until we find a safe one? But what if the next version is vulnerable? Then we have to keep going.
We can do:
candidate_version = next version after current_version (in the list of all versions, sorted by semver)
while candidate_version exists:
if candidate_version is not vulnerable to any of the vulnerabilities (by checking the vulnerable ranges) then we found it.
else candidate_version = next version.
If we run out of versions, then no safe version.
But note: what if the next version is the same major version but then the next is a major version? We might skip the major version if we are in conservative mode.
So we need to:
In conservative mode, we only consider versions with the same major version as current_version.
In latest mode, we consider any version.
We can:
Get the list of all versions for the dependency (from the repository metadata).
Filter the list:
if conservative: keep only versions with the same major version as current_version.
if latest: keep all.
Then sort by version (ascending).
Then iterate from the first version that is greater than current_version until we find a safe one.
But note: the list of versions from the repository might include very old versions. We are only interested in versions >= current_version.
So:
available_versions = get_all_versions(dependency)
candidate_versions = [v for v in available_versions if v > current_version and (conservative ? same_major(v, current_version) : true)]
Then sort candidate_versions by semver (ascending) and check each until we find one that is safe.
How to check if a version is safe?
For each vulnerability in vulnerabilities:
if version is in the vulnerable range for that vulnerability -> not safe.
If none of the vulnerabilities have the version in their vulnerable range, then safe.
We need a function to check if a version is in a range. The range might be expressed as a string. We can use a library like semver for Java, but we are designing in Python? Let's assume we are implementing in Python and use packaging.version and packaging.specifiers.
But note: the vulnerableVersions string might not be a valid semver range? It might be a numeric range? We have to parse.
Actually, the OWASP Dependency Check uses the following format for vulnerableVersions:
A comma separated list of version ranges. Each range is either:
[lower,upper] inclusive
(lower,upper) exclusive
[lower,upper) etc.
And the bounds can be numbers or '*' for no bound.
We can parse that into a list of SpecifierSet from packaging? Not exactly.
Alternatively, we can use the Version and Specifier from packaging but note that Specifier is for single version specifiers (like >=1.0,<2.0). We can convert the range string to a specifier string.
Example:
"[2.0-beta9,2.14.1]" -> ">=2.0-beta9,<=2.14.1"
So we can replace the brackets with the appropriate operator.
But note: the brackets might be mixed.
We can write a parser.
Given the complexity, we might assume that the scanner provides a list of vulnerable versions (explicit list) or a range that we can convert to a SpecifierSet.
Let's assume we have a helper function:
def is_version_in_range(version, range_string):
# convert range_string to a SpecifierSet and check
But note: the range_string might be a list of ranges? The OWASP format can have multiple ranges? Actually, it's a single string that might contain multiple ranges separated by comma? Yes.
Example: "(,2.14.1]" meaning <=2.14.1.
We can split by comma and then combine with "and"? Actually, the format is:
[lower,upper] means lower <= version <= upper.
(lower,upper) means lower < version < upper.
And multiple ranges are OR? Actually, the string is a single range? Wait, the documentation says:
vulnerableVersions: A string containing comma separated list of version ranges (using the same format as above) that are considered vulnerable.
So it's a list of ranges, and if the version is in any of the ranges, it's vulnerable.
So we can split by comma and then each part is a range? But note: a range might have a comma inside? Actually, the range is defined by two bounds separated by comma? And the bounds are enclosed in brackets or parentheses.
Example: "[1.0,2.0),(2.5,3.0]" -> two ranges.
So we need to parse the string into a list of ranges.
This is getting complex.
Given the time, we'll assume we have a function from the scanner that tells us for a given dependency and version, whether it is vulnerable to a given CVE? But we have the list of CVEs for the dependency.
Alternatively, we can use the scanner's data to build a mapping:
vulnerable_versions[dep][cve] = set of versions (or a range)
Then for a candidate version, we check for each cve in the dependency's vulnerabilities:
if candidate_version in vulnerable_versions[dep][cve] -> vulnerable.
But building that mapping requires parsing the vulnerableVersions string for each vulnerability.
We'll leave the implementation of the version range parsing as a separate module.
For the purpose of this design, we'll assume we have:
def is_version_vulnerable(dependency, version, vulnerability):
# returns True if the version is vulnerable to the given vulnerability.
Then:
def find_safe_version(dependency, current_version, vulnerabilities, strategy):
# Get all available versions for the dependency (from repository)
available_versions = get_available_versions(dependency)
# Filter by strategy and > current_version
candidate_versions = filter_versions(available_versions, current_version, strategy)
for version in sorted(candidate_versions, key=parse_version):
safe = True
for vul in vulnerabilities:
if is_version_vulnerable(dependency, version, vul):
safe = False
break
if safe:
return version
return None
Now, the steps:
For each dependency that has vulnerabilities:
if there's an exception for any of the vulnerabilities of this dependency? Actually, the exception is per vulnerability.
But we are grouping by dependency. So:
Let dep_vulns = list of vulnerabilities for this dependency.
Check if any of dep_vulns has an exception? If yes, then we skip the entire dependency? Or we skip only the ones with exception?
Actually, we might have an exception for one vulnerability but not for another. So we should only skip updating if the version we are updating to would still be vulnerable to the exceptioned vulnerability? But wait, the exception is for the current vulnerable version? Or for the vulnerability in general?
Our exception is for the dependency and vulnerability. So if we update to a version that is not vulnerable to that vulnerability, then the exception is no longer relevant.
But the exception might be because we don't want to update at all? Or because we accept the risk for that vulnerability?
Let's clarify: the exception means we accept the current state (with the vulnerable version) for that vulnerability. So if we update to a version that fixes that vulnerability, then we no longer have that vulnerability, so the exception is not needed.
However, the exception might be for a vulnerability that we cannot fix (no safe version). Then we keep the exception.
So:
For each vulnerability in dep_vulns:
if there's an exception for (dependency, vulnerability) and the current version is vulnerable to that vulnerability, then we mark that vulnerability as exceptioned.
Then, when looking for a safe version, we only consider the vulnerabilities that are not exceptioned? Because the exceptioned ones we are willing to live with.
But wait: what if we update to a version that fixes the exceptioned vulnerability? Then we don't need to exception it anymore. But the exception record is still there. That's okay.
Alternatively, we can remove the exception if the dependency is updated to a safe version? But that might be dangerous because the reason for the exception might still hold (e.g., the fix breaks functionality). So we don't remove exceptions automatically.
So:
We have a set of vulnerabilities that we are trying to fix: those that are not exceptioned.
Then we look for a version that is not vulnerable to any of the non-exceptioned vulnerabilities.
But note: the version we choose might be vulnerable to an exceptioned vulnerability? That's okay because we have an exception for it.
However, the current version might be vulnerable to both exceptioned and non-exceptioned. We want to update to a version that fixes the non-exceptioned ones, and we don't care about the exceptioned ones.
So the condition for a candidate version is:
For each vulnerability in dep_vulns that is not exceptioned, the candidate version must not be vulnerable.
For vulnerabilities that are exceptioned, we don't care.
Then, if we find such a candidate version, we update.
If we don't find, then we cannot fix the non-exceptioned vulnerabilities, so we leave them as is (and they will be reported as vulnerabilities).
But note: the exceptioned vulnerabilities are already accepted, so we don't report them as vulnerabilities that need fixing? We do report them as exceptions.
So:
For a dependency:
non_exceptioned_vulns = [v for v in dep_vulns if not exception_exists(dependency, v)]
Then we look for a safe version for these non_exceptioned_vulns.
If found, update.
If not found, then we cannot fix the non_exceptioned ones, so we leave the dependency as is (and the non_exceptioned ones will remain as vulnerabilities in the next scan).
But what about the exceptioned ones? They are accepted, so we don't try to fix them.
Therefore, the steps per dependency:
Let current_version = version in manifest.
Let dep_vulns = all vulnerabilities for this dependency.
Let non_exceptioned_vulns = [v for v in dep_vulns if not exception_exists(dependency, v)]
If non_exceptioned_vulns is empty, then we don't need to update (all vulnerabilities are exceptioned). But note: what if we are exceptioning a vulnerability that is not present in the current version? That shouldn't happen because the scanner only reports vulnerabilities that are present.
So if non_exceptioned_vulns is empty, we skip.
Else:
safe_version = find_safe_version(dependency, current_version, non_exceptioned_vulns, strategy)
If safe_version is found:
Update the manifest to safe_version.
Record: updated dependency from current_version to safe_version, and which vulnerabilities were fixed (the non_exceptioned ones that are not vulnerable in safe_version).
Else:
Cannot fix non-exceptioned vulnerabilities. We leave the dependency as is.
Record: could not fix non-exceptioned vulnerabilities for dependency.
But note: when we update, we might fix some of the non_exceptioned_vulns, but what if the new version introduces a new vulnerability? We are only checking against the current set of vulnerabilities. We are not scanning the new version for new vulnerabilities.
That's a problem. We should re-scan after update? But that would require running the scanner again, which is heavy.
Alternatively, we can check the new version against the same set of vulnerabilities? That doesn't catch new ones.
So we have two options:
1. After updating, re-scan the project and then repeat the process? That might be too heavy for auto-remediation in CI.
2. Accept that we might introduce new vulnerabilities? That's bad.
We can do:
After updating a dependency, we can check the new version against the vulnerability database for the same set of vulnerabilities? But that doesn't catch new ones.
We can also check for known vulnerabilities in the new version? We would need to query the vulnerability database for the new version.
But note: the scanner we are using already does that. So we are relying on the scanner's data.
Actually, the scanner's data for a dependency includes all known vulnerabilities for that dependency, regardless of the version? Yes, the scanner reports vulnerabilities for the version we are using.
But if we update to a new version, the scanner would report new vulnerabilities for that version? We don't have that data until we scan again.
So we cannot guarantee that the new version is free of all vulnerabilities, only that it fixes the ones we are aware of.
Given the nature of auto-remediation, we are only fixing the known vulnerabilities. We accept that new ones might appear.
So we proceed with the above.
Now, the tool flow:
Inputs:
- Scanner output (JSON)
- Configuration file (exceptions and strategy)
- Manifest file (pom.xml)
Steps:
1. Parse the scanner output and build a structure:
vulnerabilities_by_dependency = {
"group:artifact": [
{
"cve": "CVE-2021-44228",
"vulnerableVersions": ">=2.0-beta9,<=2.14.1",
... other fields
},
...
]
}
2. Parse the manifest file (pom.xml) to get the current version for each dependency.
3. Load the exceptions from configuration.
4. For each dependency in the manifest that has vulnerabilities:
current_version = get from manifest
dep_vulns = vulnerabilities_by_dependency.get(dependency, [])
non_exceptioned_vulns = [v for v in dep_vulns if not is_exceptioned(dependency, v)]
if non_exceptioned_vulns:
safe_version = find_safe_version(dependency, current_version, non_exceptioned_vulns, strategy)
if safe_version:
update the manifest to set the version to safe_version.
record update.
else:
record that we couldn't fix.
5. Write the updated manifest.
6. Generate a report:
- Updated dependencies (with old and new version, and which vulnerabilities were fixed)
- Exceptions (which vulnerabilities were exceptioned and for which dependencies)
- Vulnerabilities that could not be fixed (non-exceptioned and no safe version)
We also need to handle:
- What if the dependency is not in the vulnerabilities_by_dependency? Then we skip.
- What if the dependency is in the vulnerabilities_by_dependency but we don't have version information? Then we skip? Or we try to get the version from the manifest? We already have.
Now, the exception configuration:
We can have a JSON file:
{
"strategy": "conservative",
"exceptions": [
{
"dependency": "org.apache.logging.log4j:log4j-core",
"vulnerability": "CVE-2021-44228",
"reason": "We are not using the vulnerable code path.",
"approvedBy": "security-team",
"approvedDate": "2021-12-10"
}
]
}
We can also have an exception by dependency only? But then we would exception all vulnerabilities for that dependency? That might be too broad.
We'll stick to per dependency and vulnerability.
Implementation details:
We need to parse the pom.xml. We can use `xml.etree.ElementTree` for Maven.
We need to handle:
- direct dependencies in <dependencies>
- dependencyManagement? We are only updating the version in the dependency declaration? But if the version is managed in dependencyManagement, then we should update there? Actually, the version in the dependency might be omitted if it's in dependencyManagement.
This is getting complex.
Let's assume we are only updating dependencies that have a version specified in the <dependency> tag.
If the version is managed, then we don't update? Or we update the dependencyManagement? That's a separate issue.
For simplicity, we'll only update dependencies that have a version element in the dependency.
We can also update the version in dependencyManagement? But then we have to find the right dependencyManagement entry.
We'll leave that for future work.
So we'll only update dependencies that have a element.
Steps for updating the pom.xml:
Find the dependency by groupId and artifactId.
Update the version.
We'll assume the pom.xml is well-formed.
Now, let's write the code structure:
class RemediationTool:
def __init__(self, scanner_output_path, config_path, pom_path):
self.scanner_output = self.load_scanner_output(scanner_output_path)
self.config = self.load_config(config_path)
self.pom = self.parse_pom(pom_path)
def load_scanner_output(self, path):
# load JSON
pass
def load_config(self, path):
# load JSON
pass
def parse_pom(self, path):
# parse XML and return a tree? and also a mapping of dependencies?
pass
def get_dependency_version(self, group_id, artifact_id):
# from the pom, find the dependency and return the version string
pass
def set_dependency_version(self, group_id, artifact_id, version):
# update the pom tree
pass
def write_pom(self, path):
# write the updated pom tree to file
pass
def is_exceptioned(self, dependency, vulnerability):
# dependency: "group:artifact", vulnerability: cve string
for exc in self.config['exceptions']:
if exc['dependency'] == dependency and exc['vulnerability'] == vulnerability:
return True
return False
def get_available_versions(self, dependency):
# get from Maven Central? or from the repositories in the pom?
# For now, we can use Maven Central.
# We can use:
# https://repo1.maven.org/maven2/group_path/artifact_id/maven-metadata.xml
# But we need to convert group_id to path: replace '.' with '/'
# And artifact_id as is.
pass
def is_version_vulnerable(self, dependency, version, vulnerability):
# We have the vulnerability object from the scanner output.
# The vulnerability object has a 'vulnerableVersions' string.
# We need to check if the given version is in that range.
# We can use a helper to parse the range and check.
pass
def find_safe_version(self, dependency, current_version, vulnerabilities, strategy):
# Get all available versions for the dependency.
available_versions = self.get_available_versions(dependency)
# Filter versions that are > current_version and (if conservative) same major version.
candidate_versions = []
for v in available_versions:
if v <= current_version:
continue
if strategy == 'conservative':
if self.get_major_version(v) != self.get_major_version(current_version):
continue
candidate_versions.append(v)
# Sort candidate_versions by semver.
candidate_versions.sort(key=self.parse_version)
for v in candidate_versions:
safe = True
for vul in vulnerabilities:
if self.is_version_vulnerable(dependency, v, vul):
safe = False
break
if safe:
return v
return None
def run(self):
# Build vulnerabilities_by_dependency from scanner output.
# For each dependency in the pom that has vulnerabilities:
# ... as above.
# Then write the pom and generate report.
We are missing:
- How to build the vulnerabilities_by_dependency from the scanner output?
The scanner output might be a list of vulnerabilities, each with a dependency field.
Example:
{
"vulnerabilities": [
{
"dependency": "log4j-core-2.14.0.jar",
"cve": "CVE-2021-44228",
"vulnerableVersions": ">=2.0-beta9,<=2.14.1",
...
}
]
}
But note: the dependency field might be the filename. We need to extract groupId:artifactId? Or we have to map from the filename? Not reliable.
Actually, the scanner might provide the groupId and artifactId? In OWASP Dependency Check, the dependency node has:
"fileName": "log4j-core-2.14.0.jar",
"group": "org.apache.logging.log4j",
"artifact": "log4j-core"
So we can build:
dependency_key = group + ":" + artifact
Then:
vulnerabilities_by_dependency[dependency_key].append(vulnerability)
But note: the same dependency might have multiple vulnerabilities.
So we do:
for vul in scanner_output['vulnerabilities']:
group = vul['group']
artifact = vul['artifact']
key = f"{group}:{artifact}"
vulnerabilities_by_dependency.setdefault(key, []).append(vul)
Then, for each dependency in the pom, we get the key in the same way.
But note: the pom might have a dependency with the same group and artifact but different version? Then we are only looking at the current version.
We are only concerned with the current version.
So we get the current version for the dependency from the pom.
Then, for that dependency key, we get the list of vulnerabilities.
But note: the scanner might have reported vulnerabilities for a dependency that we are not using? Or for a different version? The scanner should only report for the version we have.
Actually, the scanner reports vulnerabilities for the dependencies found in the project, so it should be for the version we have.
But wait: the scanner might report a vulnerability for a dependency that we have, but the vulnerable version range might include versions we are not using? That's okay because we are using the current version and we are checking if the current version is in the vulnerable range? Actually, the scanner already says we are vulnerable, so the current version must be in the vulnerable range.
So we can trust the scanner that the current version is vulnerable to these CVEs.
Therefore, we don't need to check the current version again? Actually, we do because we are going to check the candidate version against the vulnerable ranges.
But note: the scanner's vulnerable range might be for the dependency in general, not just for the current version? Yes, it's for the dependency.
So we can use the same vulnerable range for all versions.
Now, the function is_version_vulnerable:
We have the vulnerability object with 'vulnerableVersions' string.
We parse that string into a list of range objects? Or we can use a function that, given a version string and a range string, returns True if the version is in the range.
We can use the `packaging` library in Python? But note: the range string might not be a valid specifier? We have to convert.
Let's assume the vulnerableVersions string is in the format of Maven version ranges? We can use `maven` version range comparison? That's complex.
Alternatively, we can use the `semver` library and convert the range string to a semver range? But Maven versioning is not exactly semver.
Given the time, we'll assume we have a helper that can compare Maven versions and check ranges.
We can use `packaging.version` for simple versions (with numbers and dots) but for beta versions? It might not work.
We'll leave the implementation of version comparison and range checking as a separate module.
Given the complexity of version comparison and the fact that we are designing, we'll assume we have:
def version_in_range(version, range_string):
# returns True if version is in the range defined by range_string.
pass
Then:
def is_version_vulnerable(self, dependency, version, vulnerability):
range_str = vulnerability['vulnerableVersions']
return version_in_range(version, range_str)
But note: the vulnerability might have multiple ranges? Then we split the string by comma and OR the ranges.
So:
ranges = split_ranges(range_str) # split by comma, but be careful with nested commas? Actually, the format is: [range1],[range2]...
for r in ranges:
if version_in_range(version, r):
return True
return False
Now, the get_available_versions:
We need to get the list of all versions for a dependency from the Maven repository.
We can use the Maven Metadata XML.
Example: for group `org.apache.logging.log4j` and artifact `log4j-core`, the URL is:
https://repo1.maven.org/maven2/org/apache/logging/log4j/log4j-core/maven-metadata.xml
The XML has:
<versioning>
<versions>
<version>2.0-beta9</version>
<version>2.0</version>
...
</versions>
</versioning>
We can parse that and get all versions.
But note: the versions in the metadata might not be sorted? They are usually sorted.
We can sort them with our version comparison.
We'll implement:
def get_available_versions(self, dependency):
group, artifact = dependency.split(':')
group_path = group.replace('.', '/')
url = f"https://repo1.maven.org/maven2/{group_path}/{artifact}/maven-metadata.xml"
# fetch and parse XML, extract <version> elements.
# return list of version strings.
But note: we might have multiple repositories? We are only using Maven Central. We can extend later.
Now, the version comparison:
We need to compare Maven versions. They are not exactly semver.
We can use `pkg_resources` from setuptools? Or `packaging.version`? But for Maven, there are special rules (like 1.0 < 1.0.1? and 1.0-alpha < 1.0?).
We can use the `maven` library? But we don't want to add dependencies.
Given the time, we'll use a simple comparison: split by non-digit and digit? But that's complex.
Alternatively, we can use the `lxml` to compare? No.
We'll use `packaging.version` and hope that Maven versions are compatible? They are not always.
But for the purpose of this design, we'll assume the versions are semver.
If they are not, then our ordering might be wrong.
We'll use:
from packaging import version
def parse_version(v):
return version.Version(v)
Then we can compare.
But note: packaging.version can handle some non-semver? It tries.
Now, the get_major_version:
We can get the major version by splitting by '.' and taking the first part? But for versions like "2.0-beta", the major is 2.
We can use:
major = int(version_obj.major)
where version_obj is a `Version` object.
Now, the run method:
Steps:
1. Build vulnerabilities_by_dependency from scanner output.
2. For each dependency in the pom (we need to traverse the pom tree):
group_id = dep.find('groupId').text
artifact_id = dep.find('artifactId').text
version_elem = dep.find('version')
if version_elem is None:
# version might be in dependencyManagement? We skip for now.
continue
current_version = version_elem.text
key = f"{group_id}:{artifact_id}"
if key not in vulnerabilities_by_dependency:
continue
dep_vulns = vulnerabilities_by_dependency[key]
non_exceptioned_vulns = [v for v in dep_vulns if not self.is_exceptioned(key, v['cve'])]
if not non_exceptioned_vulns:
# All vulnerabilities are exceptioned, skip.
continue
safe_version = self.find_safe_version(key, current_version, non_exceptioned_vulns, self.config['strategy'])
if safe_version:
# Update the version in the pom.
version_elem.text = safe_version
record update.
else:
record that we couldn't fix.
3. Write the updated pom.
4. Generate report.
We also need to record:
- For each update: which vulnerabilities were fixed? Actually, we fixed all non-exceptioned ones because the safe_version is not vulnerable to any of them.
But note: the safe_version might be vulnerable to some of the non_exceptioned_vulns? We checked that it isn't.
So we can say: fixed all non-exceptioned vulnerabilities.
- For each dependency that we couldn't fix: list the non-exceptioned vulnerabilities.
- For exceptions: list the exceptioned vulnerabilities.
Now, the report can be a JSON or a text.
We'll generate a JSON report:
{
"updated_dependencies": [
{
"dependency": "org.apache.logging.log4j:log4j-core",
"old_version": "2.14.0",
"new_version": "2.17.0",
"fixed_vulnerabilities": ["CVE-2021-44228", ...]
}
],
"exceptions": [
{
"dependency": "org.apache.logging.log4j:log4j-core",
"vulnerability": "CVE-2021-44228",
"reason": "..."
}
],
"unfixed_vulnerabilities": [
{
"dependency": "org.apache.logging.log4j:log4j-core",
"vulnerabilities": ["CVE-2021-44228"],
"reason": "No safe version found"
}
]
}
But note: the unfixed_vulnerabilities are the non-exceptioned ones that we couldn't fix.
Now, edge cases:
- What if the dependency is not in the Maven Central? Then get_available_versions might fail. We can skip or use other repositories? We'll skip and log.
- What if the version comparison fails? We'll skip that dependency and log.
- What if the pom has multiple dependencies with the same group and artifact? That shouldn't happen, but if it does, we update all? Actually, we should update only the first? But it's invalid to have duplicate dependencies. We'll update all occurrences.
We'll update all dependencies with the same group and artifact.
Implementation:
When parsing the pom, we might have multiple <dependency> with the same groupId and artifactId? That's invalid but possible.
We can:
dependencies = pom.findall('.//dependency')
for dep in dependencies:
group_id = ...
artifact_id = ...
if key == target_dependency_key:
update the version in this dep.
But note: we are iterating by dependency keys from the vulnerabilities. So we might update multiple times if the same dependency appears multiple times? We are updating each occurrence.
That's okay.
Now, let's code the structure.
We are not going to write the full code, but the design.
We have to consider:
- The tool should be idempotent? Running it twice should not change anything after the first run if there are no new vulnerabilities.
But note: after updating, the vulnerabilities for that dependency might change (because we fixed some). So if we run again, we might try to fix the remaining ones? But we already fixed the non-exceptioned ones. The remaining ones are exceptioned? Or we couldn't fix them.
So running again should not change anything.
However, if we have new vulnerabilities for the updated dependency? Then we would try to fix them? That's good.
But note: the scanner output we are using is from a scan of the old pom. So we should re-scan after updating? But we are not doing that.
So the tool is a one-time fix based on a given scanner output.
We can run it in a loop: update, then re-scan, then update again? But that might be dangerous because we might update multiple times in one run.
We'll do one pass.
Finally, we need to handle:
- What if the dependency is not found in the pom? Then we skip? But the scanner found it, so it must be in the pom? Not necessarily: the scanner might find it in the transitive dependencies? Then we cannot update because it's not in the pom.
We should only update direct dependencies? Or also transitive? We can only update direct dependencies because they are in the pom.
So if the dependency is not in the pom (as a direct dependency), we skip and report.
So in the pom parsing, we only look at direct dependencies? Actually, the pom might have for direct dependencies. Transitive are not listed.
So we are safe.
Now, let's summarize the design:
We have a tool that:
1. Takes a scanner output (JSON), a config (JSON), and a pom.xml.
2. For each direct dependency in the pom that has vulnerabilities (according to the scanner):
a. Check if any of the vulnerabilities are exceptioned. If all are exceptioned, skip.
b. Otherwise, find a safe version that fixes all non-exceptioned vulnerabilities (according to the strategy).
c. If found, update the version in the pom (for all occurrences of that dependency).
d. If not found, leave as is.
3. Write the updated pom.
4. Generate a report.
This design assumes:
- The scanner output provides groupId, artifactId, and vulnerable version ranges for each vulnerability.
- We can get the list of all available versions for a dependency from Maven Central (or a configured repository).
- We can compare versions using semver (or Maven versioning).
Limitations:
- Only works for Maven.
- Only updates direct dependencies.
- Only uses Maven Central for version list.
- Does not handle dependencyManagement.
- Does not handle multiple repositories.
- Does not re-scan after update to check for new vulnerabilities.
But it's a starting point.
Let's write the code structure in Python.
We'll create a class:
class DependencyRemediation:
def __init__(self, scanner_output, config, pom_path):
self.scanner_output = scanner_output # dict from JSON
self.config = config # dict from JSON
self.pom_path = pom_path
self.tree = ET.parse(pom_path)
self.root = self.tree.getroot()
# We'll need to handle namespaces? Maven pom has namespaces.
# We'll assume no namespace for simplicity.
def get_vulnerabilities_by_dependency(self):
vulns_by_dep = {}
for vul in self.scanner_output.get('vulnerabilities', []):
group = vul.get('group')
artifact = vul.get('artifact')
if not group or not artifact:
continue
key = f"{group}:{artifact}"
vulns_by_dep.setdefault(key, []).append(vul)
return vulns_by_dep
def get_dependencies(self):
# return list of (group, artifact, version_elem) for each direct dependency with a version.
deps = []
# In Maven pom, dependencies are under <dependencies>.
# We assume no namespace.
for dep in self.root.findall('.//dependency'):
group_elem = dep.find('groupId')
artifact_elem = dep.find('artifactId')
version_elem = dep.find('version')
if group_elem is None or artifact_elem is None or version_elem is None:
continue
group = group_elem.text.strip()
artifact = artifact_elem.text.strip()
version = version_elem.text.strip()
deps.append((group, artifact, version_elem))
return deps
def is_exceptioned(self, dependency_key, cve):
for exc in self.config.get('exceptions', []):
if exc.get('dependency') == dependency_key and exc.get('vulnerability') == cve:
return True
return False
def get_available_versions(self, dependency_key):
group, artifact = dependency_key.split(':')
group_path = group.replace('.', '/')
url = f"https://repo1.maven.org/maven2/{group_path}/{artifact}/maven-metadata.xml"
try:
response = requests.get(url)
response.raise_for_status()
root = ET.fromstring(response.content)
versions = []
for version_elem in root.findall('.//version'):
versions.append(version_elem.text.strip())
return versions
except Exception as e:
print(f"Error fetching versions for {dependency_key}: {e}")
return []
def version_in_range(self, version, range_str):
# We'll implement a simple version range checker for Maven-like ranges.
# This is a placeholder.
# We assume range_str is like ">=2.0-beta9,<=2.14.1" or "[2.0-beta9,2.14.1]"
# We'll convert to a list of (operator, version) pairs.
# But note: the range_str might have multiple ranges separated by comma (OR) and each range might be [a,b] or (a,b) etc.
# We'll parse the range_str into a list of (lower_bound, upper_bound) with inclusive/exclusive.
# Then check if version is in any of the intervals.
# This is complex. We'll use a library if available, but for now, we'll assume we have a helper.
# We'll use the `maven` library? Not standard.
# We'll leave as TODO.
pass
def is_version_vulnerable(self, dependency_key, version, vulnerability):
range_str = vulnerability.get('vulnerableVersions')
if not range_str:
return False
return self.version_in_range(version, range_str)
def find_safe_version(self, dependency_key, current_version, vulnerabilities, strategy):
available_versions = self.get_available_versions(dependency_key)
if not available_versions:
return None
# Parse current_version and available_versions to comparable objects.
# We'll use packaging.version.Version.
try:
current_ver = version.parse(current_version)
except:
print(f"Invalid current version: {current_version} for {dependency_key}")
return None
candidate_versions = []
for v in available_versions:
try:
ver = version.parse(v)
if ver <= current_ver:
continue
if strategy == 'conservative':
if ver.major != current_ver.major:
continue
candidate_versions.append(ver)
except:
continue
candidate_versions.sort()
for ver in candidate_versions:
safe = True
for vul in vulnerabilities:
if self.is_version_vulnerable(dependency_key, str(ver), vul):
safe = False
break
if safe:
return str(ver)
return None
def run(self):
vulns_by_dep = self.get_vulnerabilities_by_dependency()
deps = self.get_dependencies()
updated_deps = []
exceptions = []
unfixed = []
for group, artifact, version_elem in deps:
key = f"{group}:{artifact}"
if key not in vulns_by_dep:
continue
dep_vulns = vulns_by_dep[key]
current_version = version_elem.text.strip()
non_exceptioned_vulns = []
for vul in dep_vulns:
cve = vul.get('cve')
if not self.is_exceptioned(key, cve):
non_exceptioned_vulns.append(vul)
else:
exceptions.append({
'dependency': key,
'vulnerability': cve,
'reason': next((exc['reason'] for exc in self.config.get('exceptions', []) if exc['dependency']==key and exc['vulnerability']==cve), '')
})
if not non_exceptioned_vulns:
continue
safe_version = self.find_safe_version(key, current_version, non_exceptioned_vulns, self.config.get('strategy', 'conservative'))
if safe_version:
version_elem.text = safe_version
fixed_cves = [vul['cve'] for vul in non_exceptioned_vulns]
updated_deps.append({
'dependency': key,
'old_version': current_version,
'new_version': safe_version,
'fixed_vulnerabilities': fixed_cves
})
else:
unfixed.append({
'dependency': key,
'vulnerabilities': [vul['cve'] for vul in non_exceptioned_vulns],
'reason': 'No safe version found'
})
# Write the updated pom.
self.tree.write(self.pom_path, encoding='utf-8', xml_declaration=True)
# Generate report.
report = {
'updated_dependencies': updated_deps,
'exceptions': exceptions,
'unfixed_vulnerabilities': unfixed
}
return report
This is a simplified version.
We have to handle:
- XML namespaces in pom.xml.
- Better version range parsing.
- Error handling.
- Logging.
But the design is there.
Note: the version_in_range function is not implemented. We need to implement a Maven version range checker.
We can use the maven library? There is a Python package maven? Not sure.
Alternatively, we can use pom from maven? Not standard.
We might have to implement our own.
Given the complexity, we might change the design to rely on the scanner to tell us if a version is vulnerable? But the scanner only checks the current version.
We need to check arbitrary versions.
So we need a version range checker.
We can use the semantic_version library? But Maven versions are not semantic.
We can use the packaging.version and hope for the best? It might fail for beta versions.
Alternatively, we can use the lxml and compare as strings? That's not correct.
We might have to implement a Maven version comparator.
Given the time, we'll leave it as a TODO.
This design is a starting point.
We can also consider:
- Supporting other build tools (Gradle, npm, etc.) by having different implementations for get_dependencies, set_dependency_version, and get_available_versions.
- Using a local cache for the Maven metadata to avoid fetching every time.
- Allowing the user to specify a custom repository URL.
But for now, we have a design for Maven.
Let me know if you have any questions.
I'll design a comprehensive Dependency Vulnerability Auto-Remediation System with Exception Management. This system automates vulnerability fixing while allowing controlled exceptions for legitimate cases.
System Architecture
┌─────────────────────────────────────────────────────────────┐
│ AUTOREMEDIATION ENGINE │
├─────────────┬─────────────┬─────────────┬─────────────────┤
│ Scanner │ Remediation │ Exception │ Reporting │
│ Interface │ Engine │ Manager │ & Audit │
└─────────────┴─────────────┴─────────────┴─────────────────┘
│ │ │
┌────▼────┐ ┌────▼────┐ ┌────▼────┐
│ SCA │ │ Version │ │ Approval│
│ Tools │ │ Updater │ │ Workflow │
│ (OWASP, │ │(npm, pip,│ │ │
│ Snyk, │ │ maven,...)│ │ │
│ Trivy) │ │ │ │ │
└─────────┘ └──────────┘ └──────────┘
Core Components
1. Scanner Integration Layer
class VulnerabilityScanner:
def scan_project(self, path: str) -> List[Vulnerability]:
"""Integrates with multiple SCA tools"""
vulnerabilities = []
# OWASP Dependency Check
owasp_results = run_owasp_dependency_check(path)
vulnerabilities.extend(parse_owasp(owasp_results))
# Snyk
snyk_results = run_snyk_scan(path)
vulnerabilities.extend(parse_snyk(snyk_results))
# Trivy (for containers)
trivy_results = run_trivy_scan(path)
vulnerabilities.extend(parse_trivy(trivy_results))
return deduplicate_vulnerabilities(vulnerabilities)
2. Remediation Engine with Exception Handling
class RemediationEngine:
def __init__(self, config: RemediationConfig):
self.config = config
self.exception_manager = ExceptionManager(config.exception_db)
self.package_managers = {
'javascript': NpmManager(),
'python': PipManager(),
'java': MavenManager(),
'go': GoModManager(),
'ruby': BundlerManager()
}
def auto_remediate(self, vulnerabilities: List[Vulnerability]) -> RemediationResult:
results = RemediationResult()
for vuln in vulnerabilities:
# Check for existing exception
if self.exception_manager.is_excepted(vuln):
results.add_exception(vuln, self.exception_manager.get_exception_reason(vuln))
continue
# Check if auto-remediation is allowed for this package
if not self.is_auto_remediatable(vuln):
results.add_manual_review(vuln, "Package excluded from auto-remediation")
continue
# Attempt remediation
success, new_version, error = self.attempt_remediation(vuln)
if success:
results.add_fixed(vuln, new_version)
else:
# Check if we should create an exception
if self.should_create_exception(vuln, error):
exception = self.create_exception(vuln, error, self.config.auto_exception_rules)
self.exception_manager.add_exception(exception)
results.add_exception(vuln, f"Auto-excepted: {error}")
else:
results.add_failed(vuln, error)
return results
def attempt_remediation(self, vuln: Vulnerability) -> Tuple[bool, str, str]:
"""Try to update dependency to safe version"""
manager = self.package_managers[vuln.ecosystem]
# Get safe versions
safe_versions = manager.get_safe_versions(
vuln.package_name,
vuln.vulnerable_versions
)
if not safe_versions:
return False, "", "No safe versions available"
# Select best version based on policy
selected_version = self.select_version(safe_versions, vuln)
if not selected_version:
return False, "", "No suitable version found"
# Update dependency
try:
manager.update_dependency(vuln.package_name, selected_version)
return True, selected_version, ""
except Exception as e:
return False, "", str(e)
3. Exception Management System
class ExceptionManager:
def __init__(self, db_path: str):
self.db = ExceptionDatabase(db_path)
def is_excepted(self, vulnerability: Vulnerability) -> bool:
"""Check if vulnerability has active exception"""
return self.db.exists(
package=vulnerability.package_name,
cve=vulnerability.cve,
version=vulnerability.version,
status='active'
)
def create_exception(self, vuln: Vulnerability, reason: str,
auto_rule: AutoExceptionRule) -> Exception:
"""Create new exception with approval workflow"""
exception = Exception(
id=generate_exception_id(),
package=vuln.package_name,
cve=vuln.cve,
vulnerable_version=vuln.version,
reason=reason,
created_at=datetime.utcnow(),
expires_at=datetime.utcnow() + timedelta(days=auto_rule.max_days),
risk_level=self.assess_risk(vuln),
approval_required=auto_rule.requires_approval,
auto_approved=not auto_rule.requires_approval
)
if auto_rule.requires_approval:
exception.status = 'pending'
self.send_for_approval(exception)
else:
exception.status = 'active'
self.db.save(exception)
return exception
def get_exception_reason(self, vuln: Vulnerability) -> str:
"""Get reason for existing exception"""
exception = self.db.get_exception(
package=vuln.package_name,
cve=vuln.cve
)
return exception.reason if exception else "No exception found"
4. Configuration & Policies
# remediate-config.yaml
remediation:
strategy: "conservative" # conservative | aggressive | latest
auto_apply: true
backup_before_update: true
run_tests_after_update: true
max_parallel_updates: 5
exceptions:
database: "./exceptions.db"
auto_exception_rules:
- pattern: "*-test" # Test dependencies
max_days: 90
requires_approval: false
- severity: ["low", "medium"]
max_days: 30
requires_approval: true
- cvss_score: [0, 3.0] # Low CVSS
max_days: 180
requires_approval: false
- package: ["@babel/*", "eslint-*"]
reason: "False positive in dev dependencies"
max_days: 365
requires_approval: false
approval_workflow:
auto_approve_team: ["security-team"]
required_approvers: 1
escalation_after_days: 7
exclusions:
packages: [] # Never auto-update these
ecosystems: [] # Never auto-update these ecosystems
paths: ["./tests/", "./vendor/"] # Skip these directories
severity: ["critical"] # Don't auto-fix unless specified
5. CLI/API Interface
# Auto-remediate with exceptions
$ vuln-remediate --path ./myapp \
--scanner owasp,snyk \
--policy ./remediate-config.yaml \
--dry-run # Show what would change
# Manage exceptions
$ vuln-remediate exceptions list --status active
$ vuln-remediate exceptions approve EXC-123 --reason "Dev dependency, no prod impact"
$ vuln-remediate exceptions expire EXC-124
# Generate reports
$ vuln-remediate report --format html --output remediation-report.html
6. Approval Workflow Integration
class ApprovalWorkflow:
def __init__(self, config: ApprovalConfig):
self.config = config
self.notifiers = {
'slack': SlackNotifier(),
'email': EmailNotifier(),
'jira': JiraNotifier()
}
def request_approval(self, exception: Exception):
"""Send exception for approval"""
approvers = self.get_required_approvers(exception)
message = f"""
🔔 Exception Approval Required
Package: {exception.package}
CVE: {exception.cve}
Reason: {exception.reason}
Risk Level: {exception.risk_level}
Expires: {exception.expires_at}
Please approve: {self.config.approve_url}/{exception.id}
"""
for approver in approvers:
self.notifiers[self.config.notification_channel].send(
to=approver,
subject=f"Vulnerability Exception: {exception.package}",
message=message
)
7. Reporting & Audit Trail
class RemediationReport:
def generate(self, result: RemediationResult, format: str = 'json'):
report = {
'summary': {
'total_vulnerabilities': result.total,
'auto_fixed': result.fixed_count,
'exceptions': result.exception_count,
'failed': result.failed_count,
'manual_review': result.manual_count
},
'fixed': [
{
'package': fix.package,
'cve': fix.cve,
'old_version': fix.old_version,
'new_version': fix.new_version,
'ecosystem': fix.ecosystem,
'remediation_time': fix.remediation_time
}
for fix in result.fixed
],
'exceptions': [
{
'package': exc.package,
'cve': exc.cve,
'reason': exc.reason,
'approved_by': exc.approver,
'expires_at': exc.expires_at,
'risk_level': exc.risk_level
}
for exc in result.exceptions
],
'failed': [
{
'package': fail.package,
'cve': fail.cve,
'error': fail.error,
'recommended_action': fail.recommendation
}
for fail in result.failed
],
'audit_trail': self.get_audit_log(result.run_id)
}
return self.format_report(report, format)
Database Schema (SQLite Example)
-- Exceptions table
CREATE TABLE exceptions (
id TEXT PRIMARY KEY,
package TEXT NOT NULL,
ecosystem TEXT NOT NULL,
cve TEXT,
vulnerable_version TEXT,
reason TEXT NOT NULL,
risk_level TEXT CHECK(risk_level IN ('critical', 'high', 'medium', 'low')),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP NOT NULL,
status TEXT CHECK(status IN ('pending', 'active', 'expired', 'rejected')),
approved_by TEXT,
approved_at TIMESTAMP,
auto_approved BOOLEAN DEFAULT 0,
created_by TEXT NOT NULL
);
-- Audit log
CREATE TABLE audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
action TEXT NOT NULL,
user TEXT,
details TEXT,
vulnerability_id TEXT,
exception_id TEXT,
FOREIGN KEY (vulnerability_id) REFERENCES vulnerabilities(id),
FOREIGN KEY (exception_id) REFERENCES exceptions(id)
);
Implementation Strategy
Phase 1: Basic Auto-Remediation
- Integrate 1-2 SCA tools (OWASP Dependency Check + Snyk)
- Implement version updating for 1-2 package managers (npm/pip)
- Basic exception storage (flat file or SQLite)
- Simple CLI interface
Phase 2: Exception Management
- Approval workflow (email/Slack notifications)
- Risk-based exception policies
- Exception expiry and renewal
- Audit logging
Phase 3: Enterprise Features
- Multi-repository support (Nexus, Artifactory)
- CI/CD integrations (GitHub Actions, Jenkins, GitLab CI)
- Policy as Code (OPA/Conftest integration)
- Dashboard & reporting (Grafana/Elastic)
- RBAC and team-based approvals
Phase 4: Advanced Features
- Machine learning for false positive detection
- Impact analysis (breaking changes detection)
- Canary deployments with vulnerability validation
- Compliance reporting (SOC2, ISO27001)
Safety Mechanisms
- Dry Run Mode: Show changes without applying
- Backup & Rollback: Backup lock files before updates
- Test Integration: Run tests after updates
- Staged Rollout: Update one dependency at a time
- Blocking Rules: Never update certain packages (e.g.,
openssl)
- CVSS Threshold: Only auto-fix CVSS ≥ 7.0 by default
Example Workflow
1. Scan → 15 vulnerabilities found
2. Check exceptions → 3 already excepted
3. Remaining 12:
- 8 auto-fixed (safe versions available)
- 2 need manual review (breaking changes likely)
- 2 auto-excepted (low severity, test deps)
4. Apply fixes → 8 dependencies updated
5. Run tests → All passed
6. Commit changes with conventional commit:
"chore(deps): auto-fix vulnerabilities in @babel/core, lodash, etc."
7. Create PR with remediation report
8. Notify team
Security Considerations
- Principle of Least Privilege: Tool runs with minimal permissions
- Secret Scanning: Ensure no credentials in PRs
- Immutable Logs: All actions audit-logged and signed
- Supply Chain Security: Verify package signatures
- Rate Limiting: Prevent repository DoS
- Secret Management: Use vault for API keys
Monitoring & Alerting
alerts:
- metric: "remediation.failure_rate"
threshold: >0.2
severity: warning
message: "High remediation failure rate"
- metric: "exceptions.expiring_soon"
threshold: >5
severity: critical
message: "Multiple exceptions expiring in 7 days"
- metric: "vulnerability.trend"
direction: "increasing"
threshold: 10%
severity: warning
This system provides safe, auditable, and policy-driven vulnerability remediation while maintaining control through the exception management process. The key is balancing automation with human oversight for legitimate exceptions.