enroll

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: Apache-2.0 Imports: 31 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package enroll holds the open formats and checks by which a bastion's enrollment service asks a managing system to admit its bloc worker, and then fetches and verifies the worker.

The enrollment address tells the service where the managing system's bus is and which subject roots to use, so nothing here names the managing system. The bootstrap signs an Attestation with the bastion's host key, and the service sends it as a Request through an admission account whose users it mints for itself. A person compares the host key's fingerprint and confirmation code with their terminal and approves. The service then reads the worker's manifest set and its chunks, checks the set through the sigchain package and the version floors, and checks every chunk against the manifest.

Index

Constants

View Source
const (
	ReleaseManifest = "manifest"
	ReleaseChunk    = "chunk"
	ReleaseStatus   = "status"
)

The operations of the release read, and the last token of its answer subject.

View Source
const (
	AdmissionIssuerSeed = "SAAEGUZRBQAHJJ46TIKTU36ADMGPIJ4O7SEVXVCQMPK37HS7NLH7HSYE5I" //nolint:gosec // published by design
	AdmissionIssuerKey  = "ABSA5NKTYCVPQ74ZYBOBA73Y3PGOZBAOJ2M6PCFA5JSDSZMKP527NDRN"
)

The admission issuer key. Every installation's admission account carries this key as its one user-signing key, and only as a scoped key, so any caller can mint a user for its own nkey and the bus replaces that user's permissions with the scope's template. The seed is published on purpose: the scope, not the seed, is what limits an admission user, and the account's own identity key stays secret.

View Source
const (
	// PendingBase and PendingMax bound the wait between asks while a
	// request is pending. The cap stays below the pending entry's
	// two-minute life, so a live bastion's entry never lapses.
	PendingBase = 10 * time.Second
	PendingMax  = time.Minute
	// FetchBase and FetchMax bound the wait between attempts to fetch the
	// worker binary.
	FetchBase = 5 * time.Second
	FetchMax  = 5 * time.Minute
	// RejectedPoll is the wait between asks once a person has rejected
	// the request, so a reopened request is seen without anyone touching
	// the bastion.
	RejectedPoll = 10 * time.Minute
	// Jitter is the share of each wait that is drawn at random. A wait
	// falls in (1-Jitter)·d to d, so jitter never takes it past its cap.
	Jitter = 0.2
)

The waits of the enrollment service.

View Source
const (
	// CodeAddressInvalid refuses an enrollment address that does not
	// decode or does not hold to its form.
	CodeAddressInvalid = "ENROLLMENT_ADDRESS_INVALID"
	// CodeSignatureInvalid refuses a signature in the chain that does not
	// verify, or a statement whose domain is wrong.
	CodeSignatureInvalid = sigchain.CodeSignatureInvalid
	// CodeSigningKeyRevoked refuses an online key that the newest
	// revocation statement lists.
	CodeSigningKeyRevoked = sigchain.CodeSigningKeyRevoked
	// CodeSigningKeyWindowInvalid refuses an online key whose statement
	// claims a window longer than 92 days.
	CodeSigningKeyWindowInvalid = sigchain.CodeSigningKeyWindowInvalid
	// CodeSignatureExpired refuses a signature whose window has ended by
	// this machine's clock.
	CodeSignatureExpired = sigchain.CodeSignatureExpired
	// CodeVersionBelowFloor refuses a manifest whose version is below one
	// of the three floors.
	CodeVersionBelowFloor = "WORKER_VERSION_BELOW_FLOOR"
	// CodeDigestMismatch refuses a chunk or a whole file that does not
	// match the manifest.
	CodeDigestMismatch = "WORKER_DIGEST_MISMATCH"
	// CodeTestRootsInRelease refuses to start the service in a binary
	// that trusts the public test root and carries a release version.
	CodeTestRootsInRelease = sigchain.CodeTestRootsInRelease
)

The codes of the enrollment service. Each names one reason the service stopped short of installing the worker, and the service reports the code to the managing system so a person can see it.

View Source
const (
	// CodeRequestInvalid refuses a request whose subject, size, encoding,
	// or canonical form is wrong, or whose attestation names one key
	// twice.
	CodeRequestInvalid = "JOIN_REQUEST_INVALID"
	// CodeWrongInstallation refuses an attestation that names another
	// installation, or an org other than the service that received it.
	CodeWrongInstallation = "JOIN_WRONG_INSTALLATION"
	// CodeBlocMismatch refuses a request whose subject and attestation
	// name different blocs.
	CodeBlocMismatch = "JOIN_BLOC_MISMATCH"
	// CodeBlocUnknown refuses a bloc the org doesn't hold. The service
	// asks again, because the bloc may be registered later.
	CodeBlocUnknown = "JOIN_BLOC_UNKNOWN"
	// CodeAttestationInvalid refuses a signature that doesn't verify, or
	// an attestation whose keys don't include the subject's key.
	CodeAttestationInvalid = "JOIN_ATTESTATION_INVALID"
	// CodeHostKeyUnsupported refuses a host key of a type other than
	// ssh-ed25519.
	CodeHostKeyUnsupported = "JOIN_HOST_KEY_UNSUPPORTED"
	// CodeWorkerKeyInUse refuses a worker key enrolled on another bloc.
	CodeWorkerKeyInUse = "JOIN_WORKER_KEY_IN_USE"
	// CodePendingFull refuses a request when its lane's cap is full and
	// nothing can be evicted.
	CodePendingFull = "JOIN_PENDING_FULL"
	// CodeRateLimited refuses a request that a rate limit held back.
	CodeRateLimited = "JOIN_RATE_LIMITED"
	// CodeAlreadyEnrolled refuses the install key once the worker has
	// taken its first full credential.
	CodeAlreadyEnrolled = "WORKER_ALREADY_ENROLLED"
	// CodeUnavailable refuses a request the managing system couldn't
	// decide on now. Its answer carries no detail.
	CodeUnavailable = "SERVICE_UNAVAILABLE"
	// CodeAnswerInvalid refuses, on the asking side, an answer that does
	// not decode, does not hold to its form, or names another request.
	CodeAnswerInvalid = "JOIN_ANSWER_INVALID"
)

