Rust软件物料清单生成库cyclonedx-bom的使用,cyclonedx-bom可生成符合CycloneDX标准的SBOM(软件物料清单)

Rust软件物料清单生成库cyclonedx-bom的使用

cyclonedx-bom是一个Rust库,用于生成符合CycloneDX标准的软件物料清单(SBOM)。CycloneDX是一个全栈SBOM/xBOM标准,设计用于应用安全上下文和供应链组件分析。

支持的CycloneDX版本

该库目前支持CycloneDX 1.3、1.4和1.5版本。

使用方法

读取和验证SBOM

use cyclonedx_bom::prelude::*;

// 定义要解析的BOM JSON字符串
let bom_json = r#"{
  "bomFormat": "CycloneDX",
  "specVersion": "1.5",
  "serialNumber": "urn:uuid:3e671687-395b-41f5-a30f-a58921a69b79",
  "version": 1
}"#;

// 解析JSON字符串为BOM对象
let bom = Bom::parse_from_json_v1_5(bom_json.as_bytes()).expect("Failed to parse BOM");

// 验证BOM是否符合规范
let validation_result = bom.validate();
assert!(validation_result.passed());

创建并输出SBOM

use cyclonedx_bom::prelude::*;
use cyclonedx_bom::models::{
    tool::{Tool, Tools},
};

// 创建一个新的BOM对象
let bom = Bom {
    serial_number: Some(
        UrnUuid::new("urn:uuid:3e671687-395b-41f5-a30f-a58921a69b79".to_string())
            .expect("Failed to create UrnUuid"),
    ),
    metadata: Some(Metadata {
        tools: Some(Tools::List(vec![Tool {
            name: Some(NormalizedString::new("my_tool")),
            ..Tool::default()
        }])),
        ..Metadata::default()
    }),
    ..Bom::default()
};

// 准备输出缓冲区
let mut output = Vec::<u8>::new();

// 将BOM输出为JSON格式
bom.output_as_json_v1_5(&mut output)
    .expect("Failed to write BOM");
    
// 将输出转换为字符串并验证
let output = String::from_utf8(output).expect("Failed to read output as a string");
assert_eq!(
    output,
    r#"{
  "bomFormat": "CycloneDX",
  "specVersion": "1.5",
  "version": 1,
  "serialNumber": "urn:uuid:3e671687-395b-41f5-a30f-a58921a69b79",
  "metadata": {
    "tools": [
      {
        "name": "my_tool"
      }
    ]
  }
}"#
);

完整示例代码

以下是一个更完整的示例,展示如何使用cyclonedx-bom库创建、验证和输出SBOM:

use cyclonedx_bom::prelude::*;
use cyclonedx_bom::models::{
    tool::{Tool, Tools},
    metadata::Metadata,
};

fn main() {
    // 1. 创建一个新的BOM
    let bom = create_bom();
    
    // 2. 验证BOM
    validate_bom(&bom);
    
    // 3. 输出BOM为JSON格式
    output_bom_as_json(&bom);
}

// 创建BOM的函数
fn create_bom() -> Bom {
    Bom {
        serial_number: Some(
            UrnUuid::new("urn:uuid:3e671687-395b-41f5-a30f-a58921a69b79".to_string())
                .expect("Failed to create UrnUuid"),
        ),
        metadata: Some(Metadata {
            tools: Some(Tools::List(vec![
                Tool {
                    name: Some(NormalizedString::new("my_tool")),
                    version: Some(NormalizedString::new("1.0.0")),
                    ..Tool::default()
                },
                Tool {
                    name: Some(NormalizedString::new("other_tool")),
                    vendor: Some(NormalizedString::new("Example Inc.")),
                    ..Tool::default()
                }
            ])),
            ..Metadata::default()
        }),
        ..Bom::default()
    }
}

// 验证BOM的函数
fn validate_bom(bom: &Bom) {
    let validation_result = bom.validate();
    if validation_result.passed() {
        println!("BOM验证通过!");
    } else {
        println!("BOM验证失败: {:?}", validation_result);
    }
}

// 输出BOM为JSON的函数
fn output_bom_as_json(bom: &Bom) {
    let mut output = Vec::<u8>::new();
    bom.output_as_json_v1_5(&mut output)
        .expect("Failed to write BOM");
    
    let output_str = String::from_utf8(output).expect("Failed to read output as a string");
    println!("生成的BOM:\n{}", output_str);
}

安装

在项目目录中运行以下Cargo命令:

cargo add cyclonedx-bom

或者在Cargo.toml中添加以下行:

[dependencies]
cyclonedx-bom = "0.8.0"

许可证

CycloneDX Rust库使用Apache 2.0许可证。


1 回复

Rust软件物料清单生成库cyclonedx-bom使用指南

cyclonedx-bom是一个Rust库,用于生成符合CycloneDX标准的软件物料清单(SBOM)。CycloneDX是一个轻量级的SBOM标准,帮助组织识别和管理软件组件及其依赖关系。

安装

在Cargo.toml中添加依赖:

[dependencies]
cyclonedx-bom = "0.4"

基本使用方法

1. 生成SBOM

use cyclonedx_bom::prelude::*;
use cyclonedx_bom::models::bom::Bom;
use cyclonedx_bom::models::component::Component;
use cyclonedx_bom::models::component::Classification;

fn main() -> Result<(), CycloneDxError> {
    // 创建一个新的BOM
    let mut bom = Bom::new("urn:uuid:3e671687-395b-41f5-a30f-a58921a69b79");
    
    // 添加组件
    let component = Component::new(
        Classification::Library,
        "my-library",
        "1.0.0",
        "urn:uuid:3e671687-395b-41f5-a30f-a58921a69b80"
    );
    
    bom.add_component(component);
    
    // 输出为JSON
    let json = bom.to_json()?;
    println!("{}", json);
    
    Ok(())
}

2. 从Cargo.lock生成SBOM

use cyclonedx_bom::prelude::*;
use cyclonedx_bom::format::Format;

fn main() -> Result<(), CycloneDxError> {
    // 从Cargo.lock生成BOM
    let bom = Bom::from_cargo_lock(Format::Json)?;
    
    // 输出为XML
    let xml = bom.to_xml()?;
    println!("{}", xml);
    
    Ok(())
}

高级功能

1. 添加元数据

use cyclonedx_bom::models::metadata::{Metadata, Tool};

let mut bom = Bom::new("urn:uuid:3e671687-395b-41f5-a30f-a58921a69b79");

let mut metadata = Metadata::new();
metadata.add_tool(Tool::new("cyclonedx-bom", "0.4.0"));

bom.metadata = Some(metadata);

2. 添加许可证信息

use cyclonedx_bom::models::license::License;

let mut component = Component::new(
    Classification::Library,
    "my-library",
    "1.0.0",
    "urn:uuid:3e671687-395b-41f5-a30f-a58921a69b80"
);

component.add_license(License::new("MIT"));

3. 输出格式选项

use cyclonedx_bom::format::Format;

// 生成JSON格式
let json = bom.to_json_pretty()?;  // 美化格式
let json = bom.to_json()?;         // 紧凑格式

// 生成XML格式
let xml = bom.to_xml_pretty()?;    // 美化格式
let xml = bom.to_xml()?;           // 紧凑格式

命令行工具

cyclonedx-bom也可以作为命令行工具使用:

  1. 安装CLI工具:
cargo install cyclonedx-bom
  1. 为当前项目生成SBOM:
cyclonedx-bom generate --format json --output bom.json
  1. 可用选项:
--format <FORMAT>    输出格式(json/xml) [默认: json]
--output <FILE>      输出文件路径
--pretty             美化输出格式

实际应用场景

  1. 安全审计:识别项目中的依赖项及其版本,检查已知漏洞
  2. 合规性检查:确保所有依赖项都有适当的许可证
  3. 供应链安全:跟踪软件组件的来源和依赖关系

cyclonedx-bom库为Rust项目提供了生成标准SBOM的简单方法,有助于提高软件透明度和安全性。

完整示例demo

下面是一个结合了多个功能的完整示例:

use cyclonedx_bom::prelude::*;
use cyclonedx_bom::models::{
    bom::Bom,
    component::{Component, Classification},
    metadata::{Metadata, Tool},
    license::License
};
use cyclonedx_bom::format::Format;

fn main() -> Result<(), CycloneDxError> {
    // 创建一个新的BOM
    let mut bom = Bom::new("urn:uuid:3e671687-395b-41f5-a30f-a58921a69b79");
    
    // 添加元数据
    let mut metadata = Metadata::new();
    metadata.add_tool(Tool::new("cyclonedx-bom", "0.4.0"));
    bom.metadata = Some(metadata);
    
    // 添加主应用组件
    let mut app_component = Component::new(
        Classification::Application,
        "my-app",
        "1.0.0",
        "urn:uuid:3e671687-395b-41f5-a30f-a58921a69b80"
    );
    app_component.add_license(License::new("Apache-2.0"));
    bom.add_component(app_component);
    
    // 添加依赖库组件
    let mut lib_component = Component::new(
        Classification::Library,
        "serde",
        "1.0.0",
        "urn:uuid:3e671687-395b-41f5-a30f-a58921a69b81"
    );
    lib_component.add_license(License::new("MIT"));
    bom.add_component(lib_component);
    
    // 输出为JSON和XML格式
    println!("JSON格式输出:");
    println!("{}", bom.to_json_pretty()?);
    
    println!("\nXML格式输出:");
    println!("{}", bom.to_xml_pretty()?);
    
    Ok(())
}

这个完整示例展示了:

  • 创建新的BOM对象
  • 添加元数据信息
  • 添加多个组件(应用和库)
  • 为组件添加许可证信息
  • 以美观格式输出JSON和XML格式的SBOM

您可以根据实际项目需求,进一步扩展这个示例,添加更多的组件和详细信息。

回到顶部