Documentation
¶
Overview ¶
Package rpm reads, verifies and signs RPM packages. It handles both the classic format 4 and the format 6 written by rpm 6.0, and is written in pure Go; cgo, when enabled, only switches zstd decompression to the C library.
Reading ¶
ReadRpm parses the lead and the headers of a package and gives access to the tags (see the tag package for their numbers), the files, and the payload:
pkg, err := rpm.ReadRpm(f)
if err != nil { ... }
nevra, err := pkg.Header.GetNEVRA()
provides, err := pkg.Header.GetStrings(tag.PROVIDENAME)
pkg.SetMaxPayloadSize(1 << 30) // bound the expansion of untrusted input
err = pkg.ExpandPayload(dir)
The payload of a package can also be read sequentially with Rpm.PayloadReader and Rpm.PayloadReaderExtended, which handle hard links and the stripped cpio archives of format 6. Package github.com/M0Rf30/pkgformat/rpm/cpio has the archive reader and the extraction.
ExpandPayload applies the modes (including set-uid, set-gid and sticky bits) and modification times of the package and verifies every regular file against the digest in the header; ExpandPayloadWithOptions masks the modes, applies owners, creates device nodes and FIFOs, or skips the digests on request.
ReadPackage returns the metadata of a package as a plain struct: identity, sizes, the dependency lists (requires, provides, conflicts, obsoletes and the weak dependencies, with their sense flags), the file list and the changelog. It reads the headers only, with explicit limits (PackageLimits), and is what the writers of repository metadata in package repodata consume.
Verifying ¶
Verify checks the digests of a stream and the OpenPGP signatures of the header and payload against a keyring. It returns the signatures it found. A package that carries no signature at all is not an error: Verify returns an empty list, so callers that require a signature use VerifyWithOptions with RequireSigned, or check len(sigs).
A signature is accepted only if its key is not revoked, not expired and allowed to sign, and the signature is not expired; the failure is a *SignatureError wrapping the matching error of package github.com/M0Rf30/pkgformat/gpg. VerifyOptions.Now sets the time those checks are made at.
Signing ¶
SignRpmStream computes the signatures of a package and returns the header that DumpSignatureHeader turns into the new lead and signature header, which replace the first OriginalSignatureHeaderSize bytes of the package. SignRpmFile does the same on a file. The header and payload are not touched.
Versions ¶
Vercmp compares versions the way rpm does, and NEVRA holds the name, epoch, version, release and architecture of a package.
Untrusted input ¶
Headers are parsed with limits on the number of tags and on their size, and payload extraction is confined to the destination directory. Decompression is bounded by DefaultMaxPayloadSize unless the header declares a larger payload; set a policy-specific bound with Rpm.SetMaxPayloadSize for untrusted input, and Rpm.SetVerifyPayloadDigest to check the payload against the digest of the (signed) header.
Packages are written by the pack package; repositories are written and read by the repodata package and used by the dnf package.
Example (RoundTrip) ¶
A package written with the pack package can be read back with this one.
package main
import (
"bytes"
"fmt"
"log"
"github.com/M0Rf30/pkgformat/rpm"
"github.com/M0Rf30/pkgformat/rpm/pack"
"github.com/M0Rf30/pkgformat/rpm/tag"
)
func main() {
w, err := pack.NewRPM(pack.RPMMetaData{Name: "example", Version: "3", Release: "1", Format: pack.FormatV6})
if err != nil {
log.Fatal(err)
}
w.AddFile(pack.RPMFile{Name: "/usr/share/example/hello", Body: []byte("hello"), Mode: 0o644, Owner: "root", Group: "root"})
var buf bytes.Buffer
if err := w.Write(&buf); err != nil {
log.Fatal(err)
}
pkg, err := rpm.ReadRpm(&buf)
if err != nil {
log.Fatal(err)
}
files, err := pkg.Header.GetStrings(tag.BASENAMES)
if err != nil {
log.Fatal(err)
}
fmt.Println("format", pkg.Header.Format(), files)
}
Output: format 6 [hello]
Index ¶
- Constants
- Variables
- func DigestAlgorithmName(algo uint32) string
- func FSVerityDigest(r io.Reader, algo uint32) ([]byte, error)
- func GetFileAlgoName(algo int) string
- func IsRichName(name string) bool
- func NEVRAcmp(a NEVRA, b NEVRA) int
- func SenseFlagsString[T ~uint32](flags T) string
- func Sign(src io.ReadSeeker, dst io.Writer, signer gpg.Signer) error
- func SplitVersionRelease(v string) (version, release string)
- func Vercmp(first, second string) int
- func Verify(stream io.Reader, knownKeys openpgp.EntityList) (header *RpmHeader, sigs []*Signature, err error)
- func VerifyIMASignature(sig, digest []byte, pub crypto.PublicKey) error
- func VerifyVeritySignature(sig, digest []byte, algo uint32, trusted []*x509.Certificate) error
- func VerifyWithKeyring(stream io.Reader, keyring *gpg.Keyring, opts *VerifyOptions) (*RpmHeader, []*Signature, error)
- func VerifyWithOptions(stream io.Reader, knownKeys openpgp.EntityList, opts *VerifyOptions) (header *RpmHeader, sigs []*Signature, err error)
- type ChangelogEntry
- type Dependency
- func (d Dependency) IsConfig() bool
- func (d Dependency) IsInterp() bool
- func (d Dependency) IsKeyring() bool
- func (d Dependency) IsMissingOK() bool
- func (d Dependency) IsPost() bool
- func (d Dependency) IsPosttrans() bool
- func (d Dependency) IsPostun() bool
- func (d Dependency) IsPre() bool
- func (d Dependency) IsPrereq() bool
- func (d Dependency) IsPretrans() bool
- func (d Dependency) IsPreun() bool
- func (d Dependency) IsRPMLib() bool
- func (d Dependency) IsRich() bool
- func (d Dependency) IsScriptVerify() bool
- func (d Dependency) IsUntrans() bool
- func (d Dependency) Versioned() bool
- type DigestMismatchError
- type ExpandOptions
- type FileDependency
- type FileEntry
- type FileInfo
- type FileTrigger
- type HeaderLimits
- type HeaderRange
- type IMASignature
- type KeyHolder
- type KeyNotFoundError
- type Lead
- type NEVRA
- type NEVRASlice
- type NamedScript
- type NoSuchTagError
- type Package
- type PackageLimits
- type PayloadDigest
- type PayloadReader
- type Policy
- type Rpm
- func (rpm *Rpm) ExpandPayload(dest string) error
- func (rpm *Rpm) ExpandPayloadWithOptions(dest string, opts *ExpandOptions) error
- func (rpm *Rpm) PayloadReader() (*cpio.Reader, error)
- func (rpm *Rpm) PayloadReaderExtended() (PayloadReader, error)
- func (rpm *Rpm) SetMaxPayloadSize(limit int64)
- func (rpm *Rpm) SetVerifyPayloadDigest(verify bool)
- type RpmHeader
- func ReadHeader(f io.Reader) (*RpmHeader, error)
- func ReadHeaderBlob(blob []byte, lim HeaderLimits) (*RpmHeader, error)
- func ReadHeaderLimits(f io.Reader, lim HeaderLimits) (*RpmHeader, error)
- func RewriteWithSignatures(infile *os.File, outpath string, sigPgp, sigRsa []byte) (*RpmHeader, error)
- func SignRpmFile(infile *os.File, outpath string, key *packet.PrivateKey, ...) (header *RpmHeader, err error)
- func SignRpmStream(stream io.Reader, key *packet.PrivateKey, opts *SignatureOptions) (header *RpmHeader, err error)
- func (hdr *RpmHeader) Dependencies(nameTag, flagsTag, versionTag int) ([]Dependency, error)
- func (hdr *RpmHeader) DumpSignatureHeader(sameSize bool) ([]byte, error)
- func (hdr *RpmHeader) Format() int
- func (hdr *RpmHeader) Get(id int) (interface{}, error)
- func (hdr *RpmHeader) GetBytes(id int) ([]byte, error)
- func (hdr *RpmHeader) GetFiles() ([]FileInfo, error)
- func (hdr *RpmHeader) GetInt(id int) (int, error)
- func (hdr *RpmHeader) GetInts(id int) ([]int, error)
- func (hdr *RpmHeader) GetNEVRA() (*NEVRA, error)
- func (hdr *RpmHeader) GetRange() HeaderRange
- func (hdr *RpmHeader) GetString(id int) (string, error)
- func (hdr *RpmHeader) GetStrings(id int) ([]string, error)
- func (hdr *RpmHeader) GetUint32(id int) (uint32, error)
- func (hdr *RpmHeader) GetUint32s(id int) ([]uint32, error)
- func (hdr *RpmHeader) GetUint64(id int) (uint64, error)
- func (hdr *RpmHeader) GetUint64Fallback(intTag, longTag int) (uint64, error)
- func (hdr *RpmHeader) GetUint64s(id int) ([]uint64, error)
- func (hdr *RpmHeader) HasTag(id int) bool
- func (hdr *RpmHeader) InstalledPackage(lim PackageLimits) (*Package, error)
- func (hdr *RpmHeader) InstalledSize() (int64, error)
- func (hdr *RpmHeader) IsSource() bool
- func (hdr *RpmHeader) Lead() *Lead
- func (hdr *RpmHeader) OriginalSignatureHeaderSize() int
- func (hdr *RpmHeader) Package(lim PackageLimits) (*Package, error)
- func (hdr *RpmHeader) PayloadSize() (int64, error)
- type ScriptFlags
- type Scriptlet
- type Scripts
- type Sense
- func (s Sense) Comparison() Sense
- func (s Sense) Has(mask Sense) bool
- func (s Sense) IsConfig() bool
- func (s Sense) IsInterp() bool
- func (s Sense) IsKeyring() bool
- func (s Sense) IsMissingOK() bool
- func (s Sense) IsPost() bool
- func (s Sense) IsPosttrans() bool
- func (s Sense) IsPostun() bool
- func (s Sense) IsPre() bool
- func (s Sense) IsPrereq() bool
- func (s Sense) IsPretrans() bool
- func (s Sense) IsPreun() bool
- func (s Sense) IsRPMLib() bool
- func (s Sense) IsRich() bool
- func (s Sense) IsScriptVerify() bool
- func (s Sense) IsUntrans() bool
- func (s Sense) Operator() string
- func (s Sense) Roles() []string
- func (s Sense) String() string
- func (s Sense) Versioned() bool
- type Signature
- type SignatureError
- type SignatureOptions
- type SourceFile
- type Trigger
- type TriggerKind
- type VerifyOptions
- type VersionSlice
Examples ¶
Constants ¶
const ( VeritySHA256 = 1 VeritySHA512 = 2 )
fs-verity hash algorithm numbers (VERITYSIGNATUREALGO, FS_VERITY_HASH_ALG_*).
const ( PGPHASHALGO_MD5 = 1 // MD5 PGPHASHALGO_SHA1 = 2 // SHA1 PGPHASHALGO_RIPEMD160 = 3 // RIPEMD160 PGPHASHALGO_MD2 = 5 // MD2 PGPHASHALGO_TIGER192 = 6 // TIGER192 PGPHASHALGO_HAVAL_5_160 = 7 // HAVAL-5-160 PGPHASHALGO_SHA256 = 8 // SHA256 PGPHASHALGO_SHA384 = 9 // SHA384 PGPHASHALGO_SHA512 = 10 // SHA512 PGPHASHALGO_SHA224 = 11 // SHA224 )
PGP Hash Algorithms
const ( // MaxHeaderEntries is the maximum number of index entries in a header. MaxHeaderEntries = 0xffff // MaxHeaderDataSize is the maximum size of the data store of a header, // the default of [ReadHeader] and [ReadRpm]. MaxHeaderDataSize = 0x0fffffff )
Limits applied while parsing a header from untrusted input. They match (or are tighter than) the sanity limits that rpm itself enforces.
const ( // LeadMagic is the magic number at the start of every RPM. LeadMagic uint32 = 0xEDABEEDB // LeadSize is the size in bytes of the lead, the fixed block in front of // the signature header. LeadSize = 96 )
const ( // MaxPackageHeaderDataSize is the default bound on the data store of the // headers of [ReadPackage]. MaxPackageHeaderDataSize = 1 << 24 // MaxArrayEntries is the default bound on the entries kept of one array // of a package: a dependency list, the file list, the changelog. MaxArrayEntries = 100_000 // MaxFileListBytes is the default bound on the total size of the strings // (path, digest, link target) kept for the file list of a package. Every // path is dirname+basename and all entries may reference the same // multi-megabyte dirname, so the entry count alone does not bound the // expanded size. MaxFileListBytes = 16 << 20 )
const DefaultMaxPayloadSize = 4 << 30
DefaultMaxPayloadSize bounds the decompressed payload of a package that declares no payload size.
const LuaInterpreter = "<lua>"
LuaInterpreter is the interpreter of a scriptlet that rpm runs in its embedded Lua (spec file option -p <lua>).
Variables ¶
var ( // ErrNotRPM means the input does not start with the lead of an RPM. ErrNotRPM = errors.New("rpm: not an rpm package") // ErrUnsupportedVersion means the lead announces a major version older than 3. ErrUnsupportedVersion = errors.New("rpm: unsupported package version") // ErrInvalidHeader means a header is malformed: bad magic, an entry that // points outside the data, a truncated string, a missing identity tag. ErrInvalidHeader = errors.New("rpm: invalid header") // ErrHeaderTooLarge means a header, or one of its arrays, exceeds the // limits set for the read. ErrHeaderTooLarge = errors.New("rpm: header too large") )
Errors returned for malformed or oversized packages. Match them with errors.Is: the returned errors wrap them with details.
var ( ErrNoPGPSignature = errors.New("no supported PGP signature packet found") ErrTrailingGarbage = errors.New("trailing garbage after PGP signature packet") // ErrUnsigned means the package carries no PGP signature and // VerifyOptions.RequireSigned was set. ErrUnsigned = errors.New("rpm: package is not signed") // ErrNoKnownKeys means VerifyOptions.RequireSigned was set without keys to // check the signatures against. ErrNoKnownKeys = errors.New("rpm: signatures are required but no known keys were given") )
var ErrBadV3Signature = errors.New("rpm: bad version 3 OpenPGP signature")
ErrBadV3Signature is returned for a version 3 signature packet that is malformed or does not match the signed data.
var ErrDigestMismatch = cpio.ErrDigestMismatch
ErrDigestMismatch is matched (errors.Is) by the error ExpandPayload returns when the contents of a file do not match the digest in the package header. The error is a *DigestMismatchError.
var ErrFileSignature = errors.New("rpm: bad file signature")
ErrFileSignature is returned when an IMA or fs-verity file signature is malformed or does not verify.
var ErrPayloadDigest = errors.New("rpm payload digest mismatch")
ErrPayloadDigest is returned at the end of the payload when its digest differs from the one the header records (see Rpm.SetVerifyPayloadDigest).
var ErrPayloadTooLarge = errors.New("rpm payload exceeds the configured size limit")
ErrPayloadTooLarge is returned when the decompressed payload is larger than the limit set with Rpm.SetMaxPayloadSize.
Functions ¶
func DigestAlgorithmName ¶ added in v0.4.0
DigestAlgorithmName returns the name of an OpenPGP/rpm digest algorithm number (the values of FILEDIGESTALGO and PAYLOADDIGESTALGO): "md5", "sha1", "sha256", "sha3-256" and so on, or "" for an unknown number.
func FSVerityDigest ¶ added in v0.4.0
FSVerityDigest computes the fs-verity file digest of the contents read from r (4 KiB blocks, no salt: what fsverity(1) and rpmsign use), with the fs-verity algorithm algo (VeritySHA256 or VeritySHA512).
func GetFileAlgoName ¶
GetFileAlgoName returns the name of a digest algorithm
func IsRichName ¶ added in v0.4.0
IsRichName reports whether a dependency name is a rich (boolean) dependency: rich dependencies are written in parentheses, "(a if b)".
func NEVRAcmp ¶
NEVRAcmp compares two RPM versions. It returns -1 if a < b, 1 if a > b, and 0 if a == b
func SenseFlagsString ¶
SenseFlagsString renders the comparison bits of flags as the flags attribute of repodata: "LT", "GT", "EQ", "LE" or "GE". An unversioned dependency yields "". It is Sense.String.
func Sign ¶
Sign writes a copy of the package in src to dst with the header-only (RSAHEADER) and header-plus-payload (PGP) signatures of signer, or the OpenPGP signature of a format 6 package, replacing any signature the package already had. src is read from the start and must be seekable.
Only the signature header is rewritten: the general header and the payload are copied byte for byte, so the result is a different file, with a different checksum, from the input.
A signer implementing KeyHolder (such as gpg.LocalSigner, including one made by gpg.NewCryptoSigner for an HSM or KMS key) signs with its key directly. Any other gpg.Signer (for example one that runs gpg-agent or a remote signing service) is asked for detached signatures of the general header through DetachedSign; the package then gets the header-only signature rpm 4.16 and later produce (RSAHEADER, or OPENPGP for format 6) and no header-plus-payload signature. The payload is still covered, through the payload digest of the signed header, which is checked before signing.
Example ¶
package main
import (
"bytes"
"fmt"
"log"
"os"
"github.com/ProtonMail/go-crypto/openpgp"
"github.com/M0Rf30/pkgformat/gpg"
"github.com/M0Rf30/pkgformat/rpm"
)
func main() {
entity, err := gpg.GenerateEntity("Example", "", "example@example.invalid", gpg.AlgorithmED25519)
if err != nil {
log.Fatal(err)
}
signer, err := gpg.NewLocalSignerFromEntity(entity)
if err != nil {
log.Fatal(err)
}
src, err := os.Open("testdata/hello.rpm")
if err != nil {
log.Fatal(err)
}
defer src.Close()
var signed bytes.Buffer
if err := rpm.Sign(src, &signed, signer); err != nil {
log.Fatal(err)
}
_, sigs, err := rpm.Verify(bytes.NewReader(signed.Bytes()), openpgp.EntityList{entity})
if err != nil {
log.Fatal(err)
}
fmt.Println(len(sigs) > 0)
}
Output: true
func SplitVersionRelease ¶
SplitVersionRelease splits a dependency version "ver[-rel]" at the last dash.
func Vercmp ¶
Vercmp compares two version strings the way rpm does (rpmvercmp in rpm 4.15 and later, including the tilde and caret operators). Returns -1 if first < second, 1 if first > second, and 0 if first == second.
The versions are split into runs of digits and runs of letters; anything else only separates them. A run of digits is compared as a number, and always sorts after a run of letters. A tilde sorts before everything, even the end of the version ("1.0~rc1" < "1.0"). A caret sorts after the end of the version but before any other character ("1.0" < "1.0^git1" < "1.0.1" and "1.0^git1" < "1.0a"). Letters are ASCII only; like in C, a version ends at the first NUL byte.
It runs in time linear in the length of the inputs, which may come from untrusted package headers.
func Verify ¶
func Verify(stream io.Reader, knownKeys openpgp.EntityList) (header *RpmHeader, sigs []*Signature, err error)
Verify the PGP signature over a RPM file. knownKeys should enumerate public keys to check against, otherwise the signature validity cannot be verified. If knownKeys is nil then digests will be checked but only the raw key ID will be available.
A signature is accepted only if it matches the data and its key may be relied on now: the key (primary key, subkey and primary user id) is not revoked, not expired and allowed to sign, and the signature itself is not expired. Otherwise Verify fails with a *SignatureError wrapping github.com/M0Rf30/pkgformat/gpg.ErrKeyRevoked, github.com/M0Rf30/pkgformat/gpg.ErrKeyExpired, github.com/M0Rf30/pkgformat/gpg.ErrSignatureExpired or github.com/M0Rf30/pkgformat/gpg.ErrKeyCannotSign.
A package without any signature is not an error: Verify returns an empty list of signatures. Use VerifyWithOptions with RequireSigned, or check the length of the list, when a signature is mandatory.
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/M0Rf30/pkgformat/rpm"
)
func main() {
f, err := os.Open("testdata/v6/ref-v6s.rpm")
if err != nil {
log.Fatal(err)
}
defer f.Close()
// A nil keyring checks digests and exposes the key IDs only.
_, sigs, err := rpm.Verify(f, nil)
if err != nil {
log.Fatal(err)
}
for _, sig := range sigs {
fmt.Printf("%016X header-only=%v\n", sig.KeyId, sig.HeaderOnly)
}
}
Output: 1E66303A75B7A873 header-only=true
func VerifyIMASignature ¶ added in v0.4.0
VerifyIMASignature checks an IMA signature (see ParseIMASignature for the accepted encodings) of a file whose contents hash to digest under the algorithm the signature names, which for an rpm package is the FILEDIGESTS entry of the file. pub is an *rsa.PublicKey or *ecdsa.PublicKey, typically the PublicKey of the x509.Certificate given to rpmsign --certpath.
func VerifyVeritySignature ¶ added in v0.4.0
func VerifyVeritySignature(sig, digest []byte, algo uint32, trusted []*x509.Certificate) error
VerifyVeritySignature checks an fs-verity signature of a file: sig is the FileEntry.VeritySignature of the package (or the raw PKCS #7 DER), digest the fs-verity digest of the file contents (FSVerityDigest) under algo (Package.VeritySignatureAlgorithm), and trusted the certificates the signature may come from (the --certpath given to rpmsign). The signature is a detached PKCS #7 SignedData over the fsverity_formatted_digest, as the kernel checks it.
func VerifyWithKeyring ¶ added in v0.4.0
func VerifyWithKeyring(stream io.Reader, keyring *gpg.Keyring, opts *VerifyOptions) (*RpmHeader, []*Signature, error)
VerifyWithKeyring is VerifyWithOptions with the keys of a gpg.Keyring, the keyring type the deb, pacman and repository verifiers of this module take. A nil keyring checks digests only, like a nil key list.
func VerifyWithOptions ¶ added in v0.3.1
func VerifyWithOptions(stream io.Reader, knownKeys openpgp.EntityList, opts *VerifyOptions) (header *RpmHeader, sigs []*Signature, err error)
VerifyWithOptions is Verify with options; a nil opts is the zero value.
Example ¶
package main
import (
"fmt"
"log"
"os"
"github.com/ProtonMail/go-crypto/openpgp"
"github.com/M0Rf30/pkgformat/rpm"
)
func main() {
f, err := os.Open("testdata/v6/ref-v6.rpm") // an unsigned package
if err != nil {
log.Fatal(err)
}
defer f.Close()
key, err := openpgp.NewEntity("example", "", "example@example.com", nil)
if err != nil {
log.Fatal(err)
}
_, _, err = rpm.VerifyWithOptions(f, openpgp.EntityList{key}, &rpm.VerifyOptions{RequireSigned: true})
fmt.Println(err)
}
Output: rpm: package is not signed
Types ¶
type ChangelogEntry ¶
type ChangelogEntry struct {
Time int64 `json:"time"`
Author string `json:"author"`
Description string `json:"description"`
}
ChangelogEntry is one entry of the changelog of a package.
type Dependency ¶
type Dependency struct {
Name string `json:"name"`
// Flags holds the sense bits, the tag.RPMSENSE_* values: the comparison
// and the roles of the dependency. The predicates below (IsPre, IsPost,
// IsRPMLib, ...) read them.
Flags Sense `json:"flags,omitempty"`
Version string `json:"version,omitempty"`
// Epoch is the epoch part of the version, when it is written "epoch:version".
Epoch uint32 `json:"epoch,omitempty"`
}
Dependency is one entry of a dependency list of a package: a provide, a requirement, a conflict, an obsolete or a weak dependency.
func (Dependency) IsConfig ¶ added in v0.4.0
func (d Dependency) IsConfig() bool
IsConfig reports the implicit config(name) dependency of a package that ships configuration files.
func (Dependency) IsInterp ¶ added in v0.4.0
func (d Dependency) IsInterp() bool
IsInterp reports the dependency on the interpreter of a scriptlet.
func (Dependency) IsKeyring ¶ added in v0.4.0
func (d Dependency) IsKeyring() bool
IsKeyring reports a requirement on a key of the rpm keyring.
func (Dependency) IsMissingOK ¶ added in v0.4.0
func (d Dependency) IsMissingOK() bool
IsMissingOK reports a dependency that need not be satisfied.
func (Dependency) IsPost ¶ added in v0.4.0
func (d Dependency) IsPost() bool
IsPost reports a Requires(post) dependency.
func (Dependency) IsPosttrans ¶ added in v0.4.0
func (d Dependency) IsPosttrans() bool
IsPosttrans reports a Requires(posttrans) dependency.
func (Dependency) IsPostun ¶ added in v0.4.0
func (d Dependency) IsPostun() bool
IsPostun reports a Requires(postun) dependency.
func (Dependency) IsPre ¶
func (d Dependency) IsPre() bool
IsPre reports whether the requirement is needed before the package is installed: Requires(pre), Requires(post) or a legacy PreReq; the pre attribute of repodata. See Sense.IsPre.
func (Dependency) IsPrereq ¶ added in v0.4.0
func (d Dependency) IsPrereq() bool
IsPrereq reports a legacy PreReq dependency.
func (Dependency) IsPretrans ¶ added in v0.4.0
func (d Dependency) IsPretrans() bool
IsPretrans reports a Requires(pretrans) dependency.
func (Dependency) IsPreun ¶ added in v0.4.0
func (d Dependency) IsPreun() bool
IsPreun reports a Requires(preun) dependency.
func (Dependency) IsRPMLib ¶
func (d Dependency) IsRPMLib() bool
IsRPMLib reports an rpmlib(...) feature requirement.
func (Dependency) IsRich ¶ added in v0.4.0
func (d Dependency) IsRich() bool
IsRich reports a rich (boolean) dependency such as "(a if b)". Packages do not store the rich marker of the sense flags, so it is recognised by the parenthesis that opens the name. Package richdep parses and evaluates them.
func (Dependency) IsScriptVerify ¶ added in v0.4.0
func (d Dependency) IsScriptVerify() bool
IsScriptVerify reports a Requires(verify) dependency.
func (Dependency) IsUntrans ¶ added in v0.4.0
func (d Dependency) IsUntrans() bool
IsUntrans reports a Requires(preuntrans) or Requires(postuntrans) dependency.
func (Dependency) Versioned ¶
func (d Dependency) Versioned() bool
Versioned reports whether the dependency carries a version comparison.
type DigestMismatchError ¶ added in v0.3.1
type DigestMismatchError = cpio.DigestMismatchError
DigestMismatchError describes the file whose contents do not match the digest in the package header.
type ExpandOptions ¶ added in v0.3.1
type ExpandOptions struct {
// Umask clears the given bits of every file and directory mode, as a
// unix mask over the permission bits (0777) and the special bits: 07000
// drops set-uid, set-gid and sticky. The default applies the modes of
// the package unchanged, as rpm does.
Umask uint32
// Chown applies the file owners (FILEUSERNAME/FILEGROUPNAME) of the
// package. Names are resolved with LookupUser and LookupGroup; a file
// whose owner cannot be resolved keeps the extracting user. Ignored, with a
// warning, unless the process runs as root.
Chown bool
// LookupUser and LookupGroup map an owner name to a numeric id for Chown.
// They default to the host's user database ([os/user]).
LookupUser func(name string) (int, error)
LookupGroup func(name string) (int, error)
// SpecialFiles allows creating device nodes, FIFOs and sockets. They are
// skipped, with a logged warning, unless set. Devices need privileges.
SpecialFiles bool
// SkipDigests disables the verification of regular file contents against
// FILEDIGESTS. By default a mismatch fails the extraction with a
// [*DigestMismatchError].
SkipDigests bool
// Logger receives a warning for everything that is skipped. Nil discards.
Logger *slog.Logger
}
ExpandOptions tunes Rpm.ExpandPayloadWithOptions. The zero value extracts like Rpm.ExpandPayload.
type FileDependency ¶ added in v0.4.0
type FileDependency struct {
// Provide is true for an entry of Package.Provides, false for one of
// Package.Requires.
Provide bool `json:"provide,omitempty"`
// Index is the position in that list.
Index int `json:"index"`
}
FileDependency refers to a dependency of the package that was generated from a file.
func (FileDependency) Dependency ¶ added in v0.4.0
func (d FileDependency) Dependency(pkg *Package) (Dependency, bool)
Dependency returns the dependency a file dependency refers to, and whether pkg has it.
type FileEntry ¶
type FileEntry struct {
// Path is the absolute path, directory name and base name joined.
Path string `json:"path"`
MTime int64 `json:"mtime,omitempty"`
// Mode is the file mode (type and permission bits) and Flags the
// tag.RPMFILE_* bits; both are zero when the header omits them.
Mode uint32 `json:"mode,omitempty"`
Flags uint32 `json:"flags,omitempty"`
Digest string `json:"digest,omitempty"`
LinkTo string `json:"linkTo,omitempty"`
// Size is the size of the file in bytes. User and Group name its owner.
Size int64 `json:"size,omitempty"`
User string `json:"user,omitempty"`
Group string `json:"group,omitempty"`
// Caps is the file capability set in the text form of cap_to_text(3),
// for example "cap_net_raw=ep" (FILECAPS); empty for most files.
Caps string `json:"caps,omitempty"`
// Nlink is the number of hard links of the file within the package
// (FILENLINKS). Older packages lack the tag: Nlink is then derived from
// the device and inode numbers, and stays 0 when those are missing too.
Nlink uint32 `json:"nlink,omitempty"`
// Device and Inode are the numbers recorded when the package was built;
// files with the same pair are hard links of each other. Rdev is the
// device number of a device node.
Device uint32 `json:"device,omitempty"`
Inode uint32 `json:"inode,omitempty"`
Rdev uint32 `json:"rdev,omitempty"`
// Lang is the %lang of the file (FILELANGS), for example "de".
Lang string `json:"lang,omitempty"`
// Class is the description of the file type, as file(1) classifies it
// (FILECLASS looked up in CLASSDICT), for example "directory".
Class string `json:"class,omitempty"`
// VerifyFlags are the checks "rpm -V" applies to the file: a mask of the
// tag.RPMVERIFY_* bits (FILEVERIFYFLAGS), all bits set for the default.
VerifyFlags uint32 `json:"verifyFlags,omitempty"`
// Context is the SELinux context of the file (FILECONTEXTS).
Context string `json:"context,omitempty"`
// IMASignature is the IMA file signature (FILESIGNATURES), hex encoded;
// see [Package.IMASignatureLength] and [VerifyIMASignature].
IMASignature string `json:"imaSignature,omitempty"`
// VeritySignature is the fs-verity signature of the file
// (VERITYSIGNATURES of the signature header), hex encoded; see
// [Package.VeritySignatureAlgorithm] and [VerifyVeritySignature].
VeritySignature string `json:"veritySignature,omitempty"`
// Depends lists the dependencies of the package that the file gave rise
// to (FILEDEPENDSX, FILEDEPENDSN and DEPENDSDICT): the provides and
// requires that the dependency generators found in it.
Depends []FileDependency `json:"depends,omitempty"`
}
FileEntry is one file of the file list of a package.
func (FileEntry) IsGhost ¶
IsGhost reports whether the entry is a %ghost file: owned by the package but not shipped in its payload.
type FileInfo ¶
type FileInfo interface {
Name() string
Size() int64
UserName() string
GroupName() string
Flags() int
Mtime() int
Digest() string
Mode() int
Linkname() string
Device() int
Inode() int
// Rdev returns the device number (st_rdev) of a character or block device.
Rdev() int
}
FileInfo describes a file in the RPM payload
type FileTrigger ¶ added in v0.4.0
type FileTrigger struct {
// Kind is [TriggerIn], [TriggerUn] or [TriggerPostun].
Kind TriggerKind `json:"kind"`
// Transaction is true for a transaction file trigger, run once at the end
// of the transaction instead of once per package.
Transaction bool `json:"transaction,omitempty"`
// Priority orders the triggers of a transaction: the higher runs first.
// rpm assigns 1000000 to a trigger that sets none.
Priority uint32 `json:"priority"`
Script Scriptlet `json:"script"`
// Paths are the watched path prefixes.
Paths []string `json:"paths"`
}
FileTrigger is a file trigger (%filetriggerin and friends) or, with Transaction set, a transaction file trigger (%transfiletriggerin and friends): a script that runs when files below one of the watched path prefixes are installed or removed.
type HeaderLimits ¶
type HeaderLimits struct {
// MaxEntries is the largest number of index entries accepted.
MaxEntries int
// MaxDataSize is the largest data store, in bytes, accepted for a header.
MaxDataSize int
}
HeaderLimits bounds the header of a package read from untrusted input. A zero field selects its default; the limits cannot be raised above MaxHeaderEntries and MaxHeaderDataSize.
type HeaderRange ¶
type HeaderRange struct {
// Start is the byte offset of the signature header
Start int
// End is the byte offset of the end of the general header and start of the payload
End int
}
HeaderRange indicates the byte offsets that the RPM header spans
type IMASignature ¶ added in v0.4.0
type IMASignature struct {
// Hash is the algorithm the file digest was computed with.
Hash crypto.Hash
// KeyID is the last four bytes of the SHA-1 of the public key (its
// X.509 subject key identifier, as evmctl computes it).
KeyID [4]byte
// Signature is the RSA (PKCS #1 v1.5) or ECDSA (ASN.1) signature.
Signature []byte
}
IMASignature is a decoded IMA file signature (the "signature v2" format of the security.ima extended attribute): the hash of the file contents signed with the key whose identifier it names.
func ParseIMASignature ¶ added in v0.4.0
func ParseIMASignature(sig []byte) (*IMASignature, error)
ParseIMASignature decodes an IMA signature: the hex string of FileEntry.IMASignature or the raw bytes of the security.ima attribute.
type KeyHolder ¶
type KeyHolder interface {
SigningKey() (*packet.PrivateKey, error)
}
KeyHolder is implemented by signers that hold their private key locally, such as gpg.LocalSigner.
type KeyNotFoundError ¶
func (KeyNotFoundError) Error ¶
func (e KeyNotFoundError) Error() string
type Lead ¶
type Lead struct {
// MajorVersion and MinorVersion are the version of the lead: 3.0 for
// format 4 packages, 4.0 for format 6.
MajorVersion uint8
MinorVersion uint8
// Type is 0 for a binary package and 1 for a source package.
Type uint16
// Arch is the numeric architecture of the lead.
Arch uint16
// Name is the "name-version-release" the package was built as.
Name string
// OS is the numeric operating system of the lead.
OS uint16
// SignatureType is 5 for a package with a header-style signature.
SignatureType uint16
}
Lead is the fixed block at the start of an RPM. Everything it holds is repeated, authoritatively, in the headers; rpm only checks the magic.
type NEVRA ¶
NEVRA holds the name, epoch, version, release and arch of the RPM, which uniquely identifies it
type NEVRASlice ¶
type NEVRASlice []NEVRA
NEVRASlice is used to sort a list of NEVRAs and implements sort.Interface
func (NEVRASlice) Len ¶
func (s NEVRASlice) Len() int
func (NEVRASlice) Less ¶
func (s NEVRASlice) Less(i, j int) bool
func (NEVRASlice) Swap ¶
func (s NEVRASlice) Swap(i, j int)
type NamedScript ¶ added in v0.4.0
type NamedScript struct {
// Name is "pretrans", "pre", "post", "preun", "postun", "posttrans",
// "preuntrans", "postuntrans" or "verify".
Name string
*Scriptlet
}
NamedScript is a scriptlet with the name of its slot in Scripts.
type NoSuchTagError ¶
type NoSuchTagError struct {
Tag int
}
NoSuchTagError is returned when a tag does not exist in the header
func NewNoSuchTagError ¶
func NewNoSuchTagError(id int) NoSuchTagError
NewNoSuchTagError creates a NoSuchTagError for a given tag
func (NoSuchTagError) Error ¶
func (err NoSuchTagError) Error() string
type Package ¶
type Package struct {
Name string `json:"name"`
Version string `json:"version"`
Release string `json:"release"`
Epoch uint32 `json:"epoch,omitempty"`
Arch string `json:"arch"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
License string `json:"license,omitempty"`
URL string `json:"url,omitempty"`
Vendor string `json:"vendor,omitempty"`
Group string `json:"group,omitempty"`
Packager string `json:"packager,omitempty"`
SourceRPM string `json:"sourceRpm,omitempty"`
BuildHost string `json:"buildHost,omitempty"`
BuildTime int64 `json:"buildTime,omitempty"`
// FileTime is when the file entered the repository (the <time file=>
// value of primary.xml); zero falls back to BuildTime.
FileTime int64 `json:"fileTime,omitempty"`
// PackageSize is the size of the .rpm file. The headers do not carry it:
// callers set it.
PackageSize int64 `json:"packageSize,omitempty"`
// InstalledSize is the size of the installed files.
InstalledSize int64 `json:"installedSize,omitempty"`
// InstallTime is when the package was installed, in seconds since the
// epoch. Only the header of an installed package carries it: it is set by
// [RpmHeader.InstalledPackage] and zero otherwise.
InstallTime int64 `json:"installTime,omitempty"`
// ArchiveSize is the size of the uncompressed payload.
ArchiveSize int64 `json:"archiveSize,omitempty"`
// SHA256 is the checksum of the .rpm file. The headers do not carry it:
// callers set it.
SHA256 string `json:"sha256,omitempty"`
// HeaderStart and HeaderEnd are the byte offsets of the general header
// within the .rpm file.
HeaderStart int64 `json:"headerStart,omitempty"`
HeaderEnd int64 `json:"headerEnd,omitempty"`
Provides []Dependency `json:"provides,omitempty"`
Requires []Dependency `json:"requires,omitempty"`
Conflicts []Dependency `json:"conflicts,omitempty"`
Obsoletes []Dependency `json:"obsoletes,omitempty"`
Recommends []Dependency `json:"recommends,omitempty"`
Suggests []Dependency `json:"suggests,omitempty"`
Supplements []Dependency `json:"supplements,omitempty"`
Enhances []Dependency `json:"enhances,omitempty"`
Files []FileEntry `json:"files,omitempty"`
Changelogs []ChangelogEntry `json:"changelogs,omitempty"`
// Distribution, OS, BugURL and VCS are the tags of the same name.
Distribution string `json:"distribution,omitempty"`
OS string `json:"os,omitempty"`
BugURL string `json:"bugUrl,omitempty"`
VCS string `json:"vcs,omitempty"`
// RPMVersion is the version of rpm that built the package.
RPMVersion string `json:"rpmVersion,omitempty"`
// Format is the package format: 4, or 6 for the packages of rpm 6.
Format int `json:"format,omitempty"`
// Prefixes are the paths a relocatable package may be moved from.
Prefixes []string `json:"prefixes,omitempty"`
// ModularityLabel is the module stream the package belongs to,
// "name:stream:version:context".
ModularityLabel string `json:"modularityLabel,omitempty"`
// DistTag is the %{dist} of the release (".fc41") and DistURL the
// location the package was distributed from.
DistTag string `json:"distTag,omitempty"`
DistURL string `json:"distUrl,omitempty"`
// BuildArchs are the architectures a source package is built for.
BuildArchs []string `json:"buildArchs,omitempty"`
// Cookie identifies the build ("host timestamp").
Cookie string `json:"cookie,omitempty"`
// Platform is the platform triplet the package was built for, for
// example "x86_64-redhat-linux-gnu", and OptFlags the compiler flags.
Platform string `json:"platform,omitempty"`
OptFlags string `json:"optFlags,omitempty"`
// Policies are the SELinux policy modules of the package.
Policies []Policy `json:"policies,omitempty"`
// SysUsers are the sysusers.d lines the package declares (%sysusers).
SysUsers []string `json:"sysUsers,omitempty"`
// Order lists the packages that must be installed in this transaction
// before this one, as a dependency list (the ORDER* tags).
Order []Dependency `json:"order,omitempty"`
// IsSource is true for a source package.
IsSource bool `json:"source,omitempty"`
// ExcludeArch, ExclusiveArch, ExcludeOS and ExclusiveOS restrict where
// the package is built (source packages).
ExcludeArch []string `json:"excludeArch,omitempty"`
ExclusiveArch []string `json:"exclusiveArch,omitempty"`
ExcludeOS []string `json:"excludeOs,omitempty"`
ExclusiveOS []string `json:"exclusiveOs,omitempty"`
// Sources and Patches list the sources and the patches of a source
// package, including those it does not ship (%NoSource, %NoPatch).
Sources []SourceFile `json:"sources,omitempty"`
Patches []SourceFile `json:"patches,omitempty"`
// Spec is the text of the spec file (a tag of rpm 6 source packages).
Spec string `json:"spec,omitempty"`
// Scripts are the scriptlets, Triggers the package triggers and
// FileTriggers the file triggers and transaction file triggers.
Scripts Scripts `json:"scripts,omitempty"`
Triggers []Trigger `json:"triggers,omitempty"`
FileTriggers []FileTrigger `json:"fileTriggers,omitempty"`
// PayloadFormat, PayloadCompressor and PayloadFlags describe the
// payload: "cpio", "zstd" and the compression level ("19").
PayloadFormat string `json:"payloadFormat,omitempty"`
PayloadCompressor string `json:"payloadCompressor,omitempty"`
PayloadFlags string `json:"payloadFlags,omitempty"`
// PayloadDigests are the digests of the payload, one per algorithm; see
// [Rpm.SetVerifyPayloadDigest] for their use.
PayloadDigests []PayloadDigest `json:"payloadDigests,omitempty"`
// FileDigestAlgorithm is the number of the hash of Files[i].Digest
// (FILEDIGESTALGO, 1 = MD5 for packages without the tag) and
// FileDigestName its name, for example "sha256".
FileDigestAlgorithm uint32 `json:"fileDigestAlgorithm,omitempty"`
FileDigestName string `json:"fileDigestName,omitempty"`
// IMASignatureLength is the length in bytes of the IMA signatures of the
// files (FILESIGNATURELENGTH); 0 when the package has none.
IMASignatureLength uint32 `json:"imaSignatureLength,omitempty"`
// VeritySignatureAlgorithm is the fs-verity digest algorithm of the
// fs-verity signatures of the files: 1 for SHA-256, 2 for SHA-512; 0 when
// the package has none.
VeritySignatureAlgorithm uint32 `json:"veritySignatureAlgorithm,omitempty"`
// FilesTruncated is true when the header declared more files than
// PackageLimits.MaxArrayEntries or their strings exceeded
// PackageLimits.MaxFileListBytes, so Files is only a prefix of the file
// list of the package.
FilesTruncated bool `json:"filesTruncated,omitempty"`
}
Package is the metadata of a binary or source package: what the headers carry, and what repository metadata (primary, filelists and other) lists. It is built from the headers by ReadPackage and RpmHeader.Package, and is what the writers of repository metadata consume.
func ReadPackage ¶
ReadPackage reads the lead and the headers of a package from r and returns its metadata, with the default PackageLimits. The payload is not read.
Example ¶
package main
import (
"fmt"
"log"
"os"
"strings"
"github.com/M0Rf30/pkgformat/rpm"
)
func main() {
f, err := os.Open("testdata/weakdeps.rpm")
if err != nil {
log.Fatal(err)
}
defer f.Close()
pkg, err := rpm.ReadPackage(f)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s %d:%s-%s.%s\n", pkg.Name, pkg.Epoch, pkg.Version, pkg.Release, pkg.Arch)
for _, d := range pkg.Requires {
if d.IsRPMLib() {
continue
}
fmt.Println("requires", strings.TrimSpace(d.Name+" "+rpm.SenseFlagsString(d.Flags)+" "+d.Version))
}
fmt.Println("recommends", pkg.Recommends[0].Name)
}
Output: weakdep-test 1:1.0-1.noarch requires required-pkg GE 1.5-3 requires shadow-utils recommends recommended-pkg
func ReadPackageLimits ¶
func ReadPackageLimits(r io.Reader, lim PackageLimits) (*Package, error)
ReadPackageLimits is ReadPackage with explicit limits.
func (*Package) BuildConflicts ¶ added in v0.4.0
func (p *Package) BuildConflicts() []Dependency
BuildConflicts returns the build conflicts of a source package: its Conflicts list, which holds the BuildConflicts of the spec file. It is nil for a binary package.
func (*Package) BuildRequires ¶ added in v0.4.0
func (p *Package) BuildRequires() []Dependency
BuildRequires returns the build requirements of a source package: its Requires list, which for a source package holds the BuildRequires of the spec file, including the rpmlib(...) features needed to build it. It is nil for a binary package.
type PackageLimits ¶
type PackageLimits struct {
// Header bounds the headers. The default data store is
// [MaxPackageHeaderDataSize], smaller than that of [ReadHeader].
Header HeaderLimits
// MaxArrayEntries bounds every array: a dependency list over it rejects
// the package, because dropping part of it would make the package
// installable without its requirements; the file list and the changelog
// are cut. Default [MaxArrayEntries].
MaxArrayEntries int
// MaxFileListBytes bounds the strings kept for the file list. Default
// [MaxFileListBytes].
MaxFileListBytes int
}
PackageLimits bounds what ReadPackage keeps of a package read from untrusted input. A zero field selects its default.
type PayloadDigest ¶ added in v0.4.0
type PayloadDigest struct {
// Algorithm is the lower-case name of the hash: "sha256", "sha512" or
// "sha3-256".
Algorithm string `json:"algorithm"`
// Compressed is the hex digest of the payload as stored in the package
// (PAYLOADDIGEST, PAYLOADSHA512, PAYLOADSHA3_256).
Compressed string `json:"compressed,omitempty"`
// Uncompressed is the hex digest of the payload after decompression, the
// cpio archive (PAYLOADDIGESTALT and its SHA-512 and SHA3-256 siblings).
Uncompressed string `json:"uncompressed,omitempty"`
}
PayloadDigest is the digest of the payload of a package under one hash algorithm. A package carries digests of the compressed payload, and since rpm 4.14 also of the uncompressed one.
type PayloadReader ¶
PayloadReader is used to sequentially access the file contents of a RPM payload
type Policy ¶ added in v0.4.0
type Policy struct {
Name string `json:"name"`
// Type is the kind of policy ("selinux").
Type string `json:"type,omitempty"`
Flags uint32 `json:"flags,omitempty"`
}
Policy is an SELinux policy module that a package carries (the POLICY* tags).
type Rpm ¶
type Rpm struct {
Header *RpmHeader
// contains filtered or unexported fields
}
Rpm is an open RPM header and payload
func ReadRpm ¶
ReadRpm reads the header from a RPM file and prepares to read payload contents
Example ¶
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/M0Rf30/pkgformat/rpm"
)
func main() {
f, err := os.Open("testdata/simple-1.0.1-1.i386.rpm")
if err != nil {
log.Fatal(err)
}
defer f.Close()
pkg, err := rpm.ReadRpm(f)
if err != nil {
log.Fatal(err)
}
nevra, err := pkg.Header.GetNEVRA()
if err != nil {
log.Fatal(err)
}
fmt.Println(nevra)
// Bound what an untrusted package may expand to, then extract it.
pkg.SetMaxPayloadSize(1 << 20)
dest, err := os.MkdirTemp("", "rpm-example")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dest)
if err := pkg.ExpandPayload(dest); err != nil {
log.Fatal(err)
}
extracted, err := filepath.Glob(filepath.Join(dest, "*"))
if err != nil {
log.Fatal(err)
}
fmt.Println(len(extracted) > 0)
}
Output: simple-0:1.0.1-1.i386.rpm true
func (*Rpm) ExpandPayload ¶
ExpandPayload extracts the payload of a RPM to the specified directory. It is Rpm.ExpandPayloadWithOptions with the default options: modes (including set-uid, set-gid and sticky bits) and modification times are applied as recorded, contents are checked against FILEDIGESTS, owners are not applied and device nodes, FIFOs and sockets are skipped. Both cpio payloads of RPM v3/v4 and the stripped payloads of RPM v6 are handled.
func (*Rpm) ExpandPayloadWithOptions ¶ added in v0.3.1
func (rpm *Rpm) ExpandPayloadWithOptions(dest string, opts *ExpandOptions) error
ExpandPayloadWithOptions extracts the payload of a RPM to dest as configured by opts (nil means defaults). Files in dest are confined as described in cpio.ExtractWithOptions; files flagged %ghost are not part of the payload and are not created.
Example ¶
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/M0Rf30/pkgformat/rpm"
)
func main() {
f, err := os.Open("testdata/extract/extract-v6.rpm")
if err != nil {
log.Fatal(err)
}
defer f.Close()
pkg, err := rpm.ReadRpm(f)
if err != nil {
log.Fatal(err)
}
dest, err := os.MkdirTemp("", "rpm-example")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dest)
defer func() { _ = os.Chmod(filepath.Join(dest, "opt/extract-test/ro"), 0o755) }()
// Drop the set-uid, set-gid and sticky bits and group/other write access.
if err := pkg.ExpandPayloadWithOptions(dest, &rpm.ExpandOptions{Umask: 07022}); err != nil {
log.Fatal(err)
}
fi, err := os.Stat(filepath.Join(dest, "opt/extract-test/bin/suid"))
if err != nil {
log.Fatal(err)
}
fmt.Println(fi.Mode())
}
Output: -rwxr-xr-x
func (*Rpm) PayloadReader ¶
PayloadReader accesses the payload cpio archive within the RPM. The sizes of stripped payloads (RPM v6) are taken from the header.
DEPRECATED: Use PayloadReaderExtended instead in order to handle files larger than 4GiB.
func (*Rpm) PayloadReaderExtended ¶
func (rpm *Rpm) PayloadReaderExtended() (PayloadReader, error)
PayloadReaderExtended accesses payload file contents sequentially
func (*Rpm) SetMaxPayloadSize ¶
SetMaxPayloadSize bounds the number of bytes the decompressed payload may produce through ExpandPayload, PayloadReader and PayloadReaderExtended. Once the payload yields more than limit bytes, reads fail with ErrPayloadTooLarge.
A limit of zero restores the default: DefaultMaxPayloadSize, or twice the payload size the header declares (see RpmHeader.PayloadSize) when that is larger. The declared size is attacker-controlled, so callers handling untrusted packages should check it against their own policy before expanding. A negative limit removes the bound.
func (*Rpm) SetVerifyPayloadDigest ¶ added in v0.4.0
SetVerifyPayloadDigest makes the payload readers hash the compressed payload and compare it, once the decompressed payload has been read to its end, to the PAYLOADDIGEST of the header; a mismatch ends the read with ErrPayloadDigest instead of io.EOF. Packages without a payload digest (older than rpm 4.14) are not checked. Signature verification (Verify) covers the payload digest through the signed header, so verifying both proves the payload authentic.
type RpmHeader ¶
type RpmHeader struct {
// contains filtered or unexported fields
}
RpmHeader holds the signature header and general header of a RPM
Tags are drawn from both header areas, with IDs between tag.GENERAL_TAG_BASE and tag.SIGHEADER_TAG_BASE coming from the general header and all others coming from the signature header.
func ReadHeader ¶
ReadHeader reads the signature and general headers from a RPM.
The stream is positioned for reading the compressed payload following the headers. The headers are bounded by MaxHeaderEntries and MaxHeaderDataSize; use ReadHeaderLimits for tighter bounds.
func ReadHeaderBlob ¶ added in v0.2.0
func ReadHeaderBlob(blob []byte, lim HeaderLimits) (*RpmHeader, error)
ReadHeaderBlob decodes the header of an installed package as the rpm database stores it: an immutable-region header image without the magic and reserved words a header has inside a package file, that is the number of index entries and the size of the data as two big endian 32 bit integers, the index, then the data.
The signature header of a package is not part of the image, so the result answers the tags of the general header only. The blob is not retained. lim bounds the image as it does for ReadHeaderLimits; the zero value selects the defaults.
func ReadHeaderLimits ¶
func ReadHeaderLimits(f io.Reader, lim HeaderLimits) (*RpmHeader, error)
ReadHeaderLimits is ReadHeader with the headers bounded by lim.
func RewriteWithSignatures ¶
func RewriteWithSignatures(infile *os.File, outpath string, sigPgp, sigRsa []byte) (*RpmHeader, error)
RewriteWithSignatures inserts raw signatures into a RPM header.
DEPRECATED: To perform a detached signature, use SignRpmStream and call DumpSignatureHeader to export the result.
func SignRpmFile ¶
func SignRpmFile(infile *os.File, outpath string, key *packet.PrivateKey, opts *SignatureOptions) (header *RpmHeader, err error)
SignRpmFile signs infile and writes it to outpath, which may be the same file
func SignRpmStream ¶
func SignRpmStream(stream io.Reader, key *packet.PrivateKey, opts *SignatureOptions) (header *RpmHeader, err error)
SignRpmStream reads an RPM and signs it, returning the set of headers updated with the new signature.
Example ¶
SignRpmStream signs a package without rewriting it: the new lead and signature header replace the old ones, the rest of the package is copied.
package main
import (
"bytes"
"fmt"
"log"
"os"
"github.com/ProtonMail/go-crypto/openpgp"
"github.com/M0Rf30/pkgformat/rpm"
)
func main() {
pkg, err := os.ReadFile("testdata/empty-0.1-1.x86_64.rpm")
if err != nil {
log.Fatal(err)
}
key, err := openpgp.NewEntity("example", "", "example@example.com", nil)
if err != nil {
log.Fatal(err)
}
hdr, err := rpm.SignRpmStream(bytes.NewReader(pkg), key.PrivateKey, nil)
if err != nil {
log.Fatal(err)
}
head, err := hdr.DumpSignatureHeader(false)
if err != nil {
log.Fatal(err)
}
signed := append(head, pkg[hdr.OriginalSignatureHeaderSize():]...)
_, sigs, err := rpm.Verify(bytes.NewReader(signed), openpgp.EntityList{key})
if err != nil {
log.Fatal(err)
}
// An unsigned package verifies with no signatures: check len(sigs).
fmt.Println(len(sigs), "signatures")
}
Output: 2 signatures
func (*RpmHeader) Dependencies ¶
func (hdr *RpmHeader) Dependencies(nameTag, flagsTag, versionTag int) ([]Dependency, error)
Dependencies decodes a dependency list from the parallel name, flags and version tags of the header, for example tag.REQUIRENAME, tag.REQUIREFLAGS and tag.REQUIREVERSION. A list that is absent yields nil. A flags or version tag of 0 is ignored.
func (*RpmHeader) DumpSignatureHeader ¶
DumpSignatureHeader dumps the lead and signature header, optionally adding or changing padding to make it the same size as when it was originally read. Otherwise padding is removed to make it as small as possible.
A RPM can be signed by removing the first OriginalSignatureHeaderSize() bytes of the file and replacing it with the result of DumpSignatureHeader().
func (*RpmHeader) Format ¶
Format returns the RPM package format version: the value of the RPMFORMAT tag, or 4 if absent (RPM v4 packages).
func (*RpmHeader) Get ¶
Get the value of a tag. Returns whichever type most closely represents how the tag was stored, or NoSuchTagError if the tag was not found. If tag is OLDFILENAMES, special handling is provided to splice together DIRNAMES and BASENAMES if it is not present.
func (*RpmHeader) GetFiles ¶
GetFiles returns an array of FileInfo objects holding file-related attributes held in parallel arrays of tags
func (*RpmHeader) GetInt ¶
GetInt gets an integer using the default 'int' type.
DEPRECATED: large int32s and int64s can overflow. Use GetUint32s or GetUint64s instead.
func (*RpmHeader) GetInts ¶
GetInts gets an integer array using the default 'int' type.
DEPRECATED: large int32s and int64s can overflow. Use GetUint32s or GetUint64s instead.
func (*RpmHeader) GetRange ¶
func (hdr *RpmHeader) GetRange() HeaderRange
GetRange returns the byte offsets that the RPM header spans within the original RPM file
func (*RpmHeader) GetStrings ¶
GetStrings fetches the given tag holding a string or array of strings. If tag is OLDFILENAMES, special handling is provided to splice together DIRNAMES and BASENAMES if it is not present.
func (*RpmHeader) GetUint32 ¶
GetUint32 gets an uint32 type other than INT64. Note that it returns 0 when fails instead of -1. Returns an error in case of overflow.
func (*RpmHeader) GetUint32s ¶
GetUint32s gets an int array as a uint32 slice. This can accommodate any int type other than INT64. Returns an error in case of overflow.
func (*RpmHeader) GetUint64 ¶
GetUint64 gets an uint64 type. Note that it returns 0 when fails instead of -1.
func (*RpmHeader) GetUint64Fallback ¶
GetUint64Fallback gets longTag if it exists, otherwise intTag, and returns the value as an array of uint64s. This can accommodate all int types and is normally used when a int32 tag was later replaced with a int64 tag.
func (*RpmHeader) GetUint64s ¶
GetUint64s gets an int array as a uint64 slice. This can accommodate all int types
func (*RpmHeader) InstalledPackage ¶ added in v0.2.0
func (hdr *RpmHeader) InstalledPackage(lim PackageLimits) (*Package, error)
InstalledPackage returns the metadata of a header that describes an installed package, as RpmHeader.Package does for a package file with two differences: the architecture may be missing (the gpg-pubkey pseudo packages of the rpm database have none), and Package.InstallTime is set.
func (*RpmHeader) InstalledSize ¶
InstalledSize returns the approximate disk space needed to install the package
func (*RpmHeader) OriginalSignatureHeaderSize ¶
OriginalSignatureHeaderSize returns the size of the lead and signature header area as originally read from the file.
func (*RpmHeader) Package ¶
func (hdr *RpmHeader) Package(lim PackageLimits) (*Package, error)
Package returns the metadata of the package the headers describe. PackageSize and SHA256 are left for the caller to set. Limits that were not applied when the headers were read are applied to what is kept.
func (*RpmHeader) PayloadSize ¶
PayloadSize returns the size of the uncompressed payload in bytes
type ScriptFlags ¶ added in v0.4.0
type ScriptFlags uint32
ScriptFlags are the flags of a scriptlet (the *FLAGS tags such as PREINFLAGS): how rpm runs it.
const ( // ScriptExpand makes rpm expand macros in the body before running it // (spec file option -e). ScriptExpand ScriptFlags = tag.RPMSCRIPT_FLAG_EXPAND // ScriptQFormat makes rpm expand query-format tags in the body (-q). ScriptQFormat ScriptFlags = tag.RPMSCRIPT_FLAG_QFORMAT // ScriptCritical makes a failure of the scriptlet abort the transaction. ScriptCritical ScriptFlags = tag.RPMSCRIPT_FLAG_CRITICAL )
The scriptlet flags, the tag.RPMSCRIPT_FLAG_* values.
func (ScriptFlags) Critical ¶ added in v0.4.0
func (f ScriptFlags) Critical() bool
Critical reports the flag that makes a failing scriptlet abort the transaction.
func (ScriptFlags) Expand ¶ added in v0.4.0
func (f ScriptFlags) Expand() bool
Expand reports the macro expansion flag.
func (ScriptFlags) QFormat ¶ added in v0.4.0
func (f ScriptFlags) QFormat() bool
QFormat reports the query-format expansion flag.
type Scriptlet ¶ added in v0.4.0
type Scriptlet struct {
// Body is the text of the script. It is empty for a scriptlet that only
// names a program, such as "%post -p /sbin/ldconfig".
Body string `json:"body,omitempty"`
// Interpreter is the program that runs Body (the first element of the
// *PROG tag): "/bin/sh", "/usr/bin/python3" or [LuaInterpreter]. It is
// empty when the package does not name one, which means /bin/sh.
Interpreter string `json:"interpreter,omitempty"`
// Args are the arguments of Interpreter (the remaining elements of the
// *PROG tag), such as "-e" of "/bin/bash -e".
Args []string `json:"args,omitempty"`
Flags ScriptFlags `json:"flags,omitempty"`
}
Scriptlet is one script of a package: the body and how it is run.
type Scripts ¶ added in v0.4.0
type Scripts struct {
PreTrans *Scriptlet `json:"pretrans,omitempty"`
Pre *Scriptlet `json:"pre,omitempty"`
Post *Scriptlet `json:"post,omitempty"`
PreUn *Scriptlet `json:"preun,omitempty"`
PostUn *Scriptlet `json:"postun,omitempty"`
PostTrans *Scriptlet `json:"posttrans,omitempty"`
PreUnTrans *Scriptlet `json:"preuntrans,omitempty"`
PostUnTrans *Scriptlet `json:"postuntrans,omitempty"`
// Verify is the %verifyscript, run by "rpm -V".
Verify *Scriptlet `json:"verify,omitempty"`
}
Scripts holds the scriptlets of a package. A scriptlet the package does not have is nil.
func (Scripts) All ¶ added in v0.4.0
func (s Scripts) All() []NamedScript
All returns the scriptlets the package has, in the order of the fields of Scripts.
type Sense ¶ added in v0.4.0
type Sense uint32
Sense holds the sense flags (the RPMSENSE_* bits) of a dependency: a comparison (less, greater, equal, or a combination) and the roles the dependency plays, such as being needed by a scriptlet of the package. The bits are those of the tag package, so a Sense converts to and from the uint32 stored in the REQUIREFLAGS family of tags.
const ( SenseAny Sense = tag.RPMSENSE_ANY SenseLess Sense = tag.RPMSENSE_LESS SenseGreater Sense = tag.RPMSENSE_GREATER SenseEqual Sense = tag.RPMSENSE_EQUAL SensePosttrans Sense = tag.RPMSENSE_POSTTRANS SensePrereq Sense = tag.RPMSENSE_PREREQ SensePretrans Sense = tag.RPMSENSE_PRETRANS SenseInterp Sense = tag.RPMSENSE_INTERP SenseScriptPre Sense = tag.RPMSENSE_SCRIPT_PRE SenseScriptPost Sense = tag.RPMSENSE_SCRIPT_POST SenseScriptPreun Sense = tag.RPMSENSE_SCRIPT_PREUN SenseScriptPostun Sense = tag.RPMSENSE_SCRIPT_POSTUN SenseScriptVerify Sense = tag.RPMSENSE_SCRIPT_VERIFY SenseMissingOK Sense = tag.RPMSENSE_MISSINGOK SensePreuntrans Sense = tag.RPMSENSE_PREUNTRANS SensePostuntrans Sense = tag.RPMSENSE_POSTUNTRANS SenseRPMLib Sense = tag.RPMSENSE_RPMLIB SenseKeyring Sense = tag.RPMSENSE_KEYRING SenseConfig Sense = tag.RPMSENSE_CONFIG SenseRich Sense = tag.RPMSENSE_RICH SenseTriggerIn Sense = tag.RPMSENSE_TRIGGERIN SenseTriggerUn Sense = tag.RPMSENSE_TRIGGERUN SenseTriggerPostun Sense = tag.RPMSENSE_TRIGGERPOSTUN SenseTriggerPrein Sense = tag.RPMSENSE_TRIGGERPREIN )
The comparison and role bits, as typed values; they equal the tag.RPMSENSE_* constants.
func (Sense) Comparison ¶ added in v0.4.0
Comparison returns the comparison bits only: any combination of SenseLess, SenseGreater and SenseEqual.
func (Sense) IsConfig ¶ added in v0.4.0
IsConfig reports the implicit config(name) dependency that ties a configuration file to its package.
func (Sense) IsInterp ¶ added in v0.4.0
IsInterp reports the dependency on the interpreter of a scriptlet.
func (Sense) IsKeyring ¶ added in v0.4.0
IsKeyring reports a requirement on a key of the rpm keyring.
func (Sense) IsMissingOK ¶ added in v0.4.0
IsMissingOK reports a dependency that need not be satisfied (Requires(missingok)).
func (Sense) IsPosttrans ¶ added in v0.4.0
IsPosttrans reports a Requires(posttrans) dependency.
func (Sense) IsPre ¶ added in v0.4.0
IsPre reports whether the requirement is needed before the package is installed: it is a Requires(pre) or Requires(post) dependency, or a legacy PreReq. It is what the pre attribute of repodata means. Use Sense.Has with SenseScriptPre to test for Requires(pre) alone.
func (Sense) IsPretrans ¶ added in v0.4.0
IsPretrans reports a Requires(pretrans) dependency.
func (Sense) IsRich ¶ added in v0.4.0
IsRich reports the rich marker rpm sets on the dependency while it parses it. The marker is not stored in packages: use Dependency.IsRich, which recognises a rich dependency by its name.
func (Sense) IsScriptVerify ¶ added in v0.4.0
IsScriptVerify reports a Requires(verify) dependency.
func (Sense) IsUntrans ¶ added in v0.4.0
IsUntrans reports a Requires(preuntrans) or Requires(postuntrans) dependency.
func (Sense) Operator ¶ added in v0.4.0
Operator renders the comparison bits as the operator of a spec file: "<", ">", "=", "<=" or ">=", and "" when there is no (valid) comparison.
func (Sense) Roles ¶ added in v0.4.0
Roles names the role bits that are set, the way rpm prints them in `rpm -q --requires` ("pre", "post", "preun", "postun", "pretrans", "posttrans", "preuntrans", "postuntrans", "verify", "interp", "prereq", "meta", "rpmlib", "keyring", "config", "missingok"), in a stable order.
type Signature ¶
type Signature struct {
// Signer is the PGP identity that created the signature. It may be nil if
// the public key is not available at verification time, but KeyId will
// always be set.
Signer *openpgp.Entity
// Hash is the algorithm used to digest the signature contents
Hash crypto.Hash
// CreationTime is when the signature was created
CreationTime time.Time
// HeaderOnly is true for signatures that only cover the general RPM header,
// and false for signatures that cover the general header plus the payload
HeaderOnly bool
// KeyId is the PGP key that created the signature.
KeyId uint64
// KeyFingerprint is the fingerprint of the public key that created the
// signature, if available.
KeyFingerprint []byte
// PrimaryName is the primary identity of the signing key, if available.
PrimaryName string
// contains filtered or unexported fields
}
Signature describes a PGP signature found within a RPM while verifying it.
type SignatureError ¶ added in v0.3.1
SignatureError reports a signature that matches the data but whose key cannot be relied on. Err is one of github.com/M0Rf30/pkgformat/gpg.ErrKeyRevoked, github.com/M0Rf30/pkgformat/gpg.ErrKeyExpired, github.com/M0Rf30/pkgformat/gpg.ErrSignatureExpired, github.com/M0Rf30/pkgformat/gpg.ErrKeyCannotSign or github.com/M0Rf30/pkgformat/gpg.ErrBadSignature, and is reachable with errors.Is.
func (*SignatureError) Error ¶ added in v0.3.1
func (e *SignatureError) Error() string
func (*SignatureError) Unwrap ¶ added in v0.3.1
func (e *SignatureError) Unwrap() error
Unwrap returns the reason.
type SignatureOptions ¶
type SignatureOptions struct {
// Hash algorithm for the signature. If not set, defaults to SHA-256
Hash crypto.Hash
// CreationTime for the signature. If not set, defaults to the current time
CreationTime time.Time
// Lifetime is how long the signature is valid for, counted from its
// creation time and rounded down to whole seconds. Zero means it never
// expires.
Lifetime time.Duration
}
SignatureOptions describes additional configuration for SignRpm methods
type SourceFile ¶ added in v0.4.0
type SourceFile struct {
// Name is the file name, for example "foo-1.0.tar.gz".
Name string `json:"name"`
// Number is the position in the list of sources (or patches) of the
// package. The header does not store the number the spec file gave
// ("Source5:"), so this is the number only when the spec numbers its
// sources consecutively from 0, which is the usual case.
Number int `json:"number"`
// NoSource is true for a file that the spec marks %NoSource/%NoPatch:
// listed by the package but not shipped in it.
NoSource bool `json:"noSource,omitempty"`
}
SourceFile is a source or a patch of a source package.
type Trigger ¶ added in v0.4.0
type Trigger struct {
Kind TriggerKind `json:"kind"`
Script Scriptlet `json:"script"`
// Conditions are the watched packages: the name, comparison and version
// of each "%triggerin -- foo, bar >= 2.0" target. Their Flags carry the
// trigger kind bits as well as the comparison.
Conditions []Dependency `json:"conditions,omitempty"`
}
Trigger is a package trigger: a script that runs when another package matching one of the conditions is installed or removed.
type TriggerKind ¶ added in v0.4.0
type TriggerKind string
TriggerKind says when a trigger runs relative to the install or removal of the package it watches.
const ( // TriggerPrein runs before the watched package is installed // (%triggerprein). TriggerPrein TriggerKind = "prein" // TriggerIn runs after the watched package is installed or upgraded // (%triggerin). TriggerIn TriggerKind = "in" // TriggerUn runs before the watched package is removed (%triggerun). TriggerUn TriggerKind = "un" // TriggerPostun runs after the watched package is removed // (%triggerpostun). TriggerPostun TriggerKind = "postun" )
The kinds of trigger. A file trigger is never "prein".
type VerifyOptions ¶ added in v0.3.1
type VerifyOptions struct {
// RequireSigned makes a package that carries no PGP signature fail with
// [ErrUnsigned]. Without it such a package verifies, with an empty list of
// signatures, as long as its digests are good: an unsigned package is
// intact, not authentic. Setting it needs known keys (a nil keyring fails
// with [ErrNoKnownKeys]), since a signature that is not checked proves
// nothing.
RequireSigned bool
// Now is the time source the validity of the keys and signatures is judged
// at: expiry, creation after the check, revocation. Nil is time.Now.
Now func() time.Time
}
VerifyOptions tunes VerifyWithOptions. The zero value is what Verify does.
type VersionSlice ¶
type VersionSlice []string
VersionSlice provides the Sort interface for sorting version strings.
func (VersionSlice) Len ¶
func (vs VersionSlice) Len() int
Len is the number of elements in the collection.
func (VersionSlice) Less ¶
func (vs VersionSlice) Less(i, j int) bool
Less reports wheather the element with index i should sort before the element with index j.
func (VersionSlice) Swap ¶
func (vs VersionSlice) Swap(i, j int)
Swap swaps the elements with indexes i and j.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package cpio reads, writes and extracts the cpio archives that make up the payload of rpm packages: the "newc" format of format 4 packages and the stripped variant of format 6 packages, which holds only the index of each file in the header.
|
Package cpio reads, writes and extracts the cpio archives that make up the payload of rpm packages: the "newc" format of format 4 packages and the stripped variant of format 6 packages, which holds only the index of each file in the header. |
|
Package dnf is a client for dnf/yum repositories: it reads .repo files, refreshes repository metadata into a cache, indexes it, resolves package dependencies and downloads verified packages.
|
Package dnf is a client for dnf/yum repositories: it reads .repo files, refreshes repository metadata into a cache, indexes it, resolves package dependencies and downloads verified packages. |
|
internal
|
|
|
header
Package header encodes RPM headers: the signature header and the main header of a package share one binary layout, which is written here for both the package writer and the signature rewriting of the reader.
|
Package header encodes RPM headers: the signature header and the main header of a package share one binary layout, which is written here for both the package writer and the signature rewriting of the reader. |
|
Package pack writes rpm packages.
|
Package pack writes rpm packages. |
|
Package repodata writes and reads the metadata of an RPM repository: the repomd.xml index and the primary.xml, filelists.xml, other.xml, comps.xml and modules.yaml documents that dnf and yum fetch.
|
Package repodata writes and reads the metadata of an RPM repository: the repomd.xml index and the primary.xml, filelists.xml, other.xml, comps.xml and modules.yaml documents that dnf and yum fetch. |
|
Package richdep parses and evaluates the rich (boolean) dependencies of RPM: "(foo and bar)", "(foo if bar)", "(foo unless bar else baz)", "((a or b) with c)" and the like, as rpm 4.12 and later read them.
|
Package richdep parses and evaluates the rich (boolean) dependencies of RPM: "(foo and bar)", "(foo if bar)", "(foo unless bar else baz)", "((a or b) with c)" and the like, as rpm 4.12 and later read them. |
|
Package rpmdb reads the database in which rpm records the packages installed on a host: SQLite (rpm 4.16 and later on Fedora, RHEL 9, Rocky 9, AlmaLinux 9, ...), the BerkeleyDB hash database of rpm 4.15 and earlier (RHEL 8 and its rebuilds, CentOS 7), and the "ndb" database of openSUSE and SUSE Linux Enterprise.
|
Package rpmdb reads the database in which rpm records the packages installed on a host: SQLite (rpm 4.16 and later on Fedora, RHEL 9, Rocky 9, AlmaLinux 9, ...), the BerkeleyDB hash database of rpm 4.15 and earlier (RHEL 8 and its rebuilds, CentOS 7), and the "ndb" database of openSUSE and SUSE Linux Enterprise. |
|
Package tag holds the numeric constants of the RPM header format: the types of header entries, the tag numbers of the general header and of the signature header (mirroring rpmtag.h of rpm), the bitmasks found in some of the tags, and the OpenPGP hash algorithm identifiers used by signatures.
|
Package tag holds the numeric constants of the RPM header format: the types of header entries, the tag numbers of the general header and of the signature header (mirroring rpmtag.h of rpm), the bitmasks found in some of the tags, and the OpenPGP hash algorithm identifiers used by signatures. |