Skip to content

Commit

Permalink
Fix for SPDX validation failure due to invalid CPE strings
Browse files Browse the repository at this point in the history
I've fixed an issue where an error occurs when generating SPDX SBOM
for packages with '+' in their names, due to an invalid CPE string.

Also, I've fixed to escape special characters other than +.
As spdx-tools does not support percent encoding, I'm using backslash
escape encoding instead.

This patch fixes:
  - AlmaLinux#43
  • Loading branch information
KAWAHARA-souta committed Aug 26, 2024
1 parent e893de0 commit 1fa3f71
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
5 changes: 3 additions & 2 deletions alma_sbom.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from libsbom import cyclonedx as alma_cyclonedx
from libsbom import spdx as alma_spdx
from libsbom import common

ALBS_URL = 'https://build.almalinux.org'
IS_SIGNED = 3
Expand Down Expand Up @@ -164,8 +165,8 @@ def _generate_cpe(package_nevra: PackageNevra) -> str:
cpe_epoch_part += '\\:' if cpe_epoch_part else ""
cpe = (
f'cpe:{cpe_version}:a:almalinux:'
f'{package_nevra.name}:{cpe_epoch_part}'
f'{package_nevra.version}-{package_nevra.release}:*:*:*:*:*:*:*'
f'{common.escape_encode_cpe_part(package_nevra.name)}:{cpe_epoch_part}'
f'{common.escape_encode_cpe_part(package_nevra.version)}-{common.escape_encode_cpe_part(package_nevra.release)}:*:*:*:*:*:*:*'
)
return cpe

Expand Down
13 changes: 13 additions & 0 deletions libsbom/common.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import typing
import re

def replace_patterns(input_str: str, patterns: typing.Dict[str, str]) -> str:
"""Convenience function to perform multiple string replacements."""
Expand Down Expand Up @@ -34,6 +35,18 @@ def normalize_epoch_in_purl(purl: str) -> str:
return replace_patterns(input_str=purl,
patterns=patterns)

def escape_encode_cpe_part(cpe: str) -> str:
"""Escape special characters in cpe each part in accordance with the spdx-tools validation"""

allowed_chars = r'a-zA-Z0-9\-\._'
escape_chars = r'\\*?!"#$%&\'()+,/:;<=>@[]^`{|}~'

def encode_char(match):
char = match.group(0)
if char in escape_chars:
return '\\' + char

return re.sub(f'[^{allowed_chars}]', encode_char, cpe)

def normalize_epoch_in_cpe(cpe: str) -> str:
"""Replace unset epochs in CPEs with 0."""
Expand Down

0 comments on commit 1fa3f71

Please sign in to comment.