bitwarden

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT, MIT Imports: 38 Imported by: 0 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 bitwarden is an in-process Bitwarden client: the key hierarchy (master key, user key, RSA private key, organization keys), the EncString envelope, TOTP codes, and the identity and sync API, so lys-secrets reads a vault with no external daemon and wipes its keys on lock. Its Service is the vault package's Host.

Index

Constants

This section is empty.

Variables

View Source
var ErrInsufficientKdf = errors.New("bitwarden: insufficient KDF parameters")

ErrInsufficientKdf reports KDF parameters under Bitwarden's floors.

View Source
var ErrMAC = errors.New("bitwarden: EncString MAC mismatch")

ErrMAC reports an EncString whose MAC does not verify: the wrong key, or tampered data.

View Source
var ErrMissingSecret = errors.New("bitwarden: TOTP without a secret")

ErrMissingSecret reports an otpauth URI without a secret.

View Source
var ErrUnsupportedEncType = errors.New("bitwarden: unsupported EncString type")

ErrUnsupportedEncType reports an EncString of a type this client does not open.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Op string
	vault.ServerError
}

APIError is a server answer the flow does not handle: the operation and the server's status and message.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap is the server's answer, as the vault contract reports it.

type Card

type Card struct {
	Cardholder, Brand, Number, ExpMonth, ExpYear, Code string
}

Card is a decrypted card.

type Client

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

Client talks to one server as one device. Every request carries the caller's context and a timeout.

func NewClient

func NewClient(server vaultserver.Server, device Device) *Client

NewClient is a client for server as device.

func (*Client) APIKeyLogin

func (c *Client) APIKeyLogin(ctx context.Context, id, secret string, now time.Time) (Token, error)

APIKeyLogin logs in with the account's personal API key: no second factor or device check, for the factors this client does not speak.

func (*Client) CreateCipher

func (c *Client) CreateCipher(ctx context.Context, accessToken string, req cipherRequest) (SyncCipher, error)

func (*Client) CreateSend

func (c *Client) CreateSend(ctx context.Context, accessToken string, req sendRequest) (SyncSend, error)

func (*Client) DeleteSend

func (c *Client) DeleteSend(ctx context.Context, accessToken string, id vault.SendID) error

func (*Client) PasswordLogin

func (c *Client) PasswordLogin(ctx context.Context, email, passwordHash string, tf *vault.TwoFactor, newDeviceOTP string, now time.Time) (Token, error)

PasswordLogin exchanges the master password hash for tokens. A second factor or a new device's emailed code, when the server asks, comes as TwoFactorRequiredError or ErrNewDeviceVerification; retry with it.

func (*Client) Prelogin

func (c *Client) Prelogin(ctx context.Context, email string) (Prelogin, error)

Prelogin asks how the account derives its master key. The password endpoint answers either the current shape, KDF settings and a salt, or, as bitwarden.com does, the original one; older servers (Vaultwarden among them) answer only the original endpoint. Without a salt it is the email.

func (*Client) Refresh

func (c *Client) Refresh(ctx context.Context, refreshToken, loginClientID string, now time.Time) (Token, error)

Refresh trades the refresh token for a new access token, under the client id that logged in.

func (*Client) Revoke

func (c *Client) Revoke(ctx context.Context, refreshToken, loginClientID string) error

Revoke asks the server to revoke refreshToken (RFC 7009). The token endpoint's client id needs no secret for a first-party client. A server saying it cannot is vault.ErrRevocationUnsupported; any other answer but 200 is an APIError.

func (*Client) SendLoginEmail

func (c *Client) SendLoginEmail(ctx context.Context, email, passwordHash string) error

SendLoginEmail asks the server to email the login's second-factor code.

func (*Client) Sync

func (c *Client) Sync(ctx context.Context, accessToken string) (SyncResponse, error)

Sync fetches the account: its profile with the wrapped keys, folders, collections and ciphers.

type Device

type Device struct {
	ID, Name string
}

Device is how this client registers with the server: its stable identifier and the name the account's device list shows.

type EncString

type EncString struct {
	Type          EncType
	IV, Data, MAC []byte
}

EncString is Bitwarden's encrypted value, "type.part|part|...": AES-CBC (iv, data[, mac]) or RSA-OAEP (data).

func ParseEncString

func ParseEncString(s string) (EncString, error)

ParseEncString parses s, checking the part count and the IV and MAC lengths its type requires.

func (EncString) String

func (e EncString) String() string

type EncType

type EncType int

EncType is an EncString's algorithm.

