Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Scvs feature support #323

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions cmd/scvs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright 2023 Interlynk.io
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd

import (
"context"
"fmt"

"github.com/interlynk-io/sbomqs/pkg/engine"
"github.com/interlynk-io/sbomqs/pkg/logger"
"github.com/spf13/cobra"
)

var scvsCmd = &cobra.Command{
Use: "scvs",
Short: "OWASP SCVS V2 Maturity Level Software Bill of Materials (SBOM) Requirements",
SilenceUsage: true,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) <= 0 {
if len(inFile) <= 0 && len(inDirPath) <= 0 {
return fmt.Errorf("provide a path to an sbom file or directory of sbom files")
}
}
return nil
},
RunE: processScvs,
}

func processScvs(cmd *cobra.Command, args []string) error {
debug, _ := cmd.Flags().GetBool("debug")
if debug {
logger.InitDebugLogger()
} else {
logger.InitProdLogger()
}

ctx := logger.WithLogger(context.Background())
uCmd := toUserCmd(cmd, args)

if err := validateFlags(uCmd); err != nil {
return err
}

engParams := toEngineParams(uCmd)
return engine.RunScvs(ctx, engParams)
}

func init() {
rootCmd.AddCommand(scvsCmd)

// Debug Control
scvsCmd.Flags().BoolP("debug", "D", false, "scvs compliance")

// Output Control
// scvsCmd.Flags().BoolP("json", "j", false, "results in json")
scvsCmd.Flags().BoolP("detailed", "d", true, "results in table format, default")
// scvsCmd.Flags().BoolP("basic", "b", false, "results in single line format")
}
2 changes: 1 addition & 1 deletion pkg/compliance/oct.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ func octSbomComment(doc sbom.Document) *record {
func octSbomNamespace(doc sbom.Document) *record {
result, score := "", 0.0

if ns := doc.Spec().GetNamespace(); ns != "" {
if ns := doc.Spec().GetUniqID(); ns != "" {
result = ns
score = 10.0
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/compliance/oct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func createDummyDocument() sbom.Document {
s.Format = "json"
s.SpecType = "spdx"
s.Name = "nano"
s.Namespace = "https://anchore.com/syft/dir/sbomqs-6ec18b03-96cb-4951-b299-929890c1cfc8"
s.UniqID = "https://anchore.com/syft/dir/sbomqs-6ec18b03-96cb-4951-b299-929890c1cfc8"
s.Organization = "interlynk"
s.CreationTimestamp = "2023-05-04T09:33:40Z"
s.Spdxid = "DOCUMENT"
Expand Down Expand Up @@ -308,7 +308,7 @@ func createFailureDummyDocument() sbom.Document {
s.Format = "xml"
s.SpecType = "cyclonedx"
s.Name = ""
s.Namespace = ""
s.UniqID = ""
s.Organization = ""
s.CreationTimestamp = "wrong-time-format"
s.Spdxid = ""
Expand Down
134 changes: 134 additions & 0 deletions pkg/engine/scvs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// Copyright 2023 Interlynk.io
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package engine

import (
"context"
"fmt"
"os"
"path/filepath"
"strings"

"github.com/interlynk-io/sbomqs/pkg/logger"
"github.com/interlynk-io/sbomqs/pkg/sbom"
"github.com/interlynk-io/sbomqs/pkg/scvs"
)

func RunScvs(ctx context.Context, ep *Params) error {
log := logger.FromContext(ctx)
log.Debug("engine.Run()")
log.Debug(ep)

if len(ep.Path) <= 0 {
log.Fatal("path is required")
}

return handleScvsPaths(ctx, ep)
}

func handleScvsPaths(ctx context.Context, ep *Params) error {
log := logger.FromContext(ctx)
log.Debug("engine.handlePaths()")

var docs []sbom.Document
var paths []string
var scores []scvs.ScvsScores

for _, path := range ep.Path {
log.Debugf("Processing path :%s\n", path)
pathInfo, _ := os.Stat(path)
if pathInfo.IsDir() {
files, err := os.ReadDir(path)
if err != nil {
log.Debugf("os.ReadDir failed for path:%s\n", path)
log.Debugf("%s\n", err)
continue
}
for _, file := range files {
log.Debugf("Processing file :%s\n", file.Name())
if file.IsDir() {
continue
}
path := filepath.Join(path, file.Name())
doc, scs, err := processScvsFile(ctx, ep, path)
if err != nil {
continue
}
docs = append(docs, doc)
scores = append(scores, scs)
paths = append(paths, path)
}
continue
}

doc, scs, err := processScvsFile(ctx, ep, path)
if err != nil {
continue
}
docs = append(docs, doc)
scores = append(scores, scs)
paths = append(paths, path)
}

reportFormat := "detailed"
if ep.Basic {
reportFormat = "basic"
} else if ep.JSON {
reportFormat = "json"
}

nr := scvs.NewScvsReport(ctx,
docs,
scores,
paths,
scvs.WithFormat(strings.ToLower(reportFormat)))

fmt.Println("Print the scvs report")
nr.ScvsReport()

return nil
}

func processScvsFile(ctx context.Context, ep *Params, path string) (sbom.Document, scvs.ScvsScores, error) {
log := logger.FromContext(ctx)
log.Debugf("Processing file :%s\n", path)

if _, err := os.Stat(path); err != nil {
log.Debugf("os.Stat failed for file :%s\n", path)
fmt.Printf("failed to stat %s\n", path)
return nil, nil, err
}

f, err := os.Open(path)
if err != nil {
log.Debugf("os.Open failed for file :%s\n", path)
fmt.Printf("failed to open %s\n", path)
return nil, nil, err
}
defer f.Close()

doc, err := sbom.NewSBOMDocument(ctx, f)
if err != nil {
log.Debugf("failed to create sbom document for :%s\n", path)
log.Debugf("%s\n", err)
fmt.Printf("failed to parse %s : %s\n", path, err)
return nil, nil, err
}

sr := scvs.NewScvsScorer(ctx, doc)

scores := sr.ScvsScore()
return doc, scores, nil
}
19 changes: 17 additions & 2 deletions pkg/licenses/license.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,21 @@ func (m meta) AboutCode() bool {
return m.source == "aboutcode"
}

func IsValidLicenseID(licenseKey string) bool {
if licenseKey == "" {
return false
}

if licenseKey == "none" || licenseKey == "noassertion" {
return false
}

_, lok := licenseList[licenseKey]
_, aok := licenseListAboutCode[licenseKey]

return lok || aok
}

func LookupSpdxLicense(licenseKey string) (License, error) {
if licenseKey == "" {
return nil, errors.New("license not found")
Expand Down Expand Up @@ -183,14 +198,14 @@ func LookupExpression(expression string, customLicenses []License) []License {
continue
}

//if custom license list is provided use that.
// if custom license list is provided use that.
license, err = customLookup(trimLicenseKey)
if err == nil {
licenses = append(licenses, license)
continue
}

//if nothing else this license is custom
// if nothing else this license is custom
licenses = append(licenses, CreateCustomLicense(trimLicenseKey, trimLicenseKey))
}

Expand Down
47 changes: 45 additions & 2 deletions pkg/sbom/cdx.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ type cdxDoc struct {
manufacturer Manufacturer
primaryComponentID string
compositions map[string]string
signature []GetSignature
}

func newCDXDoc(ctx context.Context, f io.ReadSeeker, format FileFormat) (Document, error) {
Expand Down Expand Up @@ -130,6 +131,10 @@ func (c cdxDoc) Manufacturer() Manufacturer {
return c.manufacturer
}

func (c cdxDoc) Signature() []GetSignature {
return c.signature
}

func (c *cdxDoc) parse() {
c.parseDoc()
c.parseSpec()
Expand All @@ -141,6 +146,7 @@ func (c *cdxDoc) parse() {
c.parseCompositions()
c.parseRels()
c.parseComps()
c.parseSignature()
}

func (c *cdxDoc) addToLogs(log string) {
Expand Down Expand Up @@ -189,16 +195,53 @@ func (c *cdxDoc) parseSpec() {
sp.Licenses = aggregateLicenses(*c.doc.Metadata.Licenses)
}
}
sp.Namespace = c.doc.SerialNumber
sp.UniqID = c.doc.SerialNumber
sp.SpecType = string(SBOMSpecCDX)

if c.doc.SerialNumber != "" && strings.HasPrefix(sp.Namespace, "urn:uuid:") {
if c.doc.SerialNumber != "" && strings.HasPrefix(sp.UniqID, "urn:uuid:") {
sp.uri = fmt.Sprintf("%s/%d", c.doc.SerialNumber, c.doc.Version)
}

c.spec = sp
}

func (c *cdxDoc) parseSignature() {
if c.doc.Declarations == nil {
fmt.Println("Declaratic.doc.Declarationsons field is nil ")
return
}

if c.doc.Declarations.Signature != nil {
fmt.Println("c.doc.Declarations.Signature field is nil ")
return
}

s := signature{}
s.keyID = c.doc.Declarations.Signature.KeyID
s.algorithm = c.doc.Declarations.Signature.Algorithm
s.value = c.doc.Declarations.Affirmation.Signature.Value
s.publicKey = c.doc.Declarations.Affirmation.Signature.PublicKey.CRV
c.signature = append(c.signature, s)

for _, ss := range lo.FromPtr(c.doc.Declarations.Affirmation.Signature.Signers) {
sig := signature{}
sig.keyID = ss.KeyID
sig.algorithm = ss.Algorithm
sig.value = ss.Value
sig.publicKey = ss.PublicKey.CRV
c.signature = append(c.signature, sig)
}

for _, sc := range lo.FromPtr(c.doc.Declarations.Affirmation.Signature.Chain) {
sig := signature{}
sig.keyID = sc.KeyID
sig.algorithm = sc.Algorithm
sig.value = sc.Value
sig.publicKey = sc.PublicKey.CRV
c.signature = append(c.signature, sig)
}
}

func (c *cdxDoc) requiredFields() bool {
if c.doc == nil {
c.addToLogs("cdx doc is not parsable")
Expand Down
2 changes: 2 additions & 0 deletions pkg/sbom/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,6 @@ type Document interface {
Lifecycles() []string
Manufacturer() Manufacturer
Supplier() GetSupplier

Signature() []GetSignature
}
Loading