The codes an admission request's answer may refuse with. The enrollment service reads them, and the managing system's join service answers with them.

View Source
const (
	// CodeReleaseSignatureExpired refuses a manifest request when the
	// managing system's newest signature set for its version has lapsed
	// by its own clock. The answer names the version and the end date.
	CodeReleaseSignatureExpired = "RELEASE_SIGNATURE_EXPIRED"
	// CodeReleaseVersionUnavailable refuses a request for a version other
	// than the one the answering copy runs.
	CodeReleaseVersionUnavailable = "RELEASE_VERSION_UNAVAILABLE"
	// CodeReleaseRateLimited refuses a request over a rate limit.
	CodeReleaseRateLimited = "RELEASE_RATE_LIMITED"
	// CodeReleaseRequestInvalid refuses a malformed request.
	CodeReleaseRequestInvalid = "RELEASE_REQUEST_INVALID"
	// CodeWorkerRevoked refuses a worker a person removed. It is the only
	// code that stops a fetch.
	CodeWorkerRevoked = "WORKER_REVOKED"
)

The codes a release read's answer may refuse with.

View Source
const (
	// MaxManifest bounds the manifest's bytes.
	MaxManifest = 256 << 10
	// MaxChunkSize bounds one chunk, so a chunk answer fits the bus's
	// payload limit with room to spare.
	MaxChunkSize = 512 << 10
	// DefaultChunkSize is the chunk size a release uses unless it names
	// another.
	DefaultChunkSize = 256 << 10
	// MaxChunks bounds the chunks of one file.
	MaxChunks = 2048
)

The bounds of a manifest.

View Source
const (
	ManifestFile      = "bloc-worker-manifest.json"
	ManifestSigFile   = "bloc-worker-manifest.json.sig"
	StatementFile     = "bloc-worker-signing-key.json"
	StatementSigFile  = "bloc-worker-signing-key.json.sig"
	RevocationFile    = "signing-key-revocation.json"
	RevocationSigFile = "signing-key-revocation.json.sig"
)

The six files of a manifest set, as a release carries them.

View Source
const (
	MaxReleaseRequest = 1 << 10
	MaxReleaseAnswer  = 1 << 20
	// StatusInterval is the least time between two status requests.
	StatusInterval = time.Minute
)

The bounds of the release read's messages. A chunk answer carries up to MaxChunkSize bytes in base64, which fits MaxReleaseAnswer.

View Source
const (
	AttestationDomain = "ocfp-bastion-join-attestation-v1"
	JoinNamespace     = "ocfp-bastion-join-v1"
)

The domain an attestation names and the SSHSIG namespace the host key signs it under.

View Source
const (
	MaxMessage          = 8 << 10
	MaxAttestation      = 2 << 10
	MaxRequestSignature = 2 << 10
	MaxCredential       = 4 << 10
)

The bounds of an admission message. MaxMessage bounds a request or an answer, MaxAttestation and MaxRequestSignature the two parts of a request, and MaxCredential the longest credential an answer carries.

View Source
const AddressVersion = 1

AddressVersion is the version of the enrollment address's payload.

View Source
const AdmissionUserLifetime = 10 * time.Minute

AdmissionUserLifetime is how long an admission user lives. The caller mints a new one for each connection, and the bus closes an admission connection long before the user lapses.

View Source
const CodeReleaseAnswerInvalid = "RELEASE_ANSWER_INVALID"

CodeReleaseAnswerInvalid refuses, on the asking side, a release answer that does not decode, does not hold to its form, or answers another request.

View Source
const ConfirmDomain = "ocfp-bastion-host-key-confirm-v1"

ConfirmDomain is the domain the confirmation code hashes before the host key's digest, so the code is never the digest itself.

View Source
const FingerprintPrefix = "SHA256:"

FingerprintPrefix begins every fingerprint, as ssh-keygen -l prints it.

View Source
const (
	FloorsFile = "floors.json"
)

The files of the trust directory.

View Source
const ManifestDomain = "bloc-worker-manifest-v1"

ManifestDomain is the domain the manifest names, which is also the namespace its signature is made under.

View Source
const MaxAddress = 2 << 10

MaxAddress bounds an enrollment address's length in bytes.

View Source
const MaxCAFile = 64 << 10

MaxCAFile bounds a saved ca.pem.

View Source
const MaxSmallFile = 64 << 10

MaxSmallFile bounds every read under the file rules except the worker binary's, which the manifest's size bounds.

View Source
const MinimumWorkerVersion = "0.0.0"

MinimumWorkerVersion is the embedded floor: no manifest below it installs, however it is signed.

View Source
const TrustDir = "/var/lib/bloc-worker-trust"

TrustDir is where a bastion keeps its floors and its newest revocation statement. Only the root steps write it, so the enrollment service can read the floors but never lower them.

Variables

View Source
var ErrBusRoots = errors.New("enroll: the bus's certificate holds to neither the system roots nor the fallback root")

ErrBusRoots is the error every refusal of the bus's certificate under a fallback root wraps: the chain verified neither to the system roots nor to the fallback root.

View Source
var ErrCAPin = errors.New("enroll: the bus's certificate does not hold to the CA pin")

ErrCAPin is the error every refusal of the bus's certificate under a CA pin wraps.

View Source
var ErrFileRule = errors.New("enroll: the file breaks the file rules")

ErrFileRule is the error every refusal under the file rules wraps. Each refusal names the path, so the log line that reports it does.

RefusalCodes are the codes a refused admission answer may carry.

ReleaseCodes are the codes a refused release answer may carry.

ServiceCodes are the codes of the enrollment service, in the order of the checks that produce them.

Functions

func CAPinOf

func CAPinOf(cert *x509.Certificate) string

CAPinOf returns the pin of a certificate: the lower-case hex SHA-256 of its DER bytes.

func CodeMatches

func CodeMatches(typed string, d [sha256.Size]byte) bool

CodeMatches reports whether typed, once normalized, is the confirmation code of the host key whose digest is d. It compares in constant time.

func CodeOf

func CodeOf(err error) string

CodeOf returns the code of the first Error in err's chain, or the empty string when err holds none.

func CompareVersions

func CompareVersions(a, b string) int

CompareVersions orders two valid versions by semantic version precedence, and returns -1, 0, or 1. A pre-release sorts below its release. It orders an invalid version below every valid one, so an invalid version never raises a floor.

func ConfirmationCode

func ConfirmationCode(d [sha256.Size]byte) string

ConfirmationCode returns the confirmation code of the host key whose digest is d. H is the SHA-256 of ConfirmDomain, one zero byte, and d. The code is the first 12 characters of the upper-case, unpadded RFC 4648 base32 of H, printed as three groups of four joined by hyphens.

func CreateExclusive

func CreateExclusive(dir, name string, data []byte, uid, gid int, mode os.FileMode) error

CreateExclusive creates name, a path relative to dir, as a fresh file under the file rules, writes data, and sets the owner and the mode on its own descriptor before it syncs and closes it. It refuses a name that already exists, of any kind. A uid or gid below zero leaves that id as the creating process's. When a step after the create fails, it removes the file it created.

func DecodeRelease

func DecodeRelease[T releaseMessage](body []byte) (T, error)

DecodeRelease reads a release message, refusing any bytes but the canonical form of a valid message. The answering side reads requests and refuses them with CodeReleaseRequestInvalid; the asking side reads answers and refuses them with CodeReleaseAnswerInvalid.

func DecodeRequest

func DecodeRequest(body []byte) (Request, Attestation, error)

DecodeRequest reads one request and returns it with its parsed attestation. Beyond DecodeEnvelope, it refuses a signature that is empty or longer than MaxRequestSignature and an attestation that ParseAttestation refuses. It checks no signature, which comes later in the check order.

func EncodeFloors

func EncodeFloors(f Floors) ([]byte, error)

EncodeFloors returns the floors' canonical bytes.

func EncodeRelease

func EncodeRelease[T releaseMessage](m T) ([]byte, error)

EncodeRelease returns a release message's canonical bytes. It refuses a request with CodeReleaseRequestInvalid and an answer with CodeReleaseAnswerInvalid.

func Fetch

func Fetch(ctx context.Context, bin Binary, src ChunkSource, target FetchTarget) error

Fetch brings target to bin's bytes, chunk by chunk from src. It keeps every leading chunk already in target that matches bin's chunk digest and fetches from the first that does not, so a fetch that stopped resumes where it left off. A fetched chunk whose length or digest is wrong is refused with CodeDigestMismatch and never written. When every chunk matches, Fetch checks the whole file's digest; on a mismatch it empties target and refuses with CodeDigestMismatch, so the next fetch starts over. A source error ends the fetch with that error, and target keeps every chunk written before it. Only a nil return means target holds the binary, which the caller may then mark ready.

func Fingerprint

func Fingerprint(d [sha256.Size]byte) string

Fingerprint returns the fingerprint of the host key whose digest is d, as ssh-keygen -l prints it: SHA256: and the unpadded standard base64 of d.

func HostKeyDigest

func HostKeyDigest(hostKey string) ([sha256.Size]byte, error)

HostKeyDigest returns D, the SHA-256 of an ssh-ed25519 host key's SSH wire-format blob, from the key as a .pub file or an authorized_keys line gives it. It refuses every other key type with CodeHostKeyUnsupported.

