Metadata-Version: 2.4
Name: sbom-pipeline
Version: 2.2.0
Summary: SBOM Generator & Formatter — full Python pipeline (no shell)
Project-URL: Homepage, https://github.com/geminishkv/sbom_genform
Project-URL: Repository, https://github.com/geminishkv/sbom_genform
Project-URL: Issues, https://github.com/geminishkv/sbom_genform/issues
Project-URL: Changelog, https://github.com/geminishkv/sbom_genform/blob/master/RELEASE%20NOTES.md
Author-email: Elijah S Shmakov <geminishkv@gmail.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
License-File: LICENSE.md
License-File: NOTICE.md
Keywords: appsec,cyclonedx,devsecops,owasp,sbom,sca,security,software-bill-of-materials,trivy,vulnerability
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Build Tools
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: beautifulsoup4>=4.12.0
Requires-Dist: cyclonedx-bom>=4.0.0
Requires-Dist: defusedxml>=0.7.1
Requires-Dist: gitpython>=3.1.40
Requires-Dist: odfpy>=1.4.1
Requires-Dist: openpyxl>=3.1.0
Requires-Dist: packageurl-python>=0.11.0
Requires-Dist: pandas>=2.0.0
Requires-Dist: python-docx>=1.1.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: requests>=2.31.0
Requires-Dist: rich>=13.0.0
Requires-Dist: typer>=0.12.0
Provides-Extra: dev
Requires-Dist: mypy>=1.10.0; extra == 'dev'
Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: ruff>=0.4.0; extra == 'dev'
Requires-Dist: types-requests; extra == 'dev'
Description-Content-Type: text/markdown

<div align="center">
<h1><a id="intro"> SBOM Security Generator & Formatter  <sup></sup></a><br></h1>
<a href="https://docs.github.com/en"><img src="https://img.shields.io/static/v1?logo=github&logoColor=fff&label=&message=Docs&color=36393f&style=flat" alt="GitHub Docs"></a>
<a href="https://daringfireball.net/projects/markdown"><img src="https://img.shields.io/static/v1?logo=markdown&logoColor=fff&label=&message=Markdown&color=36393f&style=flat" alt="Markdown"></a>
<a href="https://symbl.cc/en/unicode-table"><img src="https://img.shields.io/static/v1?logo=unicode&logoColor=fff&label=&message=Unicode&color=36393f&style=flat" alt="Unicode"></a>
<a href="https://shields.io"><img src="https://img.shields.io/static/v1?logo=shieldsdotio&logoColor=fff&label=&message=Shields&color=36393f&style=flat" alt="Shields"></a>
<img src="https://img.shields.io/badge/Contributor-Шмаков_И._С.-8b9aff" alt="Contributor Badge">
</div>

<div align="center">
<img src="https://img.shields.io/github/repo-size/geminishkv/sbom_genform" alt="repo size">
<img src="https://img.shields.io/github/last-commit/geminishkv/sbom_genform" alt="last commit">
<img src="https://img.shields.io/github/commit-activity/m/geminishkv/sbom_genform" alt="commit activity">
<img src="https://img.shields.io/github/issues-pr/geminishkv/sbom_genform" alt="open PRs">
<img src="https://img.shields.io/github/contributors/geminishkv/sbom_genform" alt="contributors">
</div>

<div align="center">

[![CI](https://github.com/geminishkv/sbom_genform/actions/workflows/ci.yml/badge.svg)](https://github.com/geminishkv/sbom_genform/actions/workflows/ci.yml)
[![Docker Hub](https://img.shields.io/docker/v/geminishkvdev/sbom-pipeline?label=Docker%20Hub&logo=docker)](https://hub.docker.com/r/geminishkvdev/sbom-pipeline)
[![PyPI](https://img.shields.io/pypi/v/sbom-pipeline)](https://pypi.org/project/sbom-pipeline/)
[![Python](https://img.shields.io/pypi/pyversions/sbom-pipeline)](https://pypi.org/project/sbom-pipeline/)
[![License](https://img.shields.io/github/license/geminishkv/sbom_genform)](LICENSE.md)
[![GitHub Package](https://img.shields.io/badge/GitHub_Packages-sbom--pipeline-8b9aff)](https://github.com/geminishkv/sbom_genform/packages)

</div>

Инструмент для безопасной генерации, анализа и форматирования **Software Bill of Materials (SBOM)**.
![runhelp](assets/gifs/cmds/full_run_trimmed.gif)

## Навигация

**Документация** (`docs/`):

- [**Руководство пользователя**](docs/USAGE.md#руководство-пользователя) — быстрый старт
- [**Полное руководство (Manual)**](docs/MANUAL.md) — все команды, флаги и примеры
- [**Демонстрация команд**](docs/demo/DEMO.md#демонстрация-работы-команд) — гифки работы CLI
- [**Примеры результатов**](docs/RESULT_EXAMPLES.md#примеры-результатов) — образцы SBOM и отчётов
- [**Права доступа**](docs/PERMISSIONS.md#required-filesystem-permissions) — требования к файловой системе
- [**Troubleshooting**](docs/TROUBLESHOOTING.md#troubleshooting) — частые проблемы и их решения

**Разделы README:**

- [**Установка**](#установка)
- [**Выходные артефакты**](#выходные-артефакты)
- [**BDU Enrichment**](#bdu-enrichment)
- [**Docker**](#docker)
- [**Архитектура**](#архитектура)

**Что делает:**

- Генерирует SBOM двумя генераторами (**cdxgen** + **syft**) и объединяет результат — из локальной директории, Git-репозитория (GitHub / GitLab) или контейнерного образа
- Дедуплицирует компоненты по PURL и уязвимости по CVE+компонент
- Создаёт **два подписанных SBOM**: без уязвимостей и с ними
- Сканирует уязвимости **параллельно** через **Trivy**, **OWASP Dependency-Check**, **Clair**
- Встраивает найденные уязвимости в SBOM (CycloneDX 1.5)
- Опционально обогащает уязвимости идентификаторами **БДУ ФСТЭК**
- Экспортирует читаемые отчёты: **Excel (.xlsx)**, **Word (.docx)**, **ODT (.odt)**
- Готовит SBOM под требования ФСТЭК (`secsbom cert` — поля GOST)

***

## Main CLI

![mainhelp](assets/gifs/help_main.gif)

***

## Установка

**PyPI:**

```bash
pip install sbom-pipeline
```

**GitHub Packages:**

```bash
pip install sbom-pipeline \
  --index-url https://${GITHUB_TOKEN}@pypi.pkg.github.com/geminishkv/
```

**Исходники:**

```bash
git clone https://github.com/geminishkv/sbom_genform.git
cd sbom_genform
python3 -m venv venv && source venv/bin/activate
pip install -e ".[dev]"
```

## Запуск утилиты

После установки доступна помощь:

```bash
secsbom --help
```

> 📖 **Полное пошаговое руководство** со всеми командами, сценариями и переменными окружения — в [docs/USAGE.md](docs/USAGE.md#руководство-пользователя).

Утилиту нужно запускать от обычного пользователя. Запуск с правами администратора/root
завершается ошибкой, чтобы не выполнять сканеры и Docker-команды с лишними привилегиями.

### Быстрый старт

Полный пайплайн генерирует SBOM, дедуплицирует компоненты, подписывает SBOM,
сканирует уязвимости и экспортирует отчёты:

```bash
# локальный демо-проект
secsbom run

# указание локального проекта из примеров
secsbom run --path examples/project_inject

# удалёный репозиторий github с токеном
secsbom run --url https://github.com/org/repo --token ghp_... 

# удалёный репозиторий gitlab с токеном
secsbom run --url https://gitlab.com/org/repo --token glpat-... 
```

По умолчанию артефакты пишутся в `secgensbom_out`, отчёты — в
`secgensbom_reports`.

### Основные режимы

Сгенерировать и подписать SBOM без этапа сканирования уязвимостей:

```bash
secsbom gen-sbom --path examples/project_inject
```

Просканировать уже готовый SBOM (и/или контейнерный образ) и сформировать отчёты только по уязвимостям:

```bash
# путь к папке проекта + готовый SBOM
secsbom scan secgensbom_out/app-bom-dedup-signed.json --path examples/project_inject

# только готовый SBOM
secsbom scan secgensbom_out/app-bom-dedup-signed.json

# только контейнерный образ
secsbom scan --clair --image nginx:latest
```

Отформатировать готовые SBOM JSON в Excel/Word/ODT:

```bash
secsbom format --sbom-dir secgensbom_out --report-dir secgensbom_reports
```

Проверить подпись SBOM:

```bash
secsbom verify secgensbom_out/merged-bom-signed.json
```

> **Примечание:** SHA-256-подпись — это контрольная сумма **целостности** (защита от случайной порчи), а не криптографическая подпись: она не подтверждает аутентичность источника, поскольку хэш и `.sig` пересчитываются после любого изменения файла. Для аутентичности и неотрекаемости используйте внешнюю подпись (cosign / sigstore).

Посмотреть краткую информацию по SBOM:

```bash
secsbom info secgensbom_out/merged-bom-signed.json
```

Проверить наличие внешних инструментов:

```bash
secsbom status
```

Сравнить два SBOM:

```bash
secsbom diff old-bom.json new-bom.json
```

Добавить поля GOST для отчёта по требованиям ФСТЭК:

```bash
secsbom cert sbom.json \
  --component-name "My Product" \
  --component-version "1.0.0" \
  --manufacturer "My Company"
```

### Полезные флаги и переменные

```bash
secsbom run --no-cdxgen          # не использовать cdxgen
secsbom run --no-syft            # не использовать syft
secsbom run --bdu                # включить BDU-обогащение
secsbom run --clair --image nginx:latest
secsbom run -o secgensbom_out --reports-dir secgensbom_reports
```

Те же настройки можно передавать через переменные окружения:

```bash
export PROJECT_DIR=examples/project_inject
export OUTPUT_DIR=secgensbom_out
export REPORTS_DIR=secgensbom_reports
export BDU=true
export NVD_API_KEY=<token>

secsbom run
```

Для `scan` используются кэши внешних данных:

- `.dependency-check-data` / `DEP_CHECK_DATA` — база NVD для OWASP Dependency-Check
- `.bdu_cache` / `BDU_CACHE_DIR` — соответствия CVE -> BDU ID

Сами этапы `scan` при повторном запуске выполняются заново, кэшируются именно
базы и справочные ответы внешних инструментов.

***

## Выходные артефакты

### SBOM JSON

| Файл                                              | Описание                                   |
| ------------------------------------------------- | ------------------------------------------ |
| `secgensbom_out/app-bom-cdxgen.json`              | SBOM от cdxgen                             |
| `secgensbom_out/app-bom-syft.json`                | SBOM от syft                               |
| `secgensbom_out/app-bom-merged.json`              | Объединённый SBOM (cdxgen + syft)          |
| `secgensbom_out/app-bom-dedup.json`               | После дедупликации компонентов             |
| `secgensbom_out/app-bom-dedup-signed.json`        | Подписанный SBOM **без** уязвимостей       |
| `secgensbom_out/app-bom-dedup-signed.sig`         | SHA-256 контрольная сумма (без уязв.)      |
| `secgensbom_out/merged-bom-signed.json`           | Подписанный SBOM **с** уязвимостями        |
| `secgensbom_out/merged-bom-signed.sig`            | SHA-256 контрольная сумма (с уязв.)        |
| `secgensbom_out/vulns-normalized.json`            | Нормализованные уязвимости                 |
| `<sbom>(cert).json`                               | SBOM с полями GOST/ФСТЭК (команда `cert`)  |

Если включено BDU-обогащение, в `merged-bom-signed.json` идентификатор БДУ записывается в `vulnerabilities[].properties[]` как свойство с именем `ru.fstec.bdu:id`.

### Отчёты сканеров

| Путь | Сканер |
| --- | --- |
| `secgensbom_out/trivy/trivy-fs.json` | Trivy — файловая система |
| `secgensbom_out/trivy/sbom-vulns.json` | Trivy — анализ SBOM |
| `secgensbom_out/dependency-check/` | OWASP Dependency-Check |
| `secgensbom_out/clair/` | Clair (если включён) |

### Reports

| Путь                              | Формат | Содержимое                                |
| --------------------------------- | ------ | ----------------------------------------- |
| `secgensbom_reports/excel/*.xlsx` | Excel  | Лист 1: компоненты, Лист 2: уязвимости    |
| `secgensbom_reports/docx/*.docx`  | Word   | Таблица компонентов + таблица уязвимостей |
| `secgensbom_reports/odt/*.odt`    | ODT    | То же самое                               |

#### Лист «Компоненты»

| Колонка | Источник |
| ------- | -------- |
| № п/п | порядковый номер |
| Наименование компонента | `components[].name` из SBOM |
| Версия компонента | `components[].version` из SBOM |
| Тип пакета / тип компонента | тип экосистемы из PURL (`pypi`, `maven`, `npm`, `apk`, …) |
| PURL / технический идентификатор компонента | `components[].purl` из SBOM |
| Язык (языки) | определяется по PURL-типу (`dependency.py`) |
| Признак принадлежности к поверхности атаки | свойство компонента CycloneDX: `attack-surface` / `attackSurface` / `isAttackSurface` / `GOST: attack_surface` |
| Признак выполнения функций безопасности | свойство компонента CycloneDX: `security-function` / `securityFunction` / `isSecurityFunction` / `GOST: security_function` |
| Принадлежность к контейнерному образу | `metadata.component.name` (только если `type = "container"`) |
| Роль компонента в составе контейнерного образа | свойство компонента: `container-role` / `containerRole` / `cdx:docker:layer` / `layer` |
| Адрес веб-ресурса | реестровый URL, вычисленный по PURL |

#### Лист «Уязвимости»

| Колонка | Источник |
| ------- | -------- |
| Компонент | имя пакета из сканера |
| Версия | версия при сканировании |
| CVE / ID | идентификатор уязвимости |
| CVSS | оценка CVSS v3 / v2 |
| Критичность | `CRITICAL` / `HIGH` / `MEDIUM` / `LOW` / `UNKNOWN` |
| Описание | первые 200 символов описания |
| Сканер | `trivy` / `clair` / `dependency-check` |
| Исправлено в версии | версия с исправлением (если известна) |
| Рекомендация / компенсирующая мера | Trivy: `PrimaryURL` → «Обновить до X»; Clair: `Links[0]`; Dependency-Check: `notes` → `references[].url` |
| Статус допустимости в рассматриваемой конфигурации | Trivy: поле `Status` (`fixed`, `affected`, `will_not_fix`, `end_of_life`, …) |

Если пайплайн запущен с `--bdu` или `BDU=true`, во всех форматах отчётов уязвимостей появляется отдельная колонка `BDU / ID`. Если BDU-обогащение выключено, эта колонка не выводится.

---

## Примеры результатов

Подробные примеры итогового SBOM, `vulns-normalized.json` и экспортируемых таблиц вынесены в [docs/RESULT_EXAMPLES.md](docs/RESULT_EXAMPLES.md#примеры-результатов).

Короткий пример структуры после полного запуска:

```text
secgensbom_out/
├── app-bom-dedup-signed.json
├── merged-bom-signed.json
├── vulns-normalized.json
├── dependency-check/
├── trivy/
└── clair/
secgensbom_reports/
├── excel/merged-bom-signed.xlsx
├── docx/merged-bom-signed.docx
└── odt/merged-bom-signed.odt
```

## BDU Enrichment

Обогащение идентификаторами БДУ ФСТЭК выключено по умолчанию.

Включение через CLI:

```bash
secsbom run --bdu
```

Включение через переменную окружения:

```bash
export BDU=true
secsbom run
```

При включённом BDU пайплайн:

- запрашивает соответствия `CVE -> BDU ID` через `bdu.fstec.ru`
- добавляет BDU ID в итоговый CycloneDX SBOM как свойство уязвимости
- выводит BDU ID в экспортируемые отчёты

Пример фрагмента SBOM:

```json
{
  "id": "CVE-2023-1234",
  "properties": [
    {
      "name": "ru.fstec.bdu:id",
      "value": "BDU:2023-01813"
    }
  ]
}
```

---

## Docker

Образ включает Python, Syft, Trivy, Docker CLI и Node.js/npx (cdxgen для non-Python проектов).
OWASP Dependency-Check запускается внутри утилиты через `docker run` (Docker-in-Docker), его Java-зависимость утяжелила бы основной образ на ~400 МБ.
Clair требует отдельного работающего HTTP-сервера — поэтому он вынесен в `docker-compose.yml`.

**Безопасность образа:** контейнер работает от непривилегированного пользователя `sbom` (uid 1001) — `secsbom` отказывается запускаться от root. В `docker-compose.yml` сервисам `secgensbom` / `scan` заданы `security_opt: no-new-privileges` и `cap_drop: ALL`. В образ встроен `HEALTHCHECK`, OCI-метки указывают лицензию Apache-2.0.

### Docker Hub (только Trivy, без Clair/Dependency-Check)

```bash
docker pull geminishkv/sbom-pipeline:latest

docker run --rm \
  -v "$(pwd)/examples/project_inject:/app/project_inject" \
  -v "$(pwd)/secgensbom_out:/app/secgensbom_out" \
  -v "$(pwd)/secgensbom_reports:/app/secgensbom_reports" \
  -v /var/run/docker.sock:/var/run/docker.sock \
  geminishkv/sbom-pipeline:latest
```

### Docker Compose (Trivy + Dependency-Check + Clair)

Полный стек с OWASP Dependency-Check и Clair v4 запускается через `docker-compose.yml`.

#### Всё одной командой (компоненты + контейнеры + SBOM + отчёты)

Поднимает Clair, собирает SBOM по исходному коду, сканирует уязвимости (Trivy + Dependency-Check + Clair) и контейнерный образ, обогащает БДУ ФСТЭК и выгружает отчёты — **NVD-ключ не нужен**:

```bash
SKIP_CLAIR=false BDU=true IMAGE_NAME=nginx:latest docker compose up --build
```

- **Код проекта** берётся из `./examples/project_inject` — замените содержимое этой папки на свой проект (или переопределите volume `secgensbom` в `docker-compose.yml`).
- **`IMAGE_NAME`** — контейнерный образ для сканирования через Clair (по умолчанию `postgres:14`).
- **`SKIP_CLAIR=false`** включает анализ контейнерного образа; **`BDU=true`** добавляет идентификаторы БДУ ФСТЭК.
- **Без `NVD_API_KEY`** база NVD для Dependency-Check скачается автоматически при первом запуске (~220 МБ, несколько минут; она кэшируется в `./.dependency-check-data` и переиспользуется далее). Clair на первом запуске прогревает updater'ы до ~10 минут.
- **Результат**: `./secgensbom_out/` (SBOM-артефакты) + `./secgensbom_reports/{excel,docx,odt}/` (отчёты по компонентам и уязвимостям).

Минимальный запуск (только демо-проект, без сканирования образа):

```bash
docker compose up --build
```

**Порядок запуска:**
1. `clair-db` (Postgres) — база данных Clair, ожидает healthcheck
2. `clair` — HTTP-сервер уязвимостей Clair v4, ожидает готовности БД
3. `secgensbom` — основной пайплайн, стартует после того, как Clair пройдёт healthcheck

**Что происходит внутри `secgensbom`:**
- Trivy запускается напрямую (встроен в образ)
- OWASP Dependency-Check запускается через `docker run owasp/dependency-check` (Docker-in-Docker через `/var/run/docker.sock`)
- Clair сканирует образ через `clairctl`, подключаясь к `http://clair:8080`

**Переменные окружения:**

| Переменная        | По умолчанию                              | Описание                                     |
| ----------------- | ----------------------------------------- | -------------------------------------------- |
| `SOURCE`          | `local`                                   | Источник проекта: `local`, `github`, `gitlab` |
| `PROJECT_DIR`     | `/app/project_inject`                     | Путь к проекту внутри контейнера             |
| `SKIP_CLAIR`      | `false`                                   | Отключить сканирование Clair (`true`/`false`) |
| `CLAIR_ENDPOINT`  | `http://clair:8080`                       | Адрес Clair API                              |
| `IMAGE_NAME`      | —                                         | Docker-образ для сканирования Clair          |
| `BDU`             | `false`                                   | Включить обогащение идентификаторами БДУ ФСТЭК |
| `DEP_CHECK_DATA`  | `/app/.dependency-check-data`             | Кэш NVD для Dependency-Check                 |
| `NVD_CACHE_DIR`   | `$DEP_CHECK_DATA/nvd-api-cache`           | Кэш ответов NVD API для повторного CVSS lookup |
| `SBOM_COMPONENT_NETWORK` | `false`                           | Разрешить сетевые уточнения языков/URL при экспорте компонентов |

> **Примечание:** Если `IMAGE_NAME` не задан, шаг Clair пропускается автоматически.

`NVD_CACHE_DIR` хранит ответы NVD API по CVE и используется Clair fallback при заполнении пустого CVSS. Повторный запуск берёт оценку из уже сохранённого ответа и не делает новый HTTP-запрос.
По умолчанию экспорт компонентов не ходит в npm/NuGet/Debian/GitHub за уточнениями; для максимально быстрых и воспроизводимых отчётов язык и URL вычисляются из PURL.

## Troubleshooting

Частые ошибки запуска, сетевых лимитов NVD, Docker/Clair и пустых отчётных колонок собраны в [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md#troubleshooting).

***

## CI/CD

### GitHub Actions

| Workflow         | Триггер              | Назначение                                              |
| ---------------- | -------------------- | ------------------------------------------------------- |
| `ci.yml`         | push / PR → main     | lint + mypy + pytest (3.11–3.13)                        |
| `secgensbom.yml` | push → `securitycheck`, вручную | запуск пайплайна, сохранение SBOM и отчётов |
| `publish.yml`    | тег `v*.*.*`         | GitHub Packages + PyPI + Docker Hub + GitHub Release    |

**Публикация новой версии** — один тег запускает всё:

```bash
git tag v2.2.0 -m "Release v2.2.0"
git push origin v2.2.0
```

### Shared template

Файл `secgensbom/secgensbom.yml` — это **переиспользуемый шаблон CI** для GitLab. Любой другой проект в GitLab может подключить готовый SBOM-шаг одной строкой, не копируя конфигурацию:

***

## Архитектура

### Пайплайн `secsbom run`

```mermaid
flowchart TD
    IN(["Источник\nlocal / github / gitlab / образ"]) --> STEP1

    subgraph pipeline["secsbom run — этапы"]
        subgraph STEP1["1 · Генерация SBOM"]
            direction TB
            CDXGEN["cdxgen\napp-bom-cdxgen.json"]
            SYFT["syft\napp-bom-syft.json"]
            GEN["generate.py — merge\napp-bom-merged.json"]
            CLAIR_SCAN["clair.py — run_scan_report()\nclair-*.json\nполучение пакетов образа"]
            CLAIR_ENRICH["clair.py — enrich_sbom_with_clair_packages()\nдобавление пакетов образа в SBOM\n(только добавление, без обновления)"]
            CDXGEN --> GEN
            SYFT --> GEN
            GEN --> CLAIR_SCAN --> CLAIR_ENRICH
        end

        STEP1 --> DEDUP["2 · dedup.py\napp-bom-dedup.json\nдедуп компонентов по PURL\n(cdxgen + syft + Clair)"]
        DEDUP --> SIGN1["3 · sign.py\napp-bom-dedup-signed.json + .sig\nSHA-256 — SBOM без уязвимостей"]
        SIGN1 --> SCAN

        subgraph SCAN["4 · scanner/ — параллельно (ThreadPoolExecutor)"]
            direction LR
            TRIVY_FS["trivy.py — scan_filesystem\ntrivy-fs.json (опц. --path)"]
            TRIVY_SBOM["trivy.py — scan_sbom\nsbom-vulns.json"]
            DEPCHECK["depcheck.py — docker run\ndependency-check-report.* (опц. --path)"]
            CLAIR_VULNS["clair.py — parse_report_findings()\n+ NVD CVSS fallback (опц. --image)"]
        end

        TRIVY_FS & TRIVY_SBOM & DEPCHECK & CLAIR_VULNS --> CROSS["cross-populate CVSS\nмежду сканерами"]
        CROSS --> DDUP2["5 · dedup.py\nдедуп уязвимостей\nпо CVE + компонент"]
        DDUP2 --> MERGE["6 · vuln_merger.py\nvulnerabilities[] в SBOM\n+ БДУ ФСТЭК (опц. --bdu)\nvulns-normalized.json"]
        MERGE --> SIGN2["7 · sign.py\nmerged-bom-signed.json + .sig\nSHA-256 — SBOM с уязвимостями"]
        SIGN2 --> EXPORT["8 · exporter.py"]
    end

    CLAIR_SCAN -.->|"отчёт повторно используется\nна этапе 4"| CLAIR_VULNS

    EXPORT --> XLSX["secgensbom_reports/\n*.xlsx"]
    EXPORT --> DOCX["secgensbom_reports/\n*.docx"]
    EXPORT --> ODT["secgensbom_reports/\n*.odt"]
```

***

## Структура репозитория

```text
sbom_genform/
├── src/sbom_pipeline/
│   ├── cli.py            # secsbom / secsbom-pipeline (typer)
│   ├── pipeline.py       # оркестратор
│   ├── generate.py       # генерация SBOM
│   ├── dedup.py          # дедупликация
│   ├── sign.py           # SHA-256 подпись
│   ├── exporter.py       # xlsx / docx / odt
│   ├── vuln_merger.py    # встраивание уязвимостей
│   ├── config.py         # конфигурация
│   ├── scanner/
│   │   ├── trivy.py
│   │   ├── depcheck.py
│   │   └── clair.py
│   └── enrichters/
│       ├── bdu.py        # БДУ ФСТЭК (CVE → BDU ID)
│       └── nvd.py        # NVD API (CVSS fallback)
├── docker/
│   └── Dockerfile.secgensbom
├── examples/project_inject/   # уязвимый PHP проект
├── secgensbom/secgensbom.yml  # GitLab CI shared template
├── .github/workflows/
│   ├── ci.yml
│   ├── secgensbom.yml
│   └── publish.yml
├── tests/test_smoke.py
├── pyproject.toml
└── .env.example
```

***

Copyright (c) 2026 Elijah S Shmakov

![Logo](assets/logo.jpg)