const (
	EncAesCbc256B64           EncType = 0
	EncAesCbc256HmacSha256B64 EncType = 2
	EncRsa2048OaepSha256B64   EncType = 3
	EncRsa2048OaepSha1B64     EncType = 4
)

The EncString types this client opens; Bitwarden defines others (the deprecated RSA+HMAC 5 and 6, COSE 7), which parse as unsupported.

type Field

type Field struct {
	Name, Value string
	Hidden      bool
}

Field is a decrypted custom field.

type FolderLogin

type FolderLogin struct {
	ID, Name, Username, URI, Folder string
}

FolderLogin is a login the Secret Service shows: its id, name, username, first URI and folder.

type Identity

type Identity struct {
	Title, First, Middle, Last, Email, Phone, Username, Company string
}

Identity is a decrypted identity's shown fields.

type Item

type Item struct {
	ID            string
	Type          vault.ItemType
	Name          string
	Notes         string
	Folder        string
	Organization  string
	Favorite      bool
	Reprompt      bool
	Username      string
	Password      string
	TOTP          string
	URIs          []string
	Card          Card
	Identity      Identity
	Fields        []Field
	Undecryptable bool
}

Item is a decrypted vault item. Undecryptable marks one any of whose fields failed to open (a key it was not shared with, an EncString type this client does not speak); the rest still shows.

type Kdf

type Kdf struct {
	Type        KdfType
	Iterations  int
	Memory      int
	Parallelism int
}

Kdf is an account's key derivation: its type and parameters, memory in MiB.

type KdfType

type KdfType int

KdfType names the master-password key derivation.

const (
	KdfPBKDF2   KdfType = 0
	KdfArgon2id KdfType = 1
)

The KDFs the server reports at prelogin.

type Keychain

type Keychain interface {
	Lookup(ctx context.Context, attrs map[string]string) (value []byte, found bool, err error)
	Store(ctx context.Context, label string, attrs map[string]string, value []byte) error
	Delete(ctx context.Context, attrs map[string]string) error
}

type Keyring

type Keyring struct {
	User SymmetricKey

	Orgs map[string]SymmetricKey
	// contains filtered or unexported fields
}

Keyring is an unlocked account's keys: the user key, the RSA private key, and each organization's key. Wipe zeroes them all.

func Unlock

func Unlock(in UnlockInput) (*Keyring, error)

Unlock derives the master key and opens the key hierarchy. A user key that does not verify is vault.ErrWrongPassword; any other key that does not open is an error naming it.

func (*Keyring) GoString

func (k *Keyring) GoString() string

GoString is String for %#v.

func (*Keyring) SetOrgKeys

func (k *Keyring) SetOrgKeys(orgKeys map[string]string) error

SetOrgKeys replaces the organization keys with orgKeys, each opened with the private key: a sync after a membership change brings new ones and drops old ones. On an error the previous keys stay.

func (*Keyring) String

func (k *Keyring) String() string

String keeps the keyring out of logs and %v output.

func (*Keyring) Wipe

func (k *Keyring) Wipe()

Wipe zeroes every key; the keyring is unusable after.

type Policy

type Policy struct {
	LockAfter, SyncInterval time.Duration
}

Policy is how the open vault is kept: locked once unused for LockAfter (0 never), synced every SyncInterval (0 only on unlock and when asked).

type Prelogin

type Prelogin struct {
	Kdf  Kdf
	Salt string
}

Prelogin is an account's key derivation and its master-password salt.

type Service

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

Service owns the vault: the session, the keys while unlocked, and the decrypted items. Operations run one at a time; no lock is held across a network call except the operation lock that serializes them.

func Open

func Open(dir, deviceName string, keychain Keychain, changed func()) (*Service, error)

Open loads the session in dir (created 0700), registering a device id on first use: an account there starts locked, none logged out. Its credential is read from keychain at the first unlock. changed runs after every status or vault change.

func (*Service) CreateLogin

func (s *Service) CreateLogin(ctx context.Context, l vault.NewLogin) (vault.ItemID, error)

func (*Service) CreateTextSend

func (s *Service) CreateTextSend(ctx context.Context, n vault.NewTextSend) (vault.CreatedSend, error)

func (*Service) DeleteSend

func (s *Service) DeleteSend(ctx context.Context, id vault.SendID) error

func (*Service) Field

func (s *Service) Field(id string, f vault.Field, password string) (vault.Value, error)

Field is item id's field f, a verification code the one current now. A secret of an item behind the master password reprompt needs the master password; otherwise password is ignored. It counts as use.

func (*Service) FindLogin

func (s *Service) FindLogin(name string, scope vault.FolderScope) (vault.Item, bool, error)

