|
| 1 | +import csv |
| 2 | + |
| 3 | +from django.core.management.base import BaseCommand, CommandError |
| 4 | + |
| 5 | +from apps.organizations.models import Tenant |
| 6 | +from apps.product_security.models import Component, Product, ProductRelease |
| 7 | +from apps.vulnerability_intelligence.models import CVEAssessment |
| 8 | +from apps.vulnerability_intelligence.services import CVERiskEnrichmentService |
| 9 | + |
| 10 | + |
| 11 | +def _parse_bool(value, default=False): |
| 12 | + if value is None or str(value).strip() == '': |
| 13 | + return default |
| 14 | + return str(value).strip().lower() in {'1', 'true', 'yes', 'ja', 'y'} |
| 15 | + |
| 16 | + |
| 17 | +class Command(BaseCommand): |
| 18 | + help = 'Imports tenant-specific CVE assessment context from CSV, suitable for Git/SBOM/scanner pipeline outputs.' |
| 19 | + |
| 20 | + def add_arguments(self, parser): |
| 21 | + parser.add_argument('tenant_slug', help='Tenant slug') |
| 22 | + parser.add_argument('file', help='Path to the CSV file') |
| 23 | + parser.add_argument('--user-id', type=int, required=True, help='User ID for audit logging') |
| 24 | + |
| 25 | + def handle(self, *args, **options): |
| 26 | + try: |
| 27 | + tenant = Tenant.objects.get(slug=options['tenant_slug']) |
| 28 | + except Tenant.DoesNotExist as exc: |
| 29 | + raise CommandError(f"Tenant nicht gefunden: {options['tenant_slug']}") from exc |
| 30 | + |
| 31 | + user_model = Tenant._meta.apps.get_model('accounts', 'User') |
| 32 | + try: |
| 33 | + user = user_model.objects.get(pk=options['user_id']) |
| 34 | + except user_model.DoesNotExist as exc: |
| 35 | + raise CommandError(f"User nicht gefunden: {options['user_id']}") from exc |
| 36 | + |
| 37 | + created = 0 |
| 38 | + updated = 0 |
| 39 | + try: |
| 40 | + with open(options['file'], 'r', encoding='utf-8-sig', newline='') as handle: |
| 41 | + reader = csv.DictReader(handle) |
| 42 | + for row in reader: |
| 43 | + cve_id = str(row.get('cve_id') or row.get('cve') or '').strip().upper() |
| 44 | + if not cve_id: |
| 45 | + continue |
| 46 | + product = self._resolve_product(tenant, row.get('product')) |
| 47 | + release = self._resolve_release(tenant, product, row.get('release')) |
| 48 | + component = self._resolve_component(tenant, product, row.get('component')) |
| 49 | + assessment, was_created = self._upsert_assessment( |
| 50 | + tenant=tenant, |
| 51 | + user=user, |
| 52 | + cve_id=cve_id, |
| 53 | + product=product, |
| 54 | + release=release, |
| 55 | + component=component, |
| 56 | + row=row, |
| 57 | + ) |
| 58 | + created += int(was_created) |
| 59 | + updated += int(not was_created) |
| 60 | + except FileNotFoundError as exc: |
| 61 | + raise CommandError(f"Datei nicht gefunden: {options['file']}") from exc |
| 62 | + except Exception as exc: |
| 63 | + raise CommandError(f'CSV-Import fehlgeschlagen: {exc}') from exc |
| 64 | + |
| 65 | + self.stdout.write(self.style.SUCCESS( |
| 66 | + f'CSV-Kontext importiert. Neu: {created} | aktualisiert: {updated}' |
| 67 | + )) |
| 68 | + |
| 69 | + def _upsert_assessment(self, *, tenant, user, cve_id, product, release, component, row): |
| 70 | + existing = CVEAssessment.objects.filter( |
| 71 | + tenant=tenant, |
| 72 | + cve__cve_id=cve_id, |
| 73 | + product=product, |
| 74 | + release=release, |
| 75 | + component=component, |
| 76 | + ).first() |
| 77 | + assessment = CVERiskEnrichmentService.create_or_update_assessment( |
| 78 | + tenant=tenant, |
| 79 | + user=user, |
| 80 | + cve_id=cve_id, |
| 81 | + product=product, |
| 82 | + release=release, |
| 83 | + component=component, |
| 84 | + exposure=(row.get('exposure') or CVEAssessment.Exposure.UNKNOWN).strip().upper(), |
| 85 | + asset_criticality=(row.get('asset_criticality') or CVEAssessment.AssetCriticality.MEDIUM).strip().upper(), |
| 86 | + epss_score=(row.get('epss_score') or None), |
| 87 | + in_kev_catalog=self._optional_bool(row.get('in_kev_catalog')), |
| 88 | + exploit_maturity=(row.get('exploit_maturity') or CVEAssessment.ExploitMaturity.UNKNOWN).strip().upper(), |
| 89 | + affects_critical_service=_parse_bool(row.get('affects_critical_service')), |
| 90 | + nis2_relevant=self._optional_bool(row.get('nis2_relevant')), |
| 91 | + nis2_impact_summary=(row.get('nis2_impact_summary') or '').strip(), |
| 92 | + repository_name=(row.get('repository_name') or '').strip(), |
| 93 | + repository_url=(row.get('repository_url') or '').strip(), |
| 94 | + git_ref=(row.get('git_ref') or '').strip(), |
| 95 | + source_package=(row.get('source_package') or '').strip(), |
| 96 | + source_package_version=(row.get('source_package_version') or '').strip(), |
| 97 | + regulatory_tags=self._split_tags(row.get('regulatory_tags')), |
| 98 | + business_context=(row.get('business_context') or '').strip(), |
| 99 | + existing_controls=(row.get('existing_controls') or '').strip(), |
| 100 | + auto_create_risk=_parse_bool(row.get('auto_create_risk'), default=True), |
| 101 | + run_llm=_parse_bool(row.get('run_llm')), |
| 102 | + ) |
| 103 | + return assessment, existing is None |
| 104 | + |
| 105 | + def _resolve_product(self, tenant, name): |
| 106 | + value = (name or '').strip() |
| 107 | + if not value: |
| 108 | + return None |
| 109 | + return Product.objects.for_tenant(tenant).filter(name=value).first() |
| 110 | + |
| 111 | + def _resolve_release(self, tenant, product, version): |
| 112 | + value = (version or '').strip() |
| 113 | + if not value: |
| 114 | + return None |
| 115 | + queryset = ProductRelease.objects.for_tenant(tenant) |
| 116 | + if product is not None: |
| 117 | + queryset = queryset.filter(product=product) |
| 118 | + return queryset.filter(version=value).first() |
| 119 | + |
| 120 | + def _resolve_component(self, tenant, product, name): |
| 121 | + value = (name or '').strip() |
| 122 | + if not value: |
| 123 | + return None |
| 124 | + queryset = Component.objects.for_tenant(tenant) |
| 125 | + if product is not None: |
| 126 | + queryset = queryset.filter(product=product) |
| 127 | + return queryset.filter(name=value).first() |
| 128 | + |
| 129 | + def _optional_bool(self, value): |
| 130 | + if value is None or str(value).strip() == '': |
| 131 | + return None |
| 132 | + return _parse_bool(value) |
| 133 | + |
| 134 | + def _split_tags(self, value): |
| 135 | + if not value: |
| 136 | + return [] |
| 137 | + return [tag.strip().upper() for tag in str(value).split(',') if tag.strip()] |
0 commit comments