A Kolo node is known by its Ed25519 public key. kolo-id creates and stores that key pair, signs messages with Ed25519ctx from RFC 8032, and checks signatures from other peers. Every other Kolo library takes its identities from here. It does not decide which keys to trust.
One person can use several devices. A 24-word recovery phrase gives a person key (through BIP-39 and SLIP-0010), and each device keeps its own random key and a certificate signed by that person key, so a lost device is revoked without losing the identity.
Keys, signing and verifying
Only the seed is stored. A signature checks out only with the context it was made under.
- Generate takes 32 random bytes: the seed.
- The seed gives the private key (64 bytes, kept in memory) and the public key (32 bytes). The public key is the identity, written as 64 hex characters.
- Sign uses Ed25519ctx: the private key signs the message under a context of 1 to 255 bytes and gives a 64-byte signature.
- Verify takes the public key, the same context, the message and the signature, and returns true.
- It returns false for another context, a public key that is not 32 bytes or a small-order key.
- Save writes only the seed, to a file with mode 0600. Load reads it back and makes the same key pair.
Install
go get github.com/ciranda-dev/kolo-idIt is pure Go with no cgo. Its dependencies are golang.org/x/sys, for the
libc-backed openat on macOS, and kolo-codec, for the certificate
encoding.
Quick start
Create an identity, sign under a context, then save and load it in a temporary directory.
package main
import (
"fmt"
"log"
"os"
"path/filepath"
koloid "github.com/ciranda-dev/kolo-id"
)
func main() {
me, err := koloid.Generate()
if err != nil {
log.Fatal(err)
}
fmt.Println("identity:", me)
const ctx = "myapp/hello/v0"
msg := []byte("hello kolo")
sig, err := me.Sign(ctx, msg)
if err != nil {
log.Fatal(err)
}
fmt.Println("valid:", koloid.Verify(me.PublicKey(), ctx, msg, sig))
fmt.Println("other context:", koloid.Verify(me.PublicKey(), "myapp/other/v0", msg, sig))
dir, err := os.MkdirTemp("", "koloid")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "id.key")
if err := me.SaveNew(path); err != nil {
log.Fatal(err)
}
loaded, err := koloid.Load(path)
if err != nil {
log.Fatal(err)
}
fmt.Println("same key:", me.PublicKey().Equal(loaded.PublicKey()))
}It prints the public key, valid: true, other context: false and
same key: true. A real node calls Load first and, when the error matches
os.ErrNotExist, calls Generate and SaveNew once, so it keeps the same
public key across restarts.
Recovery phrase and devices
A person key never lives on a device. The 24 words give the person key, the
person key certifies the first device as an approver, and an approver adds
ordinary devices without the words. A verifier always states the person it
expects. This program, examples/devices in the repository, runs the whole
flow in a temporary directory and never prints the phrase.
// Command devices shows a recovery phrase, a person key and two device certificates, all in a temporary directory.
// It never prints the phrase.
package main
import (
"bytes"
"errors"
"fmt"
"log"
"os"
"path/filepath"
koloid "github.com/ciranda-dev/kolo-id"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
// run returns errors instead of exiting, so the deferred cleanup always runs.
func run() error {
dir, err := os.MkdirTemp("", "koloid-devices")
if err != nil {
return err
}
defer os.RemoveAll(dir)
// The person key comes from 24 words. An app shows them once and never stores them.
phrase, err := koloid.GeneratePhrase()
if err != nil {
return err
}
person, err := phrase.Person()
if err != nil {
return err
}
words := phrase.Words()
phrase.Clear()
// Every device and verifier pins this key. It is never read out of a certificate that is being checked.
personKey := person.PublicKey()
fmt.Println("person:", person, "words:", len(words))
// The first device gets an approver certificate. Each device has its own random key.
laptop, err := koloid.Generate()
if err != nil {
return err
}
offer, err := person.OfferDeviceCert(laptop.PublicKey(), &koloid.IssueOptions{Serial: 1, Approver: true})
if err != nil {
return err
}
laptopCert, err := laptop.AcceptDeviceCert(offer, personKey)
if err != nil {
return err
}
if err := save(dir, "laptop", laptop, laptopCert); err != nil {
return err
}
// The laptop adds a phone without the phrase: the offer travels to the phone, the acceptance proves the phone holds its key.
laptop, laptopCert, err = load(dir, "laptop")
if err != nil {
return err
}
phone, err := koloid.Generate()
if err != nil {
return err
}
offer, err = laptop.OfferDeviceCert(phone.PublicKey(), &koloid.IssueOptions{Parent: laptopCert, Serial: 1})
if err != nil {
return err
}
// A real phone learns personKey from the linking exchange, not from the offer.
phoneCert, err := phone.AcceptDeviceCert(offer, personKey)
if err != nil {
return err
}
if err := save(dir, "phone", phone, phoneCert); err != nil {
return err
}
// A verifier states the person it expects. A message from the phone verifies through its certificate.
const ctx = "kolo-id/example/v0"
msg := []byte("hello from the phone")
sig, err := phone.Sign(ctx, msg)
if err != nil {
return err
}
opts := &koloid.VerifyOptions{Person: personKey}
fmt.Println("phone message:", koloid.VerifyDevice(phoneCert, opts, ctx, msg, sig))
// The laptop revokes the phone's certificate. A verifier that holds the revocation refuses that certificate from now on; revocations are permanent, so keep them.
rev, err := laptop.RevokeDevice(&koloid.RevokeOptions{Person: personKey, Device: phone.PublicKey(), SignerCert: laptopCert, Target: phoneCert})
if err != nil {
return err
}
opts.Revocations = []*koloid.Revocation{rev}
err = koloid.VerifyDevice(phoneCert, opts, ctx, msg, sig)
fmt.Println("after revoking:", errors.Is(err, koloid.ErrCertRevoked))
// The same words give the same person key on any new install.
again, err := koloid.ParseWords(words)
if err != nil {
return err
}
restored, err := again.Person()
if err != nil {
return err
}
fmt.Println("restored the same person:", bytes.Equal(restored.PublicKey(), personKey))
return nil
}
func save(dir, name string, id *koloid.Identity, cert *koloid.DeviceCert) error {
if err := id.Save(filepath.Join(dir, name+".key")); err != nil {
return err
}
return koloid.SaveCert(filepath.Join(dir, name+".cert"), cert)
}
func load(dir, name string) (*koloid.Identity, *koloid.DeviceCert, error) {
id, err := koloid.Load(filepath.Join(dir, name+".key"))
if err != nil {
return nil, nil, err
}
cert, err := koloid.LoadCert(filepath.Join(dir, name+".cert"))
return id, cert, err
}It prints the person key and words: 24, then phone message: <nil>,
after revoking: true and restored the same person: true.
Recovery phrase
GeneratePhrasemakes 24 words of the BIP-39 English list fromcrypto/rand: 256 bits of entropy and an 8-bit checksum. ShowWords()once, let the person write them down, then callClear()and drop the strings. The library never stores, prints or shows a phrase again.ParsePhrasereads 24 words separated by spaces, tabs or line breaks, ignoring case, andParseWordsdoes the same for a split list. Only ASCII is accepted, with no Unicode normalization, and input over 1024 bytes is refused.Phrase.Personderives the person key: the BIP-39 seed with an empty passphrase (2048 rounds of PBKDF2-HMAC-SHA512), then SLIP-0010 for Ed25519 at the hardened pathm/1802464367'/0'/0'. The path never changes, and device keys are never derived from the phrase. There is no BIP-39 passphrase.- One random typing error in 256 still passes the checksum and gives another
valid identity, so a restore screen should show the person key
(
PublicKeyString) for the person to check. - A
*Phraseprints askoloid.Phrase{redacted}for everyfmtverb and inlog/slog, and never encodes (ErrNotEncodable). Errors say the position of a bad word, never the word:ErrPhraseLength,ErrUnknownWord(an*UnknownWordError),ErrPhraseChecksumandErrInvalidPhrase.
Device certificates
- A chain is at most person, approver, device. The person key certifies approver devices; an approver certifies ordinary devices and cannot certify another approver.
- A certificate is made in two steps. The issuer signs an offer with
OfferDeviceCert, and the device finishes it withAcceptDeviceCert, which proves that it holds its own key.IssueOptions.Serialis at least 1 and chosen by the caller, since the library keeps no state. DeviceCert.Person()andDeviceCert.Issuer()are claims in unverified bytes. Pin the person key in your own state and never take it from a certificate you are checking.VerifyDevice(cert, opts, context, msg, sig)checks that a message was signed by a device ofopts.Person: structure, person, expiry, revocation and every signature. There is no mode without a certificate.DeviceCert.Verifyruns the same checks without a message.EncodeandDecodeCertOffer,DecodeDeviceCertandDecodeRevocationmove the objects over the network in the kolo-codec encoding. Decoders refuse oversized input before parsing and do not check signatures.SaveCertandLoadCertkeep the certificate next to the device key, for exampledevice.keyanddevice.cert, with mode 0600 and the same directory checks asSaveandLoad. A loaded certificate is untrusted input: verify it before use.
Revocations
RevokeDevicehas two forms. The person key or the device itself revokes by serial: every certificate of that key up toUpToSerialis void, andmath.MaxUint64burns the key for good. An approver revokes one exact ordinary-device certificate, named byRevokeOptions.Target; the signed record carries its SHA-256 (Revocation.TargetHash), andRevocation.Signerreturns the approver that signed it.- The hash covers the certificate's body, issuer and parent but not its signatures, because Ed25519 signatures are not unique. An approver's revocation cannot burn a key or cover a certificate that does not exist yet. The way back from it is a new certificate for the same device key with a new serial.
- Revoking an approver, which only the person key can do, also voids every certificate it issued.
- Revocations are permanent. A record signed by an approver is judged by the
structure and signatures of its signer certificate, not by the signer's
expiry or a later revocation of the signer. Keep every record that passed
Revocation.Verifyand pass them inVerifyOptions.Revocations: a verifier that keeps none cannot see a revoked device.
API reference
The API reference is generated from the Go source and is in English.
Package koloid provides Ed25519 node identities for Kolo. Only the 32-byte seed is stored on disk.
A person with several devices has a recovery phrase of 24 words (BIP-39), a person key derived from it (SLIP-0010), one random key per device and a certificate for each device signed by the person key or by an approver device. A verifier states the person it expects and calls VerifyDevice; a revoked device is voided with Identity.RevokeDevice. The phrase is shown once and never stored by the library.
Experimental: the API may change before v1.0.0.
Variables
var (
// ErrInvalidArgument is returned for bad options: a zero serial, an expiry not after the issue time, a missing or small-order key, an empty, long or reserved context.
ErrInvalidArgument = errors.New("koloid: invalid argument")
// ErrInvalidCert is returned for a certificate or offer that is nil, truncated, oversized, not canonical, has trailing bytes or breaks a structure rule.
ErrInvalidCert = errors.New("koloid: invalid device certificate")
// ErrNotApprover is returned by [Identity.OfferDeviceCert] and [Identity.RevokeDevice] when the signing certificate is not an approver certificate.
ErrNotApprover = errors.New("koloid: signer is not an approver")
// ErrCertSignature is returned when a certificate, offer or revocation signature, or the message signature, does not verify.
ErrCertSignature = errors.New("koloid: device certificate signature does not verify")
// ErrCertPerson is returned when the certificate chain does not end at the expected person key.
ErrCertPerson = errors.New("koloid: device certificate is for another person")
// ErrCertExpired is returned when a certificate in the chain is past its expiry.
ErrCertExpired = errors.New("koloid: device certificate expired")
// ErrCertRevoked is returned when a valid revocation covers a certificate in the chain.
ErrCertRevoked = errors.New("koloid: device certificate revoked")
// ErrInvalidRevocation is returned for a revocation that is malformed, unrelated to the expected person or not allowed to revoke its target.
ErrInvalidRevocation = errors.New("koloid: invalid revocation")
)var (
// ErrInvalidKeyFile is returned by [Load] when the file is not a regular 32-byte file, and by [LoadCert] for an empty or over-514-byte file.
ErrInvalidKeyFile = keyfile.ErrInvalid
// ErrInsecureKeyFile is returned by [Load], [LoadCert], [SaveCert], [Identity.Save] and [Identity.SaveNew] when the key directory is a symlink
// or others can access or another user owns the key file or its directory (see [Load]).
ErrInsecureKeyFile = keyfile.ErrInsecure
// ErrInvalidContext is returned by [Identity.Sign] for an empty, over-255-byte or reserved ("kolo-id/device-") context.
ErrInvalidContext = errors.New("koloid: invalid signing context")
// ErrInvalidIdentity is returned for a nil or zero Identity.
ErrInvalidIdentity = errors.New("koloid: invalid identity")
// ErrSavedNotSynced is returned by [Identity.Save] and [Identity.SaveNew] when the new key is in place but the directory sync failed.
ErrSavedNotSynced = keyfile.ErrSavedNotSynced
// ErrTempLeft is wrapped by [Identity.Save] and [Identity.SaveNew] when a temporary file could not be removed; the error text says whether the key was saved.
ErrTempLeft = keyfile.ErrTempLeft
// ErrNotDecodable is returned when decoding an Identity from text or JSON.
ErrNotDecodable = errors.New("koloid: identities cannot be decoded; use Load or FromSeed")
)var (
// ErrInvalidPhrase is returned for a nil, zero or cleared Phrase.
ErrInvalidPhrase = errors.New("koloid: invalid phrase")
// ErrPhraseLength is returned when the input is not 24 words or is over 1024 bytes.
ErrPhraseLength = errors.New("koloid: a phrase has 24 words")
// ErrPhraseChecksum is returned when the 24 words are in the list but their checksum does not match.
ErrPhraseChecksum = errors.New("koloid: phrase checksum does not match")
// ErrUnknownWord is matched by [UnknownWordError]; no error text holds a word of the input.
ErrUnknownWord = errors.New("koloid: unknown word in phrase")
// ErrNotEncodable is returned when encoding or decoding a Phrase as text or JSON.
ErrNotEncodable = errors.New("koloid: phrases cannot be encoded or decoded; use ParsePhrase")
)Functions
func SaveCert
func SaveCert(path string, c *DeviceCert) errorSaveCert atomically replaces path with the encoding of c, mode 0600, with the same directory checks as Identity.Save. Keep the certificate next to the device key, for example "device.cert" beside "device.key". It does not verify c.
func Verify
func Verify(pub ed25519.PublicKey, context string, msg, sig []byte) boolVerify reports whether sig is a valid signature of msg by pub under context. It never panics on untrusted input. Verify rejects small-order public keys, for which a signature can be forged without a private key.
func VerifyDevice
func VerifyDevice(c *DeviceCert, opts *VerifyOptions, context string, msg, sig []byte) errorVerifyDevice reports nil when sig is a signature of msg under context by a device of opts.Person, after DeviceCert.Verify. A context that starts with "kolo-id/device-" is reserved and is ErrInvalidArgument.
Types
type CertOffer
type CertOffer struct {
// contains filtered or unexported fields
}CertOffer is a certificate signed by its issuer that the device has not accepted yet.
func DecodeCertOffer
func DecodeCertOffer(b []byte) (*CertOffer, error)DecodeCertOffer decodes an offer written by CertOffer.Encode like DecodeDeviceCert; input over 450 bytes is refused.
func (CertOffer) Encode
func (o *CertOffer) Encode() []byteEncode returns the canonical encoding of o, at most 450 bytes; nil for a nil offer.
type DeviceCert
type DeviceCert struct {
// contains filtered or unexported fields
}DeviceCert says that a device key belongs to a person key; it is public, immutable and trusted only after VerifyDevice or DeviceCert.Verify.
func DecodeDeviceCert
func DecodeDeviceCert(b []byte) (*DeviceCert, error)DecodeDeviceCert decodes a certificate written by DeviceCert.Encode, checking structure but no signature. Input over 514 bytes is refused before parsing; every error wraps ErrInvalidCert.
func LoadCert
func LoadCert(path string) (*DeviceCert, error)LoadCert reads a certificate written by SaveCert with the checks of Load; the result is untrusted until VerifyDevice or DeviceCert.Verify. An empty or over-514-byte file is ErrInvalidKeyFile; bytes that do not decode are ErrInvalidCert.
func (DeviceCert) Approver
func (c *DeviceCert) Approver() boolApprover reports whether the device may certify and revoke ordinary devices without the phrase.
func (DeviceCert) Device
func (c *DeviceCert) Device() ed25519.PublicKeyDevice returns the certified device key, or nil for a nil certificate.
func (DeviceCert) Encode
func (c *DeviceCert) Encode() []byteEncode returns the canonical encoding of c, at most 256 bytes or 514 with a parent; nil for a nil certificate.
func (DeviceCert) ExpiresAt
func (c *DeviceCert) ExpiresAt() time.TimeExpiresAt returns the expiry in whole seconds, or the zero time for never; a fractional expiry given to the issuer was truncated, so it came up to 1 s early.
func (DeviceCert) IssuedAt
func (c *DeviceCert) IssuedAt() time.TimeIssuedAt returns the issue time in whole seconds; it is informational, because a thief can back-date it.
func (DeviceCert) Issuer
func (c *DeviceCert) Issuer() ed25519.PublicKeyIssuer returns the key that claims to have signed the certificate, an unverified claim that is never a trust anchor; nil for a nil certificate.
func (DeviceCert) Person
func (c *DeviceCert) Person() ed25519.PublicKeyPerson returns the person key the certificate claims, an unverified claim that is never a trust anchor; nil for a nil certificate.
func (DeviceCert) Serial
func (c *DeviceCert) Serial() uint64Serial returns the serial chosen by the issuer; a revocation covers the serials up to its UpToSerial.
func (DeviceCert) Verify
func (c *DeviceCert) Verify(opts *VerifyOptions) errorVerify checks that c is valid for opts.Person at opts.Now: structure, person, expiry, revocation and every signature. It never panics.
type Identity
type Identity struct {
// contains filtered or unexported fields
}Identity is a Kolo node identity; hold it as *Identity. A *Identity prints and encodes as its public key; the seed never appears in any output. A plain Identity value prints an opaque code address and should not be logged; log the *Identity.
func FromSeed
func FromSeed(seed []byte) (*Identity, error)FromSeed creates an Identity from a 32-byte Ed25519 seed. It copies what it needs and leaves seed untouched; the caller should clear seed when done.
func Generate
func Generate() (*Identity, error)Generate creates a new random Identity.
func Load
func Load(path string) (*Identity, error)Load reads an Identity written by Identity.Save or Identity.SaveNew. The path must end in a file name that names a regular 32-byte file, not a symlink (ErrInvalidKeyFile). It never blocks on a FIFO or device. The key file and its directory must belong to the effective user and have no group or other bits, or Load returns ErrInsecureKeyFile. The checks, which are stricter on Linux and macOS and absent on non-unix systems, are listed in docs/guide.md.
func (Identity) AcceptDeviceCert
func (i *Identity) AcceptDeviceCert(o *CertOffer, person ed25519.PublicKey) (*DeviceCert, error)AcceptDeviceCert completes o into a certificate signed by the device key i, which proves the device holds it; person comes from the linking exchange, never from o.
func (Identity) Clear
func (i *Identity) Clear()Clear erases the private key that i holds; i is invalid afterwards and so is every copy of it. It is not safe to call while another goroutine uses i, and it cannot erase copies made by the Go runtime or the standard library.
func (Identity) Format
func (i *Identity) Format(f fmt.State, _ rune)Format prints Identity.String for every verb.
func (Identity) GoString
func (i *Identity) GoString() stringGoString returns the same as Identity.String.
func (Identity) LogValue
func (i *Identity) LogValue() slog.ValueLogValue makes log/slog print only the public key.
func (Identity) MarshalJSON
func (i *Identity) MarshalJSON() ([]byte, error)MarshalJSON returns the public key as a hex JSON string.
func (Identity) MarshalText
func (i *Identity) MarshalText() ([]byte, error)MarshalText returns the public key as hex.
func (Identity) OfferDeviceCert
func (i *Identity) OfferDeviceCert(device ed25519.PublicKey, o *IssueOptions) (*CertOffer, error)OfferDeviceCert signs an offer that makes device a device of a person, with i as the person key (o.Parent nil) or an approver (o.Parent its certificate). The device completes the certificate with Identity.AcceptDeviceCert.
func (Identity) PublicKey
func (i *Identity) PublicKey() ed25519.PublicKeyPublicKey returns the public key, or nil for a nil or zero Identity.
func (Identity) PublicKeyString
func (i *Identity) PublicKeyString() stringPublicKeyString returns the public key as hex.
func (Identity) RevokeDevice
func (i *Identity) RevokeDevice(o *RevokeOptions) (*Revocation, error)RevokeDevice signs a revocation of o.Device with i, the person key, the device itself or an approver device (o.SignerCert, o.Target).
func (Identity) Save
func (i *Identity) Save(path string) errorSave atomically replaces path with the 32-byte seed, mode 0600 (on Windows, the directory's access rules). A symlink at path is replaced, not followed, and a missing parent directory is created with mode 0700. The directory is checked like in Load before anything is written. If the temporary file cannot be removed, the error wraps ErrTempLeft; the key was not saved.
func (Identity) SaveNew
func (i *Identity) SaveNew(path string) errorSaveNew is like Identity.Save but never replaces anything at path, not even a dangling symlink: it returns an error wrapping io/fs.ErrExist instead. It needs a filesystem with hard links. If the temporary file cannot be removed, the error wraps ErrTempLeft and says whether the key was saved.
func (Identity) Sign
func (i *Identity) Sign(context string, msg []byte) ([]byte, error)Sign returns the Ed25519ctx (RFC 8032) signature of msg under context; contexts that start with "kolo-id/device-" are reserved and refused.
func (Identity) String
func (i *Identity) String() stringString returns the public key, never the private key.
func (Identity) UnmarshalJSON
func (i *Identity) UnmarshalJSON([]byte) errorUnmarshalJSON always returns ErrNotDecodable, so JSON never yields an empty Identity.
func (Identity) UnmarshalText
func (i *Identity) UnmarshalText([]byte) errorUnmarshalText always returns ErrNotDecodable.
type IssueOptions
type IssueOptions struct {
// Parent is nil when the signing identity is the person key; otherwise the signer's own approver certificate.
Parent *DeviceCert
// Serial is at least 1 and chosen by the caller; the library keeps no state.
Serial uint64
// IssuedAt is zero for now; it is truncated to whole seconds.
IssuedAt time.Time
// ExpiresAt is zero for never, otherwise after IssuedAt; it is truncated to whole seconds, so a fraction expires up to 1 s early.
ExpiresAt time.Time
// Approver gives the device the right to certify and revoke ordinary devices; only the person key may set it.
Approver bool
}IssueOptions are the choices of Identity.OfferDeviceCert.
type Phrase
type Phrase struct {
// contains filtered or unexported fields
}Phrase is a 24-word recovery phrase (BIP-39); hold it as *Phrase, which prints as redacted and never encodes.
func GeneratePhrase
func GeneratePhrase() (*Phrase, error)GeneratePhrase creates a phrase from 256 bits of crypto/rand (BIP-39, section "Generating the mnemonic").
func ParsePhrase
func ParsePhrase(s string) (*Phrase, error)ParsePhrase parses 24 words separated by spaces, tabs or line breaks, ignoring ASCII case; an error never holds a word.
func ParseWords
func ParseWords(words []string) (*Phrase, error)ParseWords is like ParsePhrase for words already split; a word holding a space is unknown.
func (Phrase) Clear
func (p *Phrase) Clear()Clear erases the entropy held by p, which is invalid afterwards; it is not safe to call while another goroutine uses p.
func (Phrase) Format
func (p *Phrase) Format(f fmt.State, _ rune)Format prints Phrase.String for every verb.
func (Phrase) LogValue
func (p *Phrase) LogValue() slog.ValueLogValue makes log/slog print Phrase.String.
func (Phrase) MarshalJSON
func (p *Phrase) MarshalJSON() ([]byte, error)MarshalJSON always returns ErrNotEncodable.
func (Phrase) MarshalText
func (p *Phrase) MarshalText() ([]byte, error)MarshalText always returns ErrNotEncodable.
func (Phrase) Person
func (p *Phrase) Person() (*Identity, error)Person returns the person key at m/1802464367'/0'/0' under the phrase's BIP-39 seed; it fails under GODEBUG=fips140=only.
func (Phrase) String
func (p *Phrase) String() stringString returns "koloid.Phrase{redacted}", never a word.
func (Phrase) UnmarshalJSON
func (p *Phrase) UnmarshalJSON([]byte) errorUnmarshalJSON always returns ErrNotEncodable.
func (Phrase) UnmarshalText
func (p *Phrase) UnmarshalText([]byte) errorUnmarshalText always returns ErrNotEncodable.
func (Phrase) Words
func (p *Phrase) Words() []stringWords returns the 24 words in a fresh slice, or nil for an invalid phrase; Go strings cannot be erased, so show them and drop them.
type Revocation
type Revocation struct {
// contains filtered or unexported fields
}Revocation is public, immutable and permanent. The person key or the device itself voids a device's certificates up to a serial; an approver voids one ordinary-device certificate, named by the hash of its body and parent.
func DecodeRevocation
func DecodeRevocation(b []byte) (*Revocation, error)DecodeRevocation decodes a revocation written by Revocation.Encode, checking structure but no signature. Input over 472 bytes is refused before parsing; every error wraps ErrInvalidRevocation.
func (Revocation) Device
func (r *Revocation) Device() ed25519.PublicKeyDevice returns the revoked device key, or nil for a nil revocation.
func (Revocation) Encode
func (r *Revocation) Encode() []byteEncode returns the canonical encoding of r, at most 472 bytes; nil for a nil revocation.
func (Revocation) Person
func (r *Revocation) Person() ed25519.PublicKeyPerson returns the person key the revocation is for, or nil for a nil revocation.
func (Revocation) Signer
func (r *Revocation) Signer() ed25519.PublicKeySigner returns the approver device key that signed an approver-form revocation, so an application can drop the records of a retired approver; nil when the person key or the device itself signed.
func (Revocation) TargetHash
func (r *Revocation) TargetHash() []byteTargetHash returns the hash of the body, issuer and parent of the certificate an approver revoked, never of its signatures; nil when the person key or the device itself signed.
func (Revocation) UpToSerial
func (r *Revocation) UpToSerial() uint64UpToSerial returns the highest serial the revocation voids; for an approver it is the serial of the one certificate it names.
func (Revocation) Verify
func (r *Revocation) Verify(opts *VerifyOptions, target *DeviceCert) errorVerify checks r for opts.Person: structure, signatures and the right of the signer to revoke target, which an approver-signed r needs and must name by hash; opts.Now is not used. Errors: ErrInvalidArgument, ErrInvalidRevocation, ErrCertSignature.
type RevokeOptions
type RevokeOptions struct {
Person ed25519.PublicKey
Device ed25519.PublicKey
// UpToSerial is at least 1 for the person key or the device itself, and voids the certificates of Device up to it; math.MaxUint64 burns the key.
// An approver signs for one certificate: UpToSerial is zero or Target's serial.
UpToSerial uint64
// SignerCert is the signing device's approver certificate; nil when the signer is the person key or the device itself.
SignerCert *DeviceCert
// Target is the ordinary-device certificate an approver revokes, required with SignerCert and nil otherwise.
Target *DeviceCert
// At is zero for now; it is truncated to whole seconds and never decides validity.
At time.Time
}RevokeOptions are the choices of Identity.RevokeDevice.
type UnknownWordError
type UnknownWordError struct{ Position int }UnknownWordError says which word of the input (1-based position) is not in the word list; it matches ErrUnknownWord.
func (UnknownWordError) Error
func (e *UnknownWordError) Error() stringError reports the position of the unknown word and never the word.
func (UnknownWordError) Is
func (e *UnknownWordError) Is(target error) boolIs reports whether target is ErrUnknownWord.
type VerifyOptions
type VerifyOptions struct {
// Person is required: the person key the caller expects. A certificate never names its own trust anchor.
Person ed25519.PublicKey
// Now is the time for expiry checks; zero is time.Now().
Now time.Time
// Revocations are the records the caller holds; invalid or unrelated ones are ignored. Keep only records that passed [Revocation.Verify], and bound the slice.
Revocations []*Revocation
}VerifyOptions are the expectations of a verifier.
Good to know
Limits
- Seed: exactly 32 bytes.
FromSeedreturns an error for any other length. - Key file: a regular file of exactly 32 bytes, or
LoadreturnsErrInvalidKeyFile. - Signing context: 1 to 255 bytes.
SignreturnsErrInvalidContextoutside that range, andVerifyreturns false. - Public key: 32 bytes.
Verifyreturns false for any other size. - Phrase: exactly 24 words of the BIP-39 English list, ASCII only.
ParsePhraserefuses more than 1024 bytes of input (a phrase is 215 bytes at most). - Encoded sizes: a certificate at most 256 bytes, or 514 with an approver parent; an offer at most 450 (192 without a parent); a revocation at most 472 (182 for the person key or the device itself). A certificate file holds 1 to 514 bytes. These are the true maxima of the layouts, and decoders refuse larger input before parsing.
- Serial: at least 1. Times in a certificate are whole Unix seconds, and an
expiresAtof 0 means never. VerifyDevicechecks at most 4 certificate signatures and 1 message signature. For the revocations it indexes the list once, so the work is linear in the list, which the caller bounds.SaveandSaveNewwrite the key file with mode 0600 and create a missing parent directory with mode 0700. On Windows the file takes the access rules of its directory.
Security
- Signatures use Ed25519ctx (RFC 8032).
Verifyreturns false on any bad input and never panics. It rejects small-order public keys (all 14 encodings Go accepts), for which a signature can be forged without a private key.- The seed is never printed, logged or serialized.
UnmarshalJSONandUnmarshalTextalways returnErrNotDecodable; useLoadorFromSeed. SaveNewnever replaces anything at the path, not even a dangling symlink. A second process that races to create the key, or a dangling symlink to an unmounted volume, makes it fail instead of destroying a key.Savereplaces a symlink at the path instead of following it. The path must end in a file name.Loadrefuses a symlink at the path, a file that is not regular, and never blocks on a FIFO or a device.- On unix,
LoadreturnsErrInsecureKeyFilewhen the key file or its directory, andSaveandSaveNewwhen the directory, is not owned by the effective user or has group or other mode bits set. On Linux a POSIX ACL shows in the group bits, so it is caught. On macOS, ACL entries that allow access and volumes mounted to ignore ownership are refused too. - A nil or zero
IdentityreturnsErrInvalidIdentityfromSign,SaveandSaveNewinstead of panicking. - Contexts that start with
kolo-id/device-are reserved for certificates and revocations (kolo-id/device-link/v0,kolo-id/device-accept/v0andkolo-id/device-revoke/v0).SignreturnsErrInvalidContextfor them andVerifyDevicerefuses them, so no application signature can pass as a certificate or a revocation. - An approver device can certify and revoke ordinary devices, but not approvers; an ordinary device can only sign as itself and revoke itself. A certificate alone is public and signs nothing.
- A leaked phrase cannot be repaired inside the same identity: create a new phrase. A stolen approver stays able to certify ordinary devices until the person revokes it with the phrase, and revoking it also voids the legitimate devices it certified.
Identity.ClearandPhrase.Clearerase the key material the library holds. This is best effort: copies inside the Go runtime and the standard library are not reachable.- The embedded BIP-39 word list is pinned by its SHA-256 and checked at
first use, and the official BIP-39 and SLIP-0010 test vectors run with the
tests. Their sources, commits, hashes and licenses are in
third_party/licenses/NOTICE.md.
Known limits
- Experimental. The API may change before v1.0.0.
- FreeBSD and illumos: NFSv4 ACLs (as on ZFS) are not checked.
- Non-unix systems check neither owner nor mode bits.
- Systems other than Linux and macOS reopen the key directory by path, so a
FIFO swapped in at that moment can still block, and a symlink inside the
directory may be followed (
Loadthen rejects it). - On Linux and macOS the directory is reached through
/proc/self/fdor/dev/fd. If that is unavailable,Load,SaveandSaveNewfail withErrInsecureKeyFile. SaveNewneeds a filesystem with hard links.Phrase.Personreturns an error underGODEBUG=fips140=only, where Go refuses the salt that BIP-39 fixes and the SLIP-0010 master key.- The library keeps no state: revocations protect only the verifiers that hold them, so applications must carry them to every verifier.
Errors
| Error | Message |
|---|---|
ErrCertExpired | koloid: device certificate expired |
ErrCertPerson | koloid: device certificate is for another person |
ErrCertRevoked | koloid: device certificate revoked |
ErrCertSignature | koloid: device certificate signature does not verify |
ErrInsecureKeyFile | koloid: key file or its directory is accessible to others or owned by another user |
ErrInvalidArgument | koloid: invalid argument |
ErrInvalidCert | koloid: invalid device certificate |
ErrInvalidContext | koloid: invalid signing context |
ErrInvalidIdentity | koloid: invalid identity |
ErrInvalidKeyFile | koloid: invalid key file |
ErrInvalidPhrase | koloid: invalid phrase |
ErrInvalidRevocation | koloid: invalid revocation |
ErrNotApprover | koloid: signer is not an approver |
ErrNotDecodable | koloid: identities cannot be decoded; use Load or FromSeed |
ErrNotEncodable | koloid: phrases cannot be encoded or decoded; use ParsePhrase |
ErrPhraseChecksum | koloid: phrase checksum does not match |
ErrPhraseLength | koloid: a phrase has 24 words |
ErrSavedNotSynced | koloid: key file saved but directory sync failed |
ErrTempLeft | koloid: temporary key file left on disk |
ErrUnknownWord | koloid: unknown word in phrase |
Test errors with errors.Is, since most come wrapped with the path or a
cause. SaveNew on an existing path matches fs.ErrExist, and Load of a
missing file matches os.ErrNotExist. When only the final directory sync
fails, the error wraps ErrSavedNotSynced and the new key is in place. When
a temporary file cannot be removed, the error wraps ErrTempLeft, names the
file and says whether the key was saved. The phrase and certificate errors
never hold input bytes, and an option error from OfferDeviceCert or
RevokeDevice matches both ErrInvalidArgument and ErrInvalidCert or
ErrInvalidRevocation.
References
- RFC 8032, Edwards-Curve Digital Signature Algorithm (EdDSA) (Informational, January 2017).
- Takes: Ed25519ctx (5.1) with a context of 1 to 255 bytes, and rejection of small-order public keys.
- Not implemented: Ed25519ph and Ed448.
- BIP-39, Mnemonic code for generating deterministic keys (Status: Deployed).
- Takes: the English word list, 24 words with an 8-bit checksum, and the PBKDF2-HMAC-SHA512 seed.
- Not implemented: other word lists and lengths, the passphrase, and NFKD normalization (only ASCII is accepted).
- SLIP-0010, Universal private key derivation from master private key (Standard, Final).
- Takes: Ed25519 derivation at the hardened path m/1802464367'/0'/0'.
- Not implemented: other curves; Ed25519 has no non-hardened children.
- BIP-43, Purpose Field for Deterministic Wallets (Status: Deployed).
- Takes: a first path element that names the purpose, here the ASCII bytes of "kolo".
- Not implemented: any wallet hierarchy below it.
- RFC 8018, PKCS #5: Password-Based Cryptography Specification Version 2.1 (Informational, January 2017).
- Takes: PBKDF2, as BIP-39 uses it.
- Not implemented: nothing else from it.