64 lines
2.3 KiB
Go
64 lines
2.3 KiB
Go
package trust
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"errors"
|
||
|
|
"fmt"
|
||
|
|
"strings"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"aead.dev/minisign"
|
||
|
|
)
|
||
|
|
|
||
|
|
// SignDigest makes the publisher signature of an OCI manifest digest:
|
||
|
|
// the Signature payload yet pushes as a referrer and VerifySignature
|
||
|
|
// checks. The trusted comment is "yet package digest: <digest>" (the
|
||
|
|
// format yet has always written).
|
||
|
|
func SignDigest(kp KeyPair, digest string) (Signature, error) {
|
||
|
|
trustedComment := "yet package digest: " + digest
|
||
|
|
sig := minisign.SignWithComments(kp.Private, []byte(digest), trustedComment, "")
|
||
|
|
pubText, err := kp.Public.MarshalText()
|
||
|
|
if err != nil {
|
||
|
|
return Signature{}, err
|
||
|
|
}
|
||
|
|
return Signature{
|
||
|
|
SchemaVersion: 1,
|
||
|
|
Algorithm: "minisign",
|
||
|
|
PublicKey: string(pubText),
|
||
|
|
Digest: digest,
|
||
|
|
Value: string(sig),
|
||
|
|
SignedAt: time.Now().UTC(),
|
||
|
|
}, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// Sign makes a detached minisign signature of message: the text of a
|
||
|
|
// ".minisig" file, which "minisign -V -m <file>" verifies against the
|
||
|
|
// key's ".pub" file. trustedComment is signed with it (one line);
|
||
|
|
// untrustedComment is not ("" for minisign's default).
|
||
|
|
func Sign(kp KeyPair, message []byte, trustedComment, untrustedComment string) ([]byte, error) {
|
||
|
|
if strings.ContainsAny(trustedComment, "\r\n") || strings.ContainsAny(untrustedComment, "\r\n") {
|
||
|
|
return nil, errors.New("a minisign comment is one line")
|
||
|
|
}
|
||
|
|
return minisign.SignWithComments(kp.Private, message, trustedComment, untrustedComment), nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// ErrBadSignature: a signature does not verify (wrong key, changed
|
||
|
|
// message or changed trusted comment).
|
||
|
|
var ErrBadSignature = errors.New("signature does not verify")
|
||
|
|
|
||
|
|
// VerifyMessage checks a detached minisign signature (Sign's output, or
|
||
|
|
// a ".minisig" file from the minisign tool) of message against pub and
|
||
|
|
// returns its trusted comment, which the signature covers. A signature
|
||
|
|
// by another key fails, also when its key ID collides with pub's.
|
||
|
|
func VerifyMessage(pub minisign.PublicKey, message, signature []byte) (trustedComment string, err error) {
|
||
|
|
var sig minisign.Signature
|
||
|
|
if err := sig.UnmarshalText(signature); err != nil {
|
||
|
|
return "", fmt.Errorf("parse signature: %w", err)
|
||
|
|
}
|
||
|
|
if sig.KeyID != pub.ID() {
|
||
|
|
return "", fmt.Errorf("%w: signed by key %s, not %s", ErrBadSignature, KeyIDFromUint(sig.KeyID), ID(pub))
|
||
|
|
}
|
||
|
|
if !minisign.Verify(pub, message, signature) {
|
||
|
|
return "", ErrBadSignature
|
||
|
|
}
|
||
|
|
return sig.TrustedComment, nil
|
||
|
|
}
|