func MaxVersion

func MaxVersion(vs ...string) string

MaxVersion returns the highest of the valid versions given, or the empty string when none is valid.

func MintAdmissionUser

func MintAdmissionUser(account, userKey string, now time.Time) (string, error)

MintAdmissionUser returns the user JWT with which the holder of userKey connects to the admission account, signed with the published issuer key and naming account as its issuer account. The user is scoped, so it carries no permission or limit of its own, and the bus grants it only what the scope's template grants. It expires AdmissionUserLifetime after now.

func NormalizeCode

func NormalizeCode(typed string) (string, error)

NormalizeCode returns a typed confirmation code in its bare form of 12 characters. It drops ASCII spaces and hyphens, upper-cases ASCII letters, and reads 0 as O and 1 as I. It reads the input byte by byte, so a tab, a non-ASCII space, or a letter that Unicode folds into the alphabet is refused. It also refuses what is then not exactly 12 characters of the base32 alphabet.

func OpenNoFollow

func OpenNoFollow(dir, name string, limit int64) (*os.File, int64, error)

OpenNoFollow opens name, a path relative to dir, for reading under the file rules. It opens dir and every component without following a link, refuses anything but a regular file at the end, and refuses a file longer than limit. The caller closes the file. Every refusal wraps ErrFileRule and names the path.

func ParseFingerprint

func ParseFingerprint(fp string) ([sha256.Size]byte, error)

ParseFingerprint returns the digest a fingerprint encodes. It takes only the exact form Fingerprint prints.

func ReadNoFollow

func ReadNoFollow(dir, name string, limit int64) ([]byte, error)

ReadNoFollow reads name, a path relative to dir, under the file rules, and refuses more than limit bytes even when the file grows while it reads.

func RequestID

func RequestID(attestation []byte) string

RequestID returns the id of the request that carries attestation, the lower-case hex of the SHA-256 of its bytes.

func StopsFetch

func StopsFetch(err error) bool

StopsFetch reports whether err ends a worker fetch for good. Only CodeWorkerRevoked does. Every other error, coded or not, including a lapsed signature and a closed connection, is retried after the backoff, from a fresh manifest.

func ValidAccountKey

func ValidAccountKey(key string) bool

ValidAccountKey reports whether key is an nkeys account public key.

func ValidBloc

func ValidBloc(bloc string) bool

ValidBloc reports whether bloc has the form of a bloc's name.

func ValidInstallation

func ValidInstallation(id string) bool

ValidInstallation reports whether id has the form of an installation id.

func ValidOrg

func ValidOrg(org string) bool

ValidOrg reports whether org has the form of an org's name.

func ValidRequestID

func ValidRequestID(id string) bool

ValidRequestID reports whether id has the form RequestID gives.

func ValidUserKey

func ValidUserKey(key string) bool

ValidUserKey reports whether key is an nkeys user public key, the form of a worker key and an install key.

func ValidVersion

func ValidVersion(v string) bool

ValidVersion reports whether v is a semantic version the manifest can carry.

func ValidWorkerID

func ValidWorkerID(id string) bool

ValidWorkerID reports whether id has the form of a worker id.

func VerifyBinary

func VerifyBinary(bin Binary, r io.Reader) error

VerifyBinary reports whether r holds exactly bin's bytes.

func VerifyPinned

func VerifyPinned(presented []*x509.Certificate, host, pin string) (*x509.Certificate, error)

VerifyPinned checks the chain a bus presented against pin and host in three steps, and returns the root to save as ca.pem.

  1. It finds the presented certificate whose SHA-256 equals the pin. A copy of the root proves nothing, since the root is public, so finding it is only the start.
  2. It verifies the leaf against that certificate, as the only root, with the other presented certificates as intermediates.
  3. It checks the leaf's name against host.

Every refusal wraps ErrCAPin.

func VerifyRequest

func VerifyRequest(r Request, a Attestation) error

VerifyRequest checks the request's signature against the host key its attestation names, under JoinNamespace. It refuses a host key of a type other than ssh-ed25519 with CodeHostKeyUnsupported and a signature that does not verify with CodeAttestationInvalid.

func WriteTrust

func WriteTrust(dir string, t TrustState) error

WriteTrust writes the trust state into dir, which the root step owns, as fresh files that replace the old ones, each at mode 0644 and owned by the caller. Each file is written whole before it takes the old one's place, so a reader never sees half a floor.

Types

type Address

type Address struct {
	UIHost             string `json:"-"`
	Version            int    `json:"version"`
	BusURL             string `json:"busUrl"`
	Installation       string `json:"installation"`
	Org                string `json:"org"`
	AdmissionAccount   string `json:"admissionAccount"`
	RequestRoot        string `json:"requestRoot"`
	InboxRoot          string `json:"inboxRoot"`
	ReleaseRequestRoot string `json:"releaseRequestRoot"`
	ReleaseAnswerRoot  string `json:"releaseAnswerRoot"`
	CAPin              string `json:"caPin,omitempty"`
	FallbackPin        string `json:"fallbackPin,omitempty"`
}

