Last active
December 12, 2021 11:19
-
-
Save akhil-reni/571f64aa63b376bf88a04d8cb5e293e4 to your computer and use it in GitHub Desktop.
Parse MVN dependency for Log4j2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from xml.etree import ElementTree | |
import re | |
from packaging import version | |
pattern = "\{(.*?)\}" | |
def stripNs(el): | |
if el.tag.startswith("{"): | |
el.tag = el.tag.split('}', 1)[1] # strip namespace | |
for k in el.attrib.keys(): | |
if k.startswith("{"): | |
k2 = k.split('}', 1)[1] | |
el.attrib[k2] = el.attrib[k] | |
del el.attrib[k] | |
for child in el: | |
stripNs(child) | |
return el | |
def parse_pom(pom_file_path="./sample-pom.xml"): | |
POM_FILE = pom_file_path | |
namespaces = {'xmlns': 'http://maven.apache.org/POM/4.0.0'} | |
tree = ElementTree.parse(POM_FILE) | |
root = tree.getroot() | |
properties = root.find(".//xmlns:properties", namespaces=namespaces) | |
_properties_dict = {} | |
if properties: | |
for property in properties.getchildren(): | |
_properties_dict[stripNs(property).tag] = property.text | |
print(_properties_dict) | |
deps = root.findall(".//xmlns:dependency", namespaces=namespaces) | |
_deps_dict = {} | |
for d in deps: | |
_dep_version = d.find("xmlns:version", namespaces=namespaces).text | |
if _dep_version.startswith("${"): | |
substring = re.search(pattern, _dep_version).group(1) | |
if substring in _properties_dict: | |
_deps_dict[d.find( | |
"xmlns:artifactId", namespaces=namespaces).text] = _properties_dict[substring] | |
else: | |
_deps_dict[d.find("xmlns:artifactId", | |
namespaces=namespaces).text] = None | |
else: | |
_deps_dict[d.find("xmlns:artifactId", namespaces=namespaces).text] = d.find( | |
"xmlns:version", namespaces=namespaces).text | |
return _deps_dict | |
def scan(): | |
deps = parse_pom() | |
if "log4j" in deps: | |
if version.parse(deps["log4j"]) >= version.parse('2.0.0-beta9') or version.parse(deps["log4j"]) <= version.parse('2.14.1'): | |
print("Vulnerable") | |
return True | |
if "log4j-api" in deps: | |
if version.parse(deps["log4j-api"]) >= version.parse('2.0.0-beta9') or version.parse(deps["log4j-api"]) <= version.parse('2.14.1'): | |
print("Vulnerable") | |
return True | |
if "log4j-core" in deps: | |
if version.parse(deps["log4j-core"]) >= version.parse('2.0.0-beta9') or version.parse(deps["log4j-core"]) <= version.parse('2.14.1'): | |
print("Vulnerable") | |
return True | |
if "log4j-slf4j-impl" in deps: | |
if version.parse(deps["log4j-slf4j-impl"]) >= version.parse('2.0.0-beta9') or version.parse(deps["log4j-slf4j-impl"]) <= version.parse('2.14.1'): | |
print("Vulnerable") | |
return True | |
print(scan()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment