Um nó do Kolo é identificado pela sua chave pública Ed25519. A kolo-id cria e guarda esse par de chaves, assina mensagens com Ed25519ctx da RFC 8032 e verifica assinaturas de outros peers. Todas as outras bibliotecas do Kolo pegam suas identidades daqui. Ela não decide em quais chaves confiar.
Uma pessoa pode usar vários dispositivos. Uma frase de recuperação de 24 palavras dá uma chave de pessoa (com BIP-39 e SLIP-0010), e cada dispositivo guarda a sua própria chave aleatória e um certificado assinado por essa chave de pessoa, então um dispositivo perdido é revogado sem perder a identidade.
Chaves, assinatura e verificação
Só a semente é guardada. Uma assinatura só confere com o contexto em que foi feita.
- Generate pega 32 bytes aleatórios: a semente.
- A semente dá a chave privada (64 bytes, na memória) e a chave pública (32 bytes). A chave pública é a identidade, escrita como 64 caracteres hexadecimais.
- Sign usa Ed25519ctx: a chave privada assina a mensagem com um contexto de 1 a 255 bytes e dá uma assinatura de 64 bytes.
- Verify recebe a chave pública, o mesmo contexto, a mensagem e a assinatura, e retorna true.
- Retorna false com outro contexto, com uma chave pública que não tenha 32 bytes ou com uma chave de ordem pequena.
- Save grava só a semente, em um arquivo com modo 0600. Load a lê de volta e gera o mesmo par de chaves.
Instalação
go get github.com/ciranda-dev/kolo-idÉ Go puro, sem cgo. As dependências são golang.org/x/sys, para o openat
via libc no macOS, e a kolo-codec, para a codificação dos
certificados.
Início rápido
Crie uma identidade, assine sob um contexto e depois salve e carregue essa identidade em um diretório temporário.
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()))
}O programa imprime a chave pública, valid: true, other context: false e
same key: true. Um nó real chama Load primeiro e, quando o erro
corresponde a os.ErrNotExist, chama Generate e SaveNew uma única vez.
Assim ele mantém a mesma chave pública entre reinicializações.
Frase de recuperação e dispositivos
A chave de pessoa nunca fica em um dispositivo. As 24 palavras dão a chave
de pessoa, a chave de pessoa certifica o primeiro dispositivo como
aprovador, e um aprovador adiciona dispositivos comuns sem as palavras. Quem
verifica sempre informa a pessoa que espera. Este programa,
examples/devices no repositório, percorre o fluxo inteiro em um diretório
temporário e nunca imprime a frase.
// 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
}O programa imprime a chave de pessoa e words: 24, depois
phone message: <nil>, after revoking: true e
restored the same person: true.
Frase de recuperação
GeneratePhrasecria 24 palavras da lista em inglês do BIP-39 comcrypto/rand: 256 bits de entropia e um checksum de 8 bits. MostreWords()uma única vez, deixe a pessoa anotar as palavras, depois chameClear()e descarte as strings. A biblioteca nunca guarda, imprime nem mostra uma frase de novo.ParsePhraselê 24 palavras separadas por espaços, tabs ou quebras de linha, sem diferenciar maiúsculas, eParseWordsfaz o mesmo com uma lista já separada. Só ASCII é aceito, sem normalização Unicode, e uma entrada com mais de 1024 bytes é recusada.Phrase.Personderiva a chave de pessoa: a seed BIP-39 com passphrase vazia (2048 rodadas de PBKDF2-HMAC-SHA512) e depois SLIP-0010 para Ed25519 no caminho endurecidom/1802464367'/0'/0'. O caminho nunca muda, e as chaves de dispositivo nunca são derivadas da frase. Não existe passphrase do BIP-39.- Um erro de digitação aleatório em cada 256 passa no checksum e dá outra
identidade válida, então uma tela de restauração deve mostrar a chave de
pessoa (
PublicKeyString) para a pessoa conferir. - Um
*Phraseé impresso comokoloid.Phrase{redacted}com qualquer verbo dofmte nolog/slog, e nunca é codificado (ErrNotEncodable). Os erros dizem a posição de uma palavra errada, nunca a palavra:ErrPhraseLength,ErrUnknownWord(um*UnknownWordError),ErrPhraseChecksumeErrInvalidPhrase.
Certificados de dispositivo
- Uma cadeia é no máximo pessoa, aprovador, dispositivo. A chave de pessoa certifica dispositivos aprovadores; um aprovador certifica dispositivos comuns e não pode certificar outro aprovador.
- Um certificado é feito em dois passos. Quem emite assina uma oferta com
OfferDeviceCert, e o dispositivo a completa comAcceptDeviceCert, o que prova que ele tem a própria chave.IssueOptions.Serialé pelo menos 1 e é escolhido por quem chama, porque a biblioteca não guarda estado. DeviceCert.Person()eDeviceCert.Issuer()são afirmações dentro de bytes não verificados. Fixe a chave de pessoa no seu próprio estado e nunca a tire de um certificado que você está verificando.VerifyDevice(cert, opts, context, msg, sig)verifica que uma mensagem foi assinada por um dispositivo deopts.Person: estrutura, pessoa, validade, revogação e todas as assinaturas. Não existe modo sem certificado.DeviceCert.Verifyfaz as mesmas verificações sem mensagem.EncodeeDecodeCertOffer,DecodeDeviceCerteDecodeRevocationlevam os objetos pela rede na codificação da kolo-codec. Os decodificadores recusam uma entrada grande demais antes de analisá-la e não verificam assinaturas.SaveCerteLoadCertguardam o certificado ao lado da chave do dispositivo, por exemplodevice.keyedevice.cert, com modo 0600 e as mesmas verificações de diretório deSaveeLoad. Um certificado carregado é uma entrada não confiável: verifique-o antes de usar.
Revogações
RevokeDevicetem duas formas. A chave de pessoa ou o próprio dispositivo revogam por número de série: todo certificado dessa chave atéUpToSerialfica anulado, emath.MaxUint64queima a chave para sempre. Um aprovador revoga um certificado exato de um dispositivo comum, indicado emRevokeOptions.Target; o registro assinado leva o SHA-256 dele (Revocation.TargetHash), eRevocation.Signerdevolve o aprovador que o assinou.- O hash cobre o corpo, o emissor e o pai do certificado, mas não as assinaturas, porque assinaturas Ed25519 não são únicas. A revogação de um aprovador não pode queimar uma chave nem cobrir um certificado que ainda não existe. Para voltar atrás, basta um certificado novo para a mesma chave de dispositivo com um número de série novo.
- Revogar um aprovador, o que só a chave de pessoa pode fazer, também anula todos os certificados que ele emitiu.
- As revogações são permanentes. Um registro assinado por um aprovador é
julgado pela estrutura e pelas assinaturas do certificado do signatário,
não pela validade desse signatário nem por uma revogação posterior dele.
Guarde todo registro que passou em
Revocation.Verifye passe-os emVerifyOptions.Revocations: quem verifica sem guardar nenhum não enxerga um dispositivo revogado.
Referência da API
A referência da API é gerada a partir do código Go e está em inglês.
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.
Variáveis
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")
)Funções
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.
Tipos
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.
Bom saber
Limites
- Seed: exatamente 32 bytes.
FromSeedretorna um erro para qualquer outro tamanho. - Arquivo de chave: um arquivo regular de exatamente 32 bytes, senão
LoadretornaErrInvalidKeyFile. - Contexto de assinatura: de 1 a 255 bytes. Fora dessa faixa,
SignretornaErrInvalidContexteVerifyretorna false. - Chave pública: 32 bytes.
Verifyretorna false para qualquer outro tamanho. - Frase: exatamente 24 palavras da lista em inglês do BIP-39, só ASCII.
ParsePhraserecusa mais de 1024 bytes de entrada (uma frase tem no máximo 215 bytes). - Tamanhos codificados: um certificado no máximo 256 bytes, ou 514 com um pai aprovador; uma oferta no máximo 450 (192 sem pai); uma revogação no máximo 472 (182 para a chave de pessoa ou o próprio dispositivo). Um arquivo de certificado tem de 1 a 514 bytes. São os máximos reais dos formatos, e os decodificadores recusam uma entrada maior antes de analisá-la.
- Número de série: pelo menos 1. Os horários de um certificado são segundos
Unix inteiros, e um
expiresAtigual a 0 significa nunca. VerifyDeviceverifica no máximo 4 assinaturas de certificado e 1 assinatura de mensagem. Para as revogações ela indexa a lista uma vez, então o trabalho é linear na lista, que quem chama limita.SaveeSaveNewgravam o arquivo de chave com modo 0600 e criam o diretório pai, se ele não existir, com modo 0700. No Windows o arquivo herda as regras de acesso do seu diretório.
Segurança
- As assinaturas usam Ed25519ctx (RFC 8032).
Verifyretorna false para qualquer entrada inválida e nunca entra em pânico. Ela rejeita chaves públicas de ordem pequena (todas as 14 codificações que o Go aceita), para as quais dá para forjar uma assinatura sem a chave privada.- A seed nunca é impressa, registrada em log nem serializada.
UnmarshalJSONeUnmarshalTextsempre retornamErrNotDecodable; useLoadouFromSeed. SaveNewnunca substitui nada no caminho, nem mesmo um symlink quebrado. Se um segundo processo disputar a criação da chave, ou se houver um symlink quebrado para um volume não montado, a função falha em vez de destruir uma chave.Savesubstitui um symlink no caminho em vez de segui-lo. O caminho precisa terminar em um nome de arquivo.Loadrecusa um symlink no caminho e um arquivo que não seja regular, e nunca fica bloqueada em um FIFO ou em um dispositivo.- Em sistemas unix,
LoadretornaErrInsecureKeyFilequando o arquivo de chave ou o seu diretório, eSaveeSaveNewquando o diretório, não pertence ao usuário efetivo ou tem bits de permissão de grupo ou de outros ativados. No Linux uma ACL POSIX aparece nos bits de grupo, então ela é detectada. No macOS, entradas de ACL que liberam acesso e volumes montados para ignorar o dono também são recusados. - Uma
Identitynil ou zerada fazSign,SaveeSaveNewretornaremErrInvalidIdentityem vez de entrar em pânico. - Os contextos que começam com
kolo-id/device-são reservados para certificados e revogações (kolo-id/device-link/v0,kolo-id/device-accept/v0ekolo-id/device-revoke/v0).SignretornaErrInvalidContextpara eles eVerifyDeviceos recusa, então nenhuma assinatura de uma aplicação pode se passar por um certificado ou uma revogação. - Um dispositivo aprovador pode certificar e revogar dispositivos comuns, mas não aprovadores; um dispositivo comum só pode assinar como ele mesmo e revogar a si mesmo. Um certificado sozinho é público e não assina nada.
- Uma frase vazada não pode ser consertada dentro da mesma identidade: crie uma frase nova. Um aprovador roubado continua podendo certificar dispositivos comuns até a pessoa revogá-lo com a frase, e revogá-lo também anula os dispositivos legítimos que ele certificou.
Identity.ClearePhrase.Clearapagam o material de chave que a biblioteca guarda. É o melhor possível: cópias dentro do runtime do Go e da biblioteca padrão não podem ser alcançadas.- A lista de palavras do BIP-39 embutida é fixada pelo seu SHA-256 e
verificada no primeiro uso, e os vetores de teste oficiais do BIP-39 e do
SLIP-0010 rodam com os testes. Fontes, commits, hashes e licenças estão em
third_party/licenses/NOTICE.md.
Limites conhecidos
- Experimental. A API pode mudar antes da v1.0.0.
- FreeBSD e illumos: ACLs NFSv4 (como no ZFS) não são verificadas.
- Sistemas que não são unix não verificam nem o dono nem os bits de permissão.
- Sistemas que não são Linux nem macOS reabrem o diretório da chave pelo
caminho. Assim, um FIFO trocado nesse instante ainda pode bloquear, e um
symlink dentro do diretório pode ser seguido (
Loadentão o rejeita). - No Linux e no macOS o diretório é acessado por
/proc/self/fdou/dev/fd. Se eles não estiverem disponíveis,Load,SaveeSaveNewfalham comErrInsecureKeyFile. SaveNewprecisa de um sistema de arquivos com hard links.Phrase.Personretorna um erro comGODEBUG=fips140=only, em que o Go recusa o salt que o BIP-39 fixa e a chave mestra do SLIP-0010.- A biblioteca não guarda estado: as revogações protegem só quem verifica e as tem, então as aplicações precisam levá-las a cada um.
Erros
| Erro | Mensagem |
|---|---|
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 |
Teste os erros com errors.Is, porque a maioria vem envolvida com o caminho
ou com uma causa. SaveNew em um caminho que já existe corresponde a
fs.ErrExist, e Load de um arquivo que não existe corresponde a
os.ErrNotExist. Quando só a sincronização final do diretório falha, o erro
envolve ErrSavedNotSynced e a nova chave já está no lugar. Quando um
arquivo temporário não pode ser removido, o erro envolve ErrTempLeft,
informa o nome do arquivo e diz se a chave foi salva. Os erros da frase e
dos certificados nunca contêm bytes da entrada, e um erro de opção de
OfferDeviceCert ou RevokeDevice corresponde a ErrInvalidArgument e
também a ErrInvalidCert ou ErrInvalidRevocation.
Referências
- RFC 8032, Edwards-Curve Digital Signature Algorithm (EdDSA) (Informational, January 2017).
- Usa: Ed25519ctx (5.1) com um contexto de 1 a 255 bytes, e a rejeição de chaves públicas de ordem pequena.
- Não implementa: Ed25519ph e Ed448.
- BIP-39, Mnemonic code for generating deterministic keys (Status: Deployed).
- Usa: a lista de palavras em inglês, 24 palavras com uma soma de verificação de 8 bits e a seed PBKDF2-HMAC-SHA512.
- Não implementa: outras listas de palavras e outros tamanhos, a senha opcional (passphrase) e a normalização NFKD (só ASCII é aceito).
- SLIP-0010, Universal private key derivation from master private key (Standard, Final).
- Usa: a derivação de Ed25519 no caminho endurecido m/1802464367'/0'/0'.
- Não implementa: outras curvas; Ed25519 não tem filhos não endurecidos.
- BIP-43, Purpose Field for Deterministic Wallets (Status: Deployed).
- Usa: um primeiro elemento do caminho que nomeia o propósito, aqui os bytes ASCII de "kolo".
- Não implementa: qualquer hierarquia de carteira abaixo dele.
- RFC 8018, PKCS #5: Password-Based Cryptography Specification Version 2.1 (Informational, January 2017).
- Usa: PBKDF2, como o BIP-39 o usa.
- Não implementa: nada mais dela.