bitwarden

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: MIT Imports: 33 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 the shell reads a vault with no external daemon and wipes its keys on lock.

Index

Constants

View Source
const (
	CloudUS = "bitwarden.com"
	CloudEU = "bitwarden.eu"
)

The official clouds, by the names ParseServer takes.

Variables

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

ErrInsufficientKdf reports KDF parameters under Bitwarden's floors.

View Source
var ErrInvalidCredentials = errors.New("bitwarden: invalid credentials")

ErrInvalidCredentials reports a login the server refused.

View Source
var ErrLoginRequired = errors.New("bitwarden: login required")

ErrLoginRequired reports a session that can no longer refresh (an API key login, which gets no refresh token, or a token the server revoked): log in again.

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 ErrNewDeviceVerification = errors.New("bitwarden: new device verification required")

ErrNewDeviceVerification asks for the code the server emailed for a login from a device it has not seen.

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

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

View Source
var ErrWrongPassword = errors.New("bitwarden: wrong master password")

ErrWrongPassword reports a master password that does not open the user key.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Op      string
	Status  int
	Message string
}

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

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Retryable

func (e *APIError) Retryable() bool

Retryable reports a rate limit or a server-side failure, worth trying again later; a client error is not.

type APIKeyRequest

type APIKeyRequest struct {
	Server           Server
	Email            string
	ClientID, Secret string
	Password         string
}

APIKeyRequest is an API key login; the master password still opens the keys.

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 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) PasswordLogin

func (c *Client) PasswordLogin(ctx context.Context, email, passwordHash string, tf *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. Older servers (Vaultwarden among them) answer only the original endpoint, without a salt: then the salt 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) 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.

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 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          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.

func (Item) Match

func (it Item) Match(query string) bool

Match reports whether the item matches every word of query, in its name, username, URIs or folder, ignoring case.

type ItemType

type ItemType int

ItemType is a cipher's kind.

const (
	ItemLogin      ItemType = 1
	ItemSecureNote ItemType = 2
	ItemCard       ItemType = 3
	ItemIdentity   ItemType = 4
	ItemSSHKey     ItemType = 5
)

The cipher types.

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 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 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 LoginRequest

type LoginRequest struct {
	Server       Server
	Email        string
	Password     string
	TwoFactor    *TwoFactor
	NewDeviceOTP string
}

LoginRequest is a password login: the server, the account, the master password, and the second factor or new device code when a previous attempt asked for one.

type Prelogin

type Prelogin struct {
	Kdf  Kdf
	Salt string
}

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

type Server

type Server struct {
	API, Identity string
}

Server is where an account lives: its API and identity endpoints.

func ParseServer

func ParseServer(s string) (Server, error)

ParseServer resolves where an account lives: an official cloud by its name, or a self-hosted server (or Vaultwarden) by its http(s) base URL, its API under /api and its identity server under /identity.

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) (*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.

func (*Service) Items

func (s *Service) Items() []Item

Items is the open vault's items, nil while locked.

func (*Service) Lock

func (s *Service) Lock()

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

func (*Service) LockIdle

func (s *Service) LockIdle(idle time.Duration) bool

LockIdle locks an open vault unused for idle or longer: since it opened, or since the last Touch. It reports whether it locked.

func (*Service) Login

func (s *Service) Login(ctx context.Context, req 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 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: once the access token expires, a locked vault needs the key again.

func (*Service) Logout

func (s *Service) Logout() error

Logout locks and forgets the session.

func (*Service) SendLoginEmail

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

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

func (*Service) Status

func (s *Service) Status() Status

Status is the latest status.

func (*Service) Subscribe

func (s *Service) Subscribe() (<-chan struct{}, func())

Subscribe ticks after every status or vault change; stop unregisters.

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) Touch

func (s *Service) Touch()

Touch marks the open vault used now, restarting LockIdle's clock.

func (*Service) Unlock

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

Unlock opens a locked vault with the master password: a fresh token, a sync, the keys. A wrong password leaves it locked; a session that can no longer refresh logs out with ErrLoginRequired.

func (*Service) VerifyPassword

func (s *Service) VerifyPassword(password string) error

VerifyPassword checks the master password against the open vault's account, as the master password reprompt does before a protected item's secrets: ErrWrongPassword when it does not open the user key. It derives the key, so it is as slow as an unlock and runs off the UI loop.

type State

type State int

State is where the vault stands.

const (
	StateLoggedOut State = iota
	StateLocked
	StateUnlocked
)

The vault states: no account, an account whose keys are not in memory, and an open vault.

type Status

type Status struct {
	State    State
	Email    string
	Syncing  bool
	LastSync time.Time
	Err      error
	Items    int
}

Status is what the shell shows: the state, the account, whether a sync runs, when the last one landed, and the last operation's error (nil once one succeeds).

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) 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           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
}

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

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 TwoFactor

type TwoFactor struct {
	Provider TwoFactorProvider
	Code     string
}

TwoFactor is a second factor answering a TwoFactorRequiredError.

type TwoFactorProvider

type TwoFactorProvider int

TwoFactorProvider is a second factor the server offers.

const (
	TwoFactorAuthenticator TwoFactorProvider = 0
	TwoFactorEmail         TwoFactorProvider = 1
)

The providers this client completes; the server may list others (Duo, WebAuthn, YubiKey) that the API key login gets around.

type TwoFactorRequiredError

type TwoFactorRequiredError struct{ Providers []TwoFactorProvider }

TwoFactorRequiredError asks for a second factor: the providers the account has.

func (*TwoFactorRequiredError) Error

func (e *TwoFactorRequiredError) Error() string

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
}

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) 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