Address is the enrollment address: the one non-secret value a bastion needs to find its managing system. It is a URL on the managing system's UI, so a person who pastes it into a browser lands on the org's workers page, and its fragment holds the payload, the base64url of the canonical JSON of every field but UIHost.

The subject roots ride in the address so that this package never names the managing system. CAPin, when set, is the lower-case hex SHA-256 of the bus's private root certificate, and that root is the only root the worker trusts. With no pin, the bus presents a certificate that the system's roots verify.

FallbackPin, which only an address with no pin may carry, is the lower-case hex SHA-256 of a private root the worker also accepts when the system's roots do not verify the bus, as when the bus falls back from a public certificate to its own. An address made before the field existed simply lacks it, and it behaves as it always did.

func ParseAddress

func ParseAddress(s string) (Address, error)

ParseAddress reads an enrollment address. It takes surrounding white space, and it refuses with CodeAddressInvalid an address longer than MaxAddress, one that is not https, one whose payload is not the canonical encoding of a valid address, and anything else.

func (a Address) ApprovalLink(bloc, fp string) (string, error)

ApprovalLink returns the link a person opens to approve the worker of bloc whose host key has the fingerprint fp: https://{ui-host}/#/blocs/{bloc}/workers?expect={fp}. It names the bloc and the fingerprint and never the confirmation code, and the fingerprint rides in the fragment.

func (Address) Encode

func (a Address) Encode() (string, error)

Encode returns the address in its one form, and refuses an address that does not validate or is longer than MaxAddress.

func (Address) InboxPrefix

func (a Address) InboxPrefix(key string) (string, error)

InboxPrefix returns the inbox prefix the holder of key sets on its connection: the inbox root and the key. The admission account lets a user hear replies under its own key's prefix alone.

func (Address) ParseRequestSubject

func (a Address) ParseRequestSubject(subject string) (bloc, key string, err error)

ParseRequestSubject returns the bloc and the key of a subject that RequestSubject built from this address, and refuses any other subject with CodeRequestInvalid.

func (Address) ReleaseInbox

func (a Address) ReleaseInbox(bloc, worker string) (string, error)

ReleaseInbox returns the subject on which the worker workerID of bloc hears the answers to its release reads.

func (Address) ReleaseSubject

func (a Address) ReleaseSubject(bloc, worker, op string) (string, error)

ReleaseSubject returns the subject of a release read operation for the worker workerID of bloc, where op is ReleaseManifest, ReleaseChunk, or ReleaseStatus.

func (Address) ReplyValid

func (a Address) ReplyValid(reply, key string) bool

ReplyValid reports whether reply is an inbox subject under the prefix of key, which is the only reply subject the managing system answers.

func (Address) RequestSubject

func (a Address) RequestSubject(bloc, key string) (string, error)

RequestSubject returns the subject on which the holder of key asks to enroll a worker for bloc: the request root, the bloc, and the key.

func (Address) String

func (a Address) String() string

String returns the address in its one form, https://{ui-host}/#/enroll/v1/{payload}. It returns the empty string for an address that does not validate.

func (Address) Validate

func (a Address) Validate() error

Validate holds the address to its form, and refuses with CodeAddressInvalid.

type Answer

type Answer struct {
	State      State      `json:"state"`
	Request    string     `json:"request,omitempty"`
	Verdict    Verdict    `json:"verdict,omitempty"`
	WorkerID   string     `json:"workerId,omitempty"`
	Credential string     `json:"credential,omitempty"`
	ExpiresAt  *time.Time `json:"expiresAt,omitempty"`
	Refusal    *Refusal   `json:"refusal,omitempty"`
}

Answer answers one request. Request is the request's id, which a refusal of a request whose envelope did not decode leaves empty.

func Approved

func Approved(id, worker, credential string, expires time.Time) Answer

Approved answers a request whose worker was approved, with its worker id and a credential that lapses at expires.

func DecodeAnswer

func DecodeAnswer(body []byte, request string) (Answer, error)

DecodeAnswer reads one answer for the request whose id is request. It refuses with CodeAnswerInvalid a body longer than MaxMessage, an unknown field, trailing data, an answer that does not hold to its form, and an answer that names any other request or none.

A bus publisher can set any reply subject it likes, so another asker can have the managing system answer its own request into this asker's inbox. The request id is what ties an answer to the asker that reads it, and every refusal from the envelope's decoding on names that id. A refusal that names no request is never taken as the asker's own.

func Pending

func Pending(id string, v Verdict) Answer

Pending answers a request that waits for a person.

func Refused

func Refused(id, code string) Answer

Refused answers a refused request with code, one of RefusalCodes. id is the one DecodeEnvelope returned, which is empty only when the envelope did not decode.

func Rejected

func Rejected(id string) Answer

Rejected answers a request whose worker key was rejected.

func Removed

func Removed(id string) Answer

Removed answers a request whose worker key was removed.

func (Answer) Encode

func (a Answer) Encode() ([]byte, error)

Encode returns the answer's bytes as the bus carries them, and refuses an answer that does not validate.

func (Answer) Format

func (a Answer) Format(s fmt.State, _ rune)

Format withholds the credential as String does, under every verb.

func (Answer) GoString

func (a Answer) GoString() string

GoString withholds the credential as String does.

func (Answer) LogValue

func (a Answer) LogValue() slog.Value

LogValue gives slog the answer's fields with the credential named only by its key name, so a JSON handler, which ignores String, never carries the JWT.

func (Answer) String

func (a Answer) String() string

String names the answer's fields and gives every value but the credential, which it names only by its key name, so that a log line or an error never carries the JWT.

func (Answer) Validate

func (a Answer) Validate() error

Validate holds an answer to its form: each state carries exactly its own fields. It refuses with CodeAnswerInvalid.

type Asker

type Asker int

Asker names which of the attestation's two keys sent a request.

const (
	AskerWorker Asker = iota + 1
	AskerInstall
)

The two keys that may ask.

func Bind

func Bind(a Attestation, subjectBloc, subjectKey, org, installation string) (Asker, error)

Bind checks the four equalities that bind a request to one installation, one org, one bloc, and one pair of keys, and returns which key asked. subjectBloc and subjectKey come from the request's subject, and org and installation are those of the service that received it. The subject's key must be the attestation's worker key or its install key, else CodeAttestationInvalid. The org and the installation must match, else CodeWrongInstallation, and the blocs must match, else CodeBlocMismatch.

func (Asker) String

func (k Asker) String() string

String names the asker.

type Attestation

type Attestation struct {
	Domain       string    `json:"domain"`
	Installation string    `json:"installation"`
	Org          string    `json:"org"`
	Bloc         string    `json:"bloc"`
	WorkerKey    string    `json:"workerKey"`
	InstallKey   string    `json:"installKey"`
	HostKey      string    `json:"hostKey"`
	CreatedAt    time.Time `json:"createdAt"`
}

Attestation is what the bootstrap signs with the bastion's host key. It names two user nkeys that prepare generates together: WorkerKey is the identity a person enrolls, whose seed only the installed worker holds, and InstallKey belongs to the enrollment service, which can only ever get a credential that reads the release. The two must differ. HostKey is the host's public key as its type and its base64 blob, without a comment. CreatedAt is a UTC time in whole seconds.

func NewAttestation

func NewAttestation(installation, org, bloc, workerKey, installKey, hostKey string, at time.Time) (Attestation, error)

NewAttestation returns the attestation for a pair of keys, with hostKey as a .pub file or an authorized_keys line gives it and at as the time it was made. It drops the key line's comment and keeps at as the UTC second, which is the attestation's canonical form.

func ParseAttestation

func ParseAttestation(b []byte) (Attestation, error)

ParseAttestation reads an attestation's bytes. It refuses bytes longer than MaxAttestation, an unknown field, trailing data, an attestation that does not hold to its form, and any bytes but the canonical ones, so that one attestation has one request id.

func (Attestation) Canonical

func (a Attestation) Canonical() ([]byte, error)

Canonical returns the attestation's canonical bytes, the ones the bootstrap signs and the request carries: compact JSON with the fields in the order of the type, and no trailing newline.

func (Attestation) Validate

func (a Attestation) Validate() error

Validate holds an attestation to its form, and refuses with CodeRequestInvalid, including when both keys are one key.

type Backoff

type Backoff struct {
	Base time.Duration
	Max  time.Duration
	// Rand returns a number in [0, 1). Tests set it.
	Rand func() float64
	// contains filtered or unexported fields
}

Backoff doubles a wait from Base up to Max, and draws each wait at random from its top fifth, so bastions that failed together don't ask again together. It never gives up; the caller decides when to stop. The zero Rand uses the process's random source. A Backoff is not safe for concurrent use.

func FetchBackoff

func FetchBackoff() *Backoff

FetchBackoff returns the backoff for fetching the worker binary.

func PendingBackoff

func PendingBackoff() *Backoff

PendingBackoff returns the backoff for asking while a request is pending.

func RejectedBackoff

func RejectedBackoff() *Backoff

RejectedBackoff returns the backoff for polling a rejected request, which waits RejectedPoll each time, with the same jitter.

func (*Backoff) Next

func (b *Backoff) Next() time.Duration

Next returns the next wait and doubles the one after it, up to Max.

func (*Backoff) Reset

func (b *Backoff) Reset()

Reset starts the doubling over, after a step that succeeded.

type Binary

type Binary struct {
	Arch      string   `json:"arch"`
	Name      string   `json:"name"`
	Size      int64    `json:"size"`
	SHA256    string   `json:"sha256"`
	ChunkSize int64    `json:"chunkSize"`
	Chunks    []string `json:"chunks"`
}

Binary is one architecture's worker binary as the manifest names it: its file name, its size, its SHA-256, its chunk size, and the SHA-256 of every chunk, which let a download resume from the last chunk that matched. Digests are lower-case hex.

func (Binary) ChunkLen

func (b Binary) ChunkLen(i int) int64

ChunkLen returns the length of chunk i.

type ChunkAnswer

type ChunkAnswer struct {
	Refusal *ReleaseRefusal `json:"refusal,omitempty"`
	Version string          `json:"version,omitempty"`
	Arch    string          `json:"arch,omitempty"`
	Index   int             `json:"index,omitempty"`
	Chunk   []byte          `json:"chunk,omitempty"`
	SHA256  string          `json:"sha256,omitempty"`
}

