From 4188056a716add27a5d44b045e28c14ffa933eb0 Mon Sep 17 00:00:00 2001 From: Paul Duncan Date: Thu, 17 Feb 2022 23:24:27 -0500 Subject: dbstore/dbstore.go: add AddCpeMatches() --- dbstore/dbstore.go | 100 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) (limited to 'dbstore') diff --git a/dbstore/dbstore.go b/dbstore/dbstore.go index f432054..acaad7c 100644 --- a/dbstore/dbstore.go +++ b/dbstore/dbstore.go @@ -229,3 +229,103 @@ func (me DbStore) CpeSearch( // return success return r, nil } + +// query IDs used by AddCpeMatches() +var addCpeMatchesQueryIds = []string { + "cpe-match-insert", + "cpe-match-insert-vulnerability", + "cpe-match-insert-version-min", + "cpe-match-insert-version-max", + "cpe-match-insert-cpe", +} + +// import CPE matches +func (me DbStore) AddCpeMatches(ctx context.Context, matches cpematch.Matches) error { + // lazy-init db + if err := me.Init(ctx); err != nil { + return err + } + + // build query map + queries, err := getQueries(addCpeMatchesQueryIds) + if err != nil { + return err + } + + // begin context + tx, err := me.db.BeginTx(ctx, nil) + if err != nil { + return err + } + + // build statements + sts := make(map[string]*db_sql.Stmt) + for id, sql := range(queries) { + if st, err := tx.PrepareContext(ctx, sql); err != nil { + return err + } else { + sts[id] = st + defer sts[id].Close() + } + } + + // add matches + for _, m := range(matches.Matches) { + // add cpe + rs, err := sts["cpe-match/insert"].ExecContext(ctx, m.Cpe23Uri, m.Cpe22Uri) + if err != nil { + return err + } + + // get last row ID + id, err := rs.LastInsertId() + if err != nil { + return err + } + + // add vulnerable + if m.Vulnerable != nil { + _, err := sts["cpe-match/insert-vulnerable"].ExecContext(ctx, id, *m.Vulnerable) + if err != nil { + return err + } + } + + // add version minimum + if m.VersionStartIncluding != "" { + _, err := sts["cpe-match/insert-versiom-min"].ExecContext(ctx, id, true, m.VersionStartIncluding) + if err != nil { + return err + } + } else if m.VersionStartExcluding != "" { + _, err := sts["cpe-match/insert-versiom-min"].ExecContext(ctx, id, false, m.VersionStartExcluding) + if err != nil { + return err + } + } + + // add version maximum + if m.VersionEndIncluding != "" { + _, err := sts["cpe-match/insert-versiom-max"].ExecContext(ctx, id, true, m.VersionEndIncluding) + if err != nil { + return err + } + } else if m.VersionEndExcluding != "" { + _, err := sts["cpe-match/insert-versiom-max"].ExecContext(ctx, id, false, m.VersionEndExcluding) + if err != nil { + return err + } + } + + // add names + for _, name := range(m.Names) { + _, err := sts["cpe-match/insert-name"].ExecContext(ctx, id, name.Cpe23Uri, name.Cpe22Uri) + if err != nil { + return err + } + } + } + + // commit changes, return result + return tx.Commit() +} -- cgit v1.2.3