func (*Service) FolderLogins

func (s *Service) FolderLogins(folder string) (logins []FolderLogin, open bool)

FolderLogins is the open vault's shareable logins in folder, in vault order; open is false (and the list empty) while the vault is not open.

func (*Service) FolderPassword

func (s *Service) FolderPassword(folder, id string) ([]byte, error)

FolderPassword is the password of login id, one of FolderLogins' for folder. It counts as use.

func (*Service) Items

func (s *Service) Items() ([]vault.Item, error)

Items lists the open vault, favorites first then by name.

func (*Service) Keep

func (s *Service) Keep(ctx context.Context, p Policy, failed func(error))

Keep upholds p until ctx ends. A periodic sync that fails is reported to failed once per run of failures, and every time it logs the account out.

func (*Service) Lock

func (s *Service) Lock()

Lock wipes the keys and the plaintext; the session stays for Unlock.

func (*Service) Login

func (s *Service) Login(ctx context.Context, req vault.LoginRequest) error

Login logs in with the master password and opens the vault. A second factor or a new device's code comes back as TwoFactorRequiredError or ErrNewDeviceVerification: ask for it and call Login again with it.

func (*Service) LoginAPIKey

func (s *Service) LoginAPIKey(ctx context.Context, req vault.APIKeyRequest) error

LoginAPIKey logs in with the personal API key and opens the vault with the master password. The server issues no refresh token for it, so the keyring keeps the API key, and an unlock or a sync after the access token expired logs in with it again, as Bitwarden's clients do.

func (*Service) Logout

func (s *Service) Logout(ctx context.Context) error

Logout locks and forgets the session here first, then asks the server to revoke its refresh token, so a server that does not answer never keeps a session here. A server with no way to revoke is logged once and returned as vault.ErrRevocationUnsupported, with no error in the status, since that logout did all it can. An attempt that failed is vault.ErrSessionNotRevoked, in the status as well, and so is a keyring that could not say which refresh token to revoke. A session without a refresh token (an API key login) has nothing to revoke. It waits for a running operation, which may rotate the token or save the session.

func (*Service) NetworkLogin

func (s *Service) NetworkLogin(folder, name string) (vault.NetworkLogin, bool)

NetworkLogin is the login answering the network connection named name from folder (networkLogin); none from an empty folder or a vault that is not open.

func (*Service) SendLoginEmail

func (s *Service) SendLoginEmail(ctx context.Context, req vault.LoginRequest) error

SendLoginEmail asks the server to email the second-factor code for a login that needs it.

func (*Service) Sends

func (s *Service) Sends() ([]vault.Send, error)

func (*Service) Status

func (s *Service) Status() vault.Status

Status is the latest status.

func (*Service) Sync

func (s *Service) Sync(ctx context.Context) error

Sync refetches the open vault: new and changed items, organization memberships, folder names.

func (*Service) Unlock

func (s *Service) Unlock(ctx context.Context, password string) error

Unlock opens a locked vault with the master password: the credential from the keyring after a restart, a fresh token, a sync, the keys. A wrong password leaves it locked; a session that can no longer refresh, or one the keyring does not keep, logs out with vault.ErrLoginRequired.

type SymmetricKey

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

SymmetricKey is an AES-256-CBC key with its HMAC-SHA256 key; a legacy key has no MAC key and opens only type 0 EncStrings. It formats as [redacted].

func (SymmetricKey) Decrypt

func (k SymmetricKey) Decrypt(e EncString) ([]byte, error)

Decrypt opens an AES EncString. A MAC-carrying string needs a key with a MAC key and verifies before decrypting; a legacy type 0 string opens only with a legacy key, so a type 0 string can never stand in for an authenticated one.

func (SymmetricKey) DecryptString

func (k SymmetricKey) DecryptString(s string) (string, error)

DecryptString opens s as a UTF-8 string.

func (SymmetricKey) Encrypt

func (k SymmetricKey) Encrypt(plain []byte) (EncString, error)

func (SymmetricKey) EncryptString

func (k SymmetricKey) EncryptString(s string) (string, error)

func (SymmetricKey) GoString

func (k SymmetricKey) GoString() string

GoString is String for %#v.

func (SymmetricKey) String

func (k SymmetricKey) String() string

String and GoString keep the key out of logs and %v output.

func (SymmetricKey) Wipe

func (k SymmetricKey) Wipe()

Wipe zeroes the key material.

type SyncCard

type SyncCard struct {
	CardholderName, Brand, Number, ExpMonth, ExpYear, Code string
}

SyncCard is a card's encrypted fields.

type SyncCipher

type SyncCipher struct {
	ID             string
	OrganizationID string
	FolderID       string
	Type           vault.ItemType
	Name           string
	Notes          string
	Favorite       bool
	Key            string
	Reprompt       int
	DeletedDate    *string
	Login          *SyncLogin
	Card           *SyncCard
	Identity       *SyncIdentity
	Fields         []SyncField
}

SyncCipher is one encrypted vault item.

type SyncCollection

type SyncCollection struct {
	ID, OrganizationID, Name string
}

SyncCollection is an organization collection, its name encrypted under the organization key.

type SyncField

type SyncField struct {
	Name, Value string
	Type        int
}

SyncField is a custom field; its type says whether the value is hidden (1) or plain (0, 2 boolean, 3 linked).

type SyncFolder

type SyncFolder struct {
	ID, Name string
}

SyncFolder is a folder, its name encrypted under the user key.

type SyncIdentity

type SyncIdentity struct {
	Title, FirstName, MiddleName, LastName, Email, Phone, Username, Company string
}

SyncIdentity is an identity's encrypted fields this client shows.

type SyncLogin

type SyncLogin struct {
	Username, Password, Totp string
	Uris                     []struct{ URI string }
}

SyncLogin is a login's encrypted fields.

type SyncOrganization

type SyncOrganization struct {
	ID, Name, Key string
}

SyncOrganization is a membership: the organization and its wrapped key.

type SyncProfile

type SyncProfile struct {
	Email         string
	Key           string
	PrivateKey    string
	Organizations []SyncOrganization
}

SyncProfile carries the wrapped keys: the user key under the master key, the private key under the user key, each organization's key under the private key.

type SyncResponse

type SyncResponse struct {
	Profile     SyncProfile
	Folders     []SyncFolder
	Collections []SyncCollection
	Ciphers     []SyncCipher
	Sends       []SyncSend
}

SyncResponse is /sync's answer, the encrypted account.

type SyncSend

type SyncSend struct {
	ID             string
	AccessID       string
	Type           vault.SendType
	Name           string
	Key            string
	MaxAccessCount *uint32
	AccessCount    uint32
	Password       *string
	AuthType       *int
	Disabled       bool
	DeletionDate   serverTime
	ExpirationDate *serverTime
}

type TOTP

type TOTP struct {
	Secret    []byte
	Algorithm TOTPAlgorithm
	Digits    int
	Period    int
	Issuer    string
	Account   string
}

TOTP is a parsed authenticator key: the secret and the code's shape.

func ParseTOTP

func ParseTOTP(key string) (TOTP, error)

ParseTOTP reads a vault item's TOTP field as Bitwarden's clients do: an otpauth:// URI, a steam:// key, or a bare base32 secret, all case-insensitive.

func (TOTP) Code

func (t TOTP) Code(now time.Time) (string, time.Duration)

Code is the code at now and how long it stays valid.

type TOTPAlgorithm

type TOTPAlgorithm int

TOTPAlgorithm is a code's HMAC; Steam is SHA-1 with Steam's alphabet.

const (
	TOTPSHA1 TOTPAlgorithm = iota
	TOTPSHA256
	TOTPSHA512
	TOTPSteam
)

The algorithms an otpauth URI or a steam:// key names.

type Token

type Token struct {
	AccessToken  string
	RefreshToken string
	Expires      time.Time
	Key          string
	PrivateKey   string
}

Token is a login's answer: the access and refresh tokens, when the access token expires, and the account's wrapped keys.

type UnlockInput

type UnlockInput struct {
	Password, Email string
	Kdf             Kdf
	UserKey         string
	PrivateKey      string
	OrgKeys         map[string]string
}

UnlockInput is what unlocking needs: the master password, the account email and KDF, the master-key-wrapped user key, the user-key-wrapped private key, and the organization keys wrapped for the private key.

type Vault

type Vault struct {
	Items   []Item
	Folders map[string]string
	Sends   []vault.Send
	// contains filtered or unexported fields
}

Vault is the decrypted account: its items, favorites first then by name, and folder names by id. Deleted items (the trash) are left out.

func DecryptVault

func DecryptVault(kr *Keyring, s SyncResponse) Vault

DecryptVault opens a sync under the keyring. A field that does not open marks its item Undecryptable rather than failing the sync.

func (*Vault) Item

func (v *Vault) Item(id string) (Item, bool)

Item is the item with id, false when the vault has none.

func (*Vault) Wipe

func (v *Vault) Wipe()

Wipe drops the plaintext; the vault is empty after.

Jump to

Keyboard shortcuts

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