ChunkAnswer answers a ChunkRequest with the chunk and its SHA-256, in lower-case hex, and names the chunk it carries. Like every zero field, an Index of 0 is left out of the encoding.

func (ChunkAnswer) Answers

func (a ChunkAnswer) Answers(r ChunkRequest) bool

Answers reports whether a, a decoded chunk answer that carries a chunk, is the chunk r asked for.

type ChunkRequest

type ChunkRequest struct {
	Version string `json:"version"`
	Arch    string `json:"arch"`
	Index   int    `json:"index"`
}

ChunkRequest asks for chunk Index of the binary for Arch, of Version.

type ChunkSource

type ChunkSource interface {
	Chunk(ctx context.Context, index int) ([]byte, error)
}

ChunkSource answers for one chunk of one release binary. A source that returns a coded Error with CodeWorkerRevoked stops the fetch; any other error is for the caller to retry after its backoff.

type Error

type Error = sigchain.Error

Error is a coded refusal, the same type the sigchain package refuses with, so one CodeOf reads the code of either.

type FetchTarget

type FetchTarget interface {
	io.ReaderAt
	io.WriterAt
	Truncate(size int64) error
	Sync() error
}

FetchTarget is the file a fetch writes. *os.File satisfies it.

type Floors

type Floors struct {
	Minimum   string `json:"minimum"`
	Installed string `json:"installed"`
}

Floors are the two floors a bastion records. Minimum is the highest minimum version of any manifest that passed every step of the chain on this bastion, and Installed is the version installed there. Either is empty when nothing set it.

func ParseFloors

func ParseFloors(b []byte) (Floors, error)

ParseFloors reads the floors' canonical bytes.

type Manifest

type Manifest struct {
	Domain         string    `json:"domain"`
	Version        string    `json:"version"`
	MinimumVersion string    `json:"minimumVersion"`
	BuildTime      time.Time `json:"buildTime"`
	Binaries       []Binary  `json:"binaries"`
}

Manifest is the signed list of a release's worker binaries. Version is the release's version, and MinimumVersion the lowest version a bastion that installed this one may take later. BuildTime is a UTC second. Binaries are in ascending order of architecture, with no repeats.

func ParseManifest

func ParseManifest(b []byte) (Manifest, error)

ParseManifest reads a manifest's bytes and refuses any bytes but the canonical form of a valid manifest.

func (Manifest) Binary

func (m Manifest) Binary(arch string) (Binary, bool)

Binary returns the manifest's binary for arch.

func (Manifest) Canonical

func (m Manifest) Canonical() ([]byte, error)

Canonical returns the manifest's canonical bytes, which the online key signs.

func (Manifest) Validate

func (m Manifest) Validate() error

Validate holds the manifest to its form.

type ManifestAnswer

type ManifestAnswer struct {
	Refusal *ReleaseRefusal `json:"refusal,omitempty"`
	Set     *ManifestSet    `json:"set,omitempty"`
}

ManifestAnswer answers a ManifestRequest with the manifest set: the manifest, the newest signature set for its version, and the newest revocation statement.

type ManifestRequest

type ManifestRequest struct{}

ManifestRequest asks for the manifest of the version the answering copy runs. It carries no fields.

type ManifestSet

type ManifestSet struct {
	Manifest      []byte `json:"manifest"`
	ManifestSig   []byte `json:"manifestSig"`
	Statement     []byte `json:"statement"`
	StatementSig  []byte `json:"statementSig"`
	Revocation    []byte `json:"revocation,omitempty"`
	RevocationSig []byte `json:"revocationSig,omitempty"`
}

ManifestSet is the six files of a manifest set: the manifest and its signature, the online key's statement and its signature, and the newest revocation statement the release knows and its signature. Revocation and RevocationSig are both empty when the set carries no revocation.

type PinnedRoot

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

PinnedRoot holds the root a pinned handshake verified, which the caller saves as ca.pem only once the checks pass.

func BusTLSConfig

func BusTLSConfig(a Address, saved []byte) (*tls.Config, *PinnedRoot, error)

BusTLSConfig returns the TLS configuration for the bus that a names.

With no pin and no fallback root, the bus must present a certificate the system's roots verify. With no pin and a fallback root, it must present a certificate that either the system's roots verify for the bus's host or that holds to the fallback root under the checks of VerifyPinned, which check the host as well; the fallback root is never saved. With a pin and a saved ca.pem, which must hold exactly the pinned certificate, the saved root is the only root. With a pin and no saved root, the handshake runs the checks of VerifyPinned, and the returned PinnedRoot holds the root once they pass, so the caller can save it. The configuration fetches nothing; it only checks the handshake.

func (*PinnedRoot) PEM

func (p *PinnedRoot) PEM() []byte

PEM returns the verified root as PEM, or nil before a handshake verified it.

type Refusal

type Refusal struct {
	Code string `json:"code"`
}

Refusal is a refused request's code. It carries no message, since the asker is not yet trusted.

type ReleaseRefusal

type ReleaseRefusal struct {
	Code     string     `json:"code"`
	Version  string     `json:"version,omitempty"`
	NotAfter *time.Time `json:"notAfter,omitempty"`
}

ReleaseRefusal is a refused release answer. Version and NotAfter are set only on CodeReleaseSignatureExpired, where they name the version whose signature lapsed and the end of its window.

func (ReleaseRefusal) Err

func (r ReleaseRefusal) Err() error

Err returns the refusal as a coded Error, which a fetch can return.

type Request

type Request struct {
	Attestation []byte `json:"attestation"`
	Signature   string `json:"signature"`
}

Request is a worker's request for admission. Attestation is the attestation's canonical bytes, which JSON carries as base64, and Signature the armored SSHSIG over them. The worker key and the install key send the same Request, so both share one request id.

func DecodeEnvelope

func DecodeEnvelope(body []byte) (Request, string, error)

DecodeEnvelope is the second step of the check order. It checks the size, decodes the request's envelope, and hashes its attestation field to get the request id, without reading the attestation itself. From this step on, every refusal names the id DecodeEnvelope returns, so the asker can bind the refusal to its own request. It refuses with CodeRequestInvalid and an empty id a body longer than MaxMessage, one that does not decode, one with an unknown field or trailing data, and one whose attestation is empty, which names no request.

func SignAttestation

func SignAttestation(hostKey ed25519.PrivateKey, a Attestation) (Request, error)

SignAttestation returns the armored SSHSIG of the attestation's canonical bytes, made with an Ed25519 host key under JoinNamespace. It writes what ssh-keygen -Y sign -n ocfp-bastion-join-v1 writes.

func (Request) Encode

func (r Request) Encode() ([]byte, error)

Encode returns the request's bytes as the bus carries them, and refuses a request DecodeRequest would refuse.

func (Request) ID

func (r Request) ID() string

ID returns the request's id.

type State

type State string

State is where a request stands, as an answer reports it.

const (
	// StatePending says the request waits for a person. Its answer
	// carries the verdict of the host key check.
	StatePending State = "pending"
	// StateApproved says a person approved the worker. Its answer carries
	// the worker id and a fresh credential for the key that asked.
	StateApproved State = "approved"
	// StateRejected says a person rejected the worker key.
	StateRejected State = "rejected"
	// StateRemoved says the worker key was enrolled and then removed.
	StateRemoved State = "removed"
	// StateRefused says the managing system refused the request. Its
	// answer carries the refusal's code.
	StateRefused State = "refused"
)

The states of a request.

type StatusAnswer

type StatusAnswer struct {
	Refusal *ReleaseRefusal `json:"refusal,omitempty"`
}

StatusAnswer acknowledges a StatusRequest, or refuses it.

type StatusRequest

type StatusRequest struct {
	Code  string    `json:"code,omitempty"`
	Clock time.Time `json:"clock"`
}

StatusRequest reports the enrollment service's last refusal code, or none, and its clock reading, at most once per StatusInterval.

type TrustState

type TrustState struct {
	Floors     Floors
	Revocation *sigchain.Signed
}

TrustState is what the trust directory holds: the floors, and the newest revocation statement the bastion has verified, if any.

func ReadTrust

func ReadTrust(dir string) (TrustState, error)

ReadTrust reads the trust state from dir under the file rules. A missing file is an empty part of the state. A file that is present but broken is an error, because a floor that can't be read must not read as no floor. A revocation statement is kept only with its signature; which of several statements is newest, and whether it verifies, is the chain's step 2 to decide. The directory itself must exist and be a directory, not a link: the root step that installs the worker creates it, so a missing one is refused rather than read as a bastion with no floor.

func (TrustState) Floor

func (t TrustState) Floor() string

Floor returns the highest of the embedded minimum and the two recorded floors.

func (TrustState) Raise

func (t TrustState) Raise(v Verified) TrustState

Raise returns the trust state after v was installed: the minimum floor rises to v's minimum version, the installed floor to v's version, and the revocation to v's newest one, and none of them ever falls. Only a manifest set that passed every step may raise it.

type Verdict

type Verdict string

Verdict is how the attestation's host key compares with the bloc's record.

const (
	VerdictMatch      Verdict = "match"
	VerdictMismatch   Verdict = "mismatch"
	VerdictUnverified Verdict = "unverified"
)

The verdicts of the host key check.

type Verified

type Verified struct {
	Manifest Manifest
	Chain    sigchain.Result
}

Verified is what VerifyManifestSet found: the manifest, and the chain result whose newest revocation the caller records.

func VerifyManifestSet

func VerifyManifestSet(roots sigchain.Trust, trust TrustState, set ManifestSet, now time.Time) (Verified, error)

VerifyManifestSet checks a manifest set in the six steps of the chain, at the clock reading now, and refuses with a coded Error at the first that fails. Steps 1 to 5 are sigchain.Verify's, against roots and every revocation statement in trust and in the set. Step 6 refuses, with CodeVersionBelowFloor, a manifest whose version is below the highest of the embedded MinimumWorkerVersion and the two floors that trust records. A signed manifest that does not hold to its form is refused with CodeSignatureInvalid.

Jump to

Keyboard shortcuts

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