Help us shape the future of Go! Take the 2026 Go Developer Survey

database

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package database stores the SSLKnife inventory in an encrypted SQLite database (see docs/DESIGN.md §5 for the construction).

Index

Constants

This section is empty.

Variables

View Source
var ErrAmbiguous = errors.New("ambiguous identifier")

ErrAmbiguous is returned when an ID prefix matches several objects.

View Source
var ErrIntegrity = errors.New("database integrity check failed: file is corrupted, tampered with, or encrypted with a different key")

ErrIntegrity means a page failed to decrypt or verify: the file was modified outside SQLite, or it belongs to a different key.

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is returned when a looked-up object does not exist.

Functions

func CAKey

func CAKey(dn string) string

CAKey identifies the CA behind an issuer DN. CAs rotate intermediates (Let's Encrypt R10, R11, E5, ...), so the organisation is used when the DN has one; otherwise the normalised DN.

func EscapeLike

func EscapeLike(s string) string

EscapeLike escapes LIKE wildcards for use with ESCAPE '\'.

func Exists

func Exists(path string) bool

Exists reports whether a database file exists at path.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is ErrNotFound.

func KeyFilePath

func KeyFilePath(dbPath string) string

KeyFilePath returns the keyslot file path for a database path.

func NameSetKey

func NameSetKey(names []string) string

NameSetKey is an order-independent key for a set of DNS names.

func NormalizeDN

func NormalizeDN(dn string) string

NormalizeDN makes DNs from different sources comparable ("C=US, O=X" vs "O=X,C=US").

func NormalizeSerial

func NormalizeSerial(s string) string

NormalizeSerial strips separators and leading zeros from a hex serial.

func NormalizeTag

func NormalizeTag(tag string) (string, error)

NormalizeTag lower-cases a tag and checks its syntax.

Types

type CTObservation

type CTObservation struct {
	ID           string
	WatchID      string
	Provider     string
	ExternalID   string
	Identity     string
	CertSHA256   string
	PubkeySHA256 string
	Serial       string
	Issuer       string
	IssuerName   string
	DNSNames     []string
	NotBefore    time.Time
	NotAfter     time.Time
	Revoked      *bool
	Status       string
	Reason       string
	KnownCertID  string
	Acknowledged bool
	FirstSeen    time.Time
}

CTObservation is one issuance seen for a watch.

type CTObservationFilter

type CTObservationFilter struct {
	WatchIDs []string
	Status   string
	Since    time.Time
	Limit    int
}

CTObservationFilter narrows CTObservations.

type CTWatch

type CTWatch struct {
	ID                string
	Domain            string
	IncludeSubdomains bool
	Source            string
	CreatedAt         time.Time
	LastCheckedAt     time.Time
	Cursor            string
}

CTWatch is a domain monitored in Certificate Transparency.

func (CTWatch) Pattern

func (w CTWatch) Pattern() string

Pattern renders the watch as the user wrote it.

type CertIndex

type CertIndex struct {
	BySHA256 map[string]string // cert sha256 -> cert id
	BySPKI   map[string]string // spki sha256 -> cert id (or key id)
	BySerial map[string]string // normalised serial -> cert id
	Issuers  map[string]bool   // CAKey of issuers of stored certificates
	NameSets map[string]string // sorted SAN set -> cert id
	SANs     []string          // all stored DNS SANs
}

CertIndex holds inventory facts used to classify CT observations.

type Certificate

type Certificate struct {
	ID                 string
	Name               string
	SHA256             string
	SHA1               string
	SPKISHA256         string
	Serial             string
	Subject            string
	SubjectCN          string
	Issuer             string
	IssuerCN           string
	NotBefore          time.Time
	NotAfter           time.Time
	KeyAlgorithm       string
	KeyBits            int
	KeyDescription     string
	SignatureAlgorithm string
	IsCA               bool
	SelfSigned         bool
	SubjectKeyID       string
	AuthorityKeyID     string
	DER                []byte
	Source             string
	Comment            string
	IssuerID           string
	KeyID              string
	CTMonitored        bool
	ImportedAt         time.Time

	SANs []SAN
	Tags []string
}

Certificate is a stored certificate row with its SANs and tags.

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB is an open, unlocked inventory database.

func Create

func Create(ctx context.Context, path string, root []byte) (*DB, error)

Create initialises a new, empty encrypted database. It fails if the file already exists.

func Open

func Open(ctx context.Context, path string, root []byte) (*DB, error)

Open opens an existing database with the vault root key and applies any pending migrations.

func (*DB) AcknowledgeCTObservation

func (db *DB) AcknowledgeCTObservation(ctx context.Context, ref string) (string, error)

AcknowledgeCTObservation marks an observation as expected.

func (*DB) AddCTWatch

func (db *DB) AddCTWatch(ctx context.Context, domain string, subdomains bool, source string) (*CTWatch, bool, error)

AddCTWatch creates a watch, returning the existing one if present.

func (*DB) AddNote

func (db *DB) AddNote(ctx context.Context, objType, id, body string) (*Note, error)

AddNote attaches a note to an object.

func (*DB) AddTags

func (db *DB) AddTags(ctx context.Context, objType, id string, tags []string) error

AddTags adds tags to an object.

func (*DB) AllTags

func (db *DB) AllTags(ctx context.Context) (map[string]int, error)

AllTags returns every tag in use with its object count.

func (*DB) AttachPrivate

func (db *DB) AttachPrivate(ctx context.Context, tx *sql.Tx, keyID string, private []byte) error

AttachPrivate adds private material to an existing public-only key.

func (*DB) AttachSSHPrivate

func (db *DB) AttachSSHPrivate(ctx context.Context, id string, private []byte, passphraseProtected bool) error

AttachSSHPrivate stores private key file bytes for a public-only SSH key.

func (*DB) CTCertIndex

func (db *DB) CTCertIndex(ctx context.Context) (*CertIndex, error)

CTCertIndex builds the classification index from stored certificates and keys.

func (*DB) CTObservations

func (db *DB) CTObservations(ctx context.Context, f CTObservationFilter) ([]CTObservation, error)

CTObservations lists observations, newest first.

func (*DB) CTWatches

func (db *DB) CTWatches(ctx context.Context) ([]CTWatch, error)

CTWatches lists all watches.

func (*DB) CTWatchesFor

func (db *DB) CTWatchesFor(ctx context.Context, domain string) ([]CTWatch, error)

CTWatchesFor returns watches for a domain (both exact and subdomain).

func (*DB) CertificateBySHA256

func (db *DB) CertificateBySHA256(ctx context.Context, sha string) (*Certificate, error)

CertificateBySHA256 returns the certificate with the exact fingerprint, or ErrNotFound.

func (*DB) Close

func (db *DB) Close() error

Close closes the database and forgets the secret key.

func (*DB) CountCTObservations

func (db *DB) CountCTObservations(ctx context.Context, status string, since time.Time) (int, error)

CountCTObservations counts observations by status (all when empty).

func (*DB) CountCertificates

func (db *DB) CountCertificates(ctx context.Context) (int, error)

CountCertificates returns the number of stored certificates.

func (*DB) CountEndpoints

func (db *DB) CountEndpoints(ctx context.Context) (int, error)

CountEndpoints returns the number of known endpoints.

func (*DB) DeleteCTWatch

func (db *DB) DeleteCTWatch(ctx context.Context, id string) error

DeleteCTWatch removes a watch and its observations.

func (*DB) DeleteCertificate

func (db *DB) DeleteCertificate(ctx context.Context, id string) error

DeleteCertificate removes a certificate, its SANs, tags and notes.

func (*DB) DeleteKey

func (db *DB) DeleteKey(ctx context.Context, id string) error

DeleteKey removes a key and its sealed private material. Certificates that referenced the key keep existing with the link cleared.

func (*DB) DeleteSSHKey

func (db *DB) DeleteSSHKey(ctx context.Context, id string) error

DeleteSSHKey removes a key and its sealed private material.

func (*DB) Endpoints

func (db *DB) Endpoints(ctx context.Context) ([]Endpoint, error)

Endpoints lists known endpoints, most recently seen first.

func (*DB) FindEndpoints

func (db *DB) FindEndpoints(ctx context.Context, host string, port int) ([]Endpoint, error)

FindEndpoints returns endpoints for host (and port when non-zero).

func (*DB) ForgetRemote

func (db *DB) ForgetRemote(ctx context.Context, remote string) error

ForgetRemote removes all sync state for remote, so the next sync merges both sides as if they had never met.

func (*DB) GetCertificate

func (db *DB) GetCertificate(ctx context.Context, ref string) (*Certificate, error)

GetCertificate loads one certificate by reference.

func (*DB) GetKey

func (db *DB) GetKey(ctx context.Context, ref string) (*Key, error)

GetKey loads one key by reference.

func (*DB) GetSSHKey

func (db *DB) GetSSHKey(ctx context.Context, ref string) (*SSHKey, error)

GetSSHKey loads a key by ID, name, ID prefix or fingerprint.

func (*DB) GetScan

func (db *DB) GetScan(ctx context.Context, ref string) (*Scan, error)

GetScan loads one observation by ID or ID prefix.

func (*DB) GetSecret

func (db *DB) GetSecret(ctx context.Context, id string) ([]byte, error)

GetSecret loads and authenticates a secret. The caller should Zero it.

func (*DB) GetSetting

func (db *DB) GetSetting(ctx context.Context, key string) ([]byte, error)

GetSetting returns a setting value, decrypting it when it was stored as a secret. ErrNotFound when absent.

func (*DB) InsertCTObservation

func (db *DB) InsertCTObservation(ctx context.Context, o *CTObservation) (bool, error)

InsertCTObservation stores o unless an observation with the same identity exists for the watch. It reports whether a row was added.

func (*DB) InsertCertificate

func (db *DB) InsertCertificate(ctx context.Context, tx *sql.Tx, c *Certificate) error

InsertCertificate stores c and its SANs. c.ID must be set.

func (*DB) InsertKey

func (db *DB) InsertKey(ctx context.Context, tx *sql.Tx, k *Key, private []byte) error

InsertKey stores k. When private is non-nil it is sealed into the secrets table first and linked.

func (*DB) KeyBySPKI

func (db *DB) KeyBySPKI(ctx context.Context, spki string) (*Key, error)

KeyBySPKI returns the key with the given SPKI fingerprint, or ErrNotFound.

func (*DB) LinkCertificate

func (db *DB) LinkCertificate(ctx context.Context, tx *sql.Tx, id, issuerID, keyID string) error

LinkCertificate sets the issuer and/or key links. Empty values leave the column unchanged.

func (*DB) MarkCTMonitored

func (db *DB) MarkCTMonitored(ctx context.Context) error

MarkCTMonitored flags certificates whose DNS names are watched.

func (*DB) Notes

func (db *DB) Notes(ctx context.Context, objType, id string) ([]Note, error)

Notes lists notes for an object, oldest first.

func (*DB) Path

func (db *DB) Path() string

Path returns the database file path.

func (*DB) PrivateKeyDER

func (db *DB) PrivateKeyDER(ctx context.Context, k *Key) ([]byte, error)

PrivateKeyDER returns the decrypted private key (PKCS#8 DER). The caller must Zero the result when done.

func (*DB) PutNote

func (db *DB) PutNote(ctx context.Context, objType, id string, n Note) error

PutNote stores a note with a known ID (from another device). An existing note with the same ID is left unchanged.

func (*DB) PutSecret

func (db *DB) PutSecret(ctx context.Context, tx *sql.Tx, plaintext []byte) (string, error)

PutSecret seals plaintext with AES-256-GCM and stores it, returning its ID.

func (*DB) QueryCertificates

func (db *DB) QueryCertificates(ctx context.Context, where string, args []any, order string) ([]*Certificate, error)

QueryCertificates returns certificates matching a WHERE clause over alias "c". where must be built from constants with args bound as parameters. order defaults to expiry.

func (*DB) QueryKeys

func (db *DB) QueryKeys(ctx context.Context, where string, args []any) ([]*Key, error)

QueryKeys returns keys matching where (alias "k").

func (*DB) QuerySSHKeys

func (db *DB) QuerySSHKeys(ctx context.Context, where string, args []any) ([]*SSHKey, error)

QuerySSHKeys returns keys matching where (alias "s").

func (*DB) RecentCertificates

func (db *DB) RecentCertificates(ctx context.Context, limit int) ([]*Certificate, error)

RecentCertificates returns the most recently imported certificates.

func (*DB) RecentScans

func (db *DB) RecentScans(ctx context.Context, limit int, withResult bool) ([]RecentScan, error)

RecentScans returns the newest observations across endpoints.

func (*DB) RecordScan

func (db *DB) RecordScan(ctx context.Context, ep Endpoint, s *Scan) error

RecordScan upserts the endpoint and stores the observation.

func (*DB) RemoveTags

func (db *DB) RemoveTags(ctx context.Context, objType, id string, tags []string) error

RemoveTags removes tags from an object.

func (*DB) ReplaceSyncStates

func (db *DB) ReplaceSyncStates(ctx context.Context, remote string, states map[SyncKey]string) error

ReplaceSyncStates atomically replaces the sync state for remote. Keys with an empty digest are dropped.

func (*DB) ResolveCertificate

func (db *DB) ResolveCertificate(ctx context.Context, ref string) (string, error)

ResolveCertificate turns an ID, name, ID prefix or fingerprint prefix into an ID.

func (*DB) ResolveKey

func (db *DB) ResolveKey(ctx context.Context, ref string) (string, error)

ResolveKey turns an ID, name or ID prefix into an ID.

func (*DB) SQL

func (db *DB) SQL() *sql.DB

SQL exposes the underlying handle for packages in this module that add their own tables (later phases).

func (*DB) SSHPrivateKey

func (db *DB) SSHPrivateKey(ctx context.Context, k *SSHKey) ([]byte, error)

SSHPrivateKey returns the stored private key file bytes. Zero them after use.

func (*DB) Scans

func (db *DB) Scans(ctx context.Context, endpointID string, limit int, withResult bool) ([]Scan, error)

Scans lists observations of an endpoint, newest first. withResult loads the full JSON.

func (*DB) SchemaVersion

func (db *DB) SchemaVersion(ctx context.Context) (int, error)

SchemaVersion returns the highest applied migration.

func (*DB) SetSetting

func (db *DB) SetSetting(ctx context.Context, key string, value []byte, secret bool) error

SetSetting stores a value; secret values are sealed in the secrets table.

func (*DB) SyncStates

func (db *DB) SyncStates(ctx context.Context, remote string) (map[SyncKey]string, error)

SyncStates returns the last agreed digest of every object synced with remote.

func (*DB) TotalChanges

func (db *DB) TotalChanges(ctx context.Context) (int64, error)

TotalChanges returns the number of rows changed through this handle since it was opened. The CLI compares it before and after a command to decide whether there is anything to push.

func (*DB) Tx

func (db *DB) Tx(ctx context.Context, fn func(tx *sql.Tx) error) error

Tx runs fn in a write transaction.

func (*DB) UpdateCTWatchCheck

func (db *DB) UpdateCTWatchCheck(ctx context.Context, id, cursor string, at time.Time) error

UpdateCTWatchCheck records a completed poll.

func (*DB) UpdateCertificateMeta

func (db *DB) UpdateCertificateMeta(ctx context.Context, id string, name, comment *string) error

UpdateCertificateMeta changes the friendly name and/or comment. nil leaves a field unchanged.

func (*DB) UpdateKeyMeta

func (db *DB) UpdateKeyMeta(ctx context.Context, id string, name, comment *string) error

UpdateKeyMeta changes the friendly name and/or comment.

func (*DB) UpdateSSHKeyMeta

func (db *DB) UpdateSSHKeyMeta(ctx context.Context, id string, name, comment *string) error

UpdateSSHKeyMeta changes an SSH key's name and/or comment. nil leaves a field unchanged.

func (*DB) UpdateSSHKeyName

func (db *DB) UpdateSSHKeyName(ctx context.Context, id, name string) error

UpdateSSHKeyName renames a key.

func (*DB) UpsertSSHKey

func (db *DB) UpsertSSHKey(ctx context.Context, k *SSHKey, private []byte) (*SSHKey, bool, error)

UpsertSSHKey stores k; when a key with the same fingerprint exists it attaches private material if newly available. It returns the stored row and whether it was created.

type Endpoint

type Endpoint struct {
	ID        string
	Host      string
	Port      int
	SNI       string
	Protocol  string
	FirstSeen time.Time
	LastSeen  time.Time
}

Endpoint is a remote TLS service that has been inspected or scanned.

type Key

type Key struct {
	ID          string
	Name        string
	Algorithm   string
	Bits        int
	Description string
	SPKISHA256  string
	PublicDER   []byte
	SecretID    string
	Source      string
	Comment     string
	ImportedAt  time.Time

	Tags []string
}

Key is a stored key. Private key material lives in the secrets table and is only reachable through PrivateKeyDER.

func (*Key) HasPrivate

func (k *Key) HasPrivate() bool

HasPrivate reports whether private material is stored.

type Note

type Note struct {
	ID        string
	Body      string
	CreatedAt time.Time
}

Note is a free-text note attached to an object.

type RecentScan

type RecentScan struct {
	Scan
	Host string
	Port int
}

RecentScan is a stored observation with its endpoint.

type SAN

type SAN struct {
	Type  string // dns, ip, email, uri
	Value string
}

SAN is one subject alternative name.

type SSHKey

type SSHKey struct {
	ID                  string
	Name                string
	Type                string
	Bits                int
	FingerprintSHA256   string
	PublicKey           string
	Comment             string
	PassphraseProtected bool
	SecretID            string
	Source              string
	ImportedAt          time.Time
	Tags                []string
}

SSHKey is a stored SSH key.

func (*SSHKey) HasPrivate

func (k *SSHKey) HasPrivate() bool

HasPrivate reports whether the private key is stored.

type Scan

type Scan struct {
	ID         string
	EndpointID string
	Kind       string
	ScannedAt  time.Time
	LeafSHA256 string
	Snapshot   []byte
	Result     []byte
}

Scan is one stored observation of an endpoint.

type SyncKey

type SyncKey struct {
	Kind  string // cert, key, ssh
	Ident string
}

SyncKey identifies an object in remote sync state.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL