gokeepasslib

package module
v0.0.0-...-db44715 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2015 License: MIT Imports: 18 Imported by: 0

README

gokeepasslib

Travis Build state

gokeepasslib is a library which allows reading Keepass 2 files (kdbx).

Example

file, _ := os.Open("examples/example.kdbx")

db := gokeepasslib.NewDatabase()
db.Credentials = gokeepasslib.NewPasswordCredentials("abcdefg12345678")
_ = gokeepasslib.NewDecoder(file).Decode(db)

db.UnlockProtectedEntries()

entry := db.Content.Root.Groups[0].Groups[0].Entries[0]
fmt.Println(entry.GetTitle())
fmt.Println(string(entry.Password))

TODO
  • Add godoc comments
  • Improve code readability
  • Write more tests
License

LICENSE

Copyright © 2015 Tobias Schoknecht. All rights reserved.

Documentation

Overview

Package gokeepasslib is a library written in go which provides functionality to decrypt and parse keepass 2 files (kdbx)

Index

Constants

View Source
const (
	NoStreamID    uint32 = 0
	ARC4StreamID         = 1
	SalsaStreamID        = 2
)

Constant enumerator for the inner random stream ID

View Source
const (
	NoCompressionFlag   uint32 = 0
	GzipCompressionFlag        = 1
)

Constants enumerator for compression flags

Variables

View Source
var AESCipherID = []byte{0x31, 0xC1, 0xF2, 0xE6, 0xBF, 0x71, 0x43, 0x50, 0xBE, 0x58, 0x05, 0x21, 0x6A, 0xFC, 0x5A, 0xFF}
View Source
var BaseSignature = [...]byte{0x03, 0xd9, 0xa2, 0x9a}

BaseSignature is the valid base signature for kdbx files

A full valid default signature struct for new databases

View Source
var ErrInvalidUUIDLength = errors.New("gokeepasslib: length of decoded UUID was not 16")
View Source
var ErrUnsupportedStreamType = errors.New("Type of stream manager unsupported")

ErrUnsupportedStreamType is retured if no streamManager can be created due to an unsupported InnerRandomStreamID value

View Source
var FileVersion = [...]byte{0x01, 0x00, 0x03, 0x00}

FileVersion is the most recent valid file version signature for kdbx files

View Source
var VersionSignature = [...]byte{0x67, 0xfb, 0x4b, 0xb5}

VersionSignature is the valid version signature for kdbx files

Functions

func LockProtectedEntries

func LockProtectedEntries(p ProtectedStreamManager, es []Entry)

func LockProtectedEntry

func LockProtectedEntry(p ProtectedStreamManager, e *Entry)

func LockProtectedGroup

func LockProtectedGroup(p ProtectedStreamManager, g *Group)

func LockProtectedGroups

func LockProtectedGroups(p ProtectedStreamManager, gs []Group)

func ParseKeyFile

func ParseKeyFile(location string) ([]byte, error)

ParseKeyFile returns the hashed key from a key file at the path specified by location, parsing xml if needed

func UnlockProtectedEntries

func UnlockProtectedEntries(p ProtectedStreamManager, e []Entry)

func UnlockProtectedEntry

func UnlockProtectedEntry(p ProtectedStreamManager, e *Entry)

func UnlockProtectedGroup

func UnlockProtectedGroup(p ProtectedStreamManager, g *Group)

func UnlockProtectedGroups

func UnlockProtectedGroups(p ProtectedStreamManager, gs []Group)

Types

type AutoTypeAssociation

type AutoTypeAssociation struct {
	Window            string `xml:"Window"`
	KeystrokeSequence string `xml:"KeystrokeSequence"`
}

type AutoTypeData

type AutoTypeData struct {
	Enabled                 boolWrapper         `xml:"Enabled"`
	DataTransferObfuscation int64               `xml:"DataTransferObfuscation"`
	Association             AutoTypeAssociation `xml:"Association"`
}

type Binaries

type Binaries []Binary

Binaries Stores a slice of binaries in the metadata header of a database

func (*Binaries) Add

func (b *Binaries) Add(c []byte) *Binary

func (Binaries) Find

func (bs Binaries) Find(id int) *Binary

Find returns a reference to a binary with the same ID as id, or nil if none if found

type Binary

type Binary struct {
	Content    []byte      `xml:",innerxml"`
	ID         int         `xml:"ID,attr"`
	Compressed boolWrapper `xml:"Compressed,attr"`
}

Binary stores a binary found in the metadata header of a database

func (Binary) CreateReference

func (b Binary) CreateReference(f string) BinaryReference

CreateReference creates a reference with the same id as b with filename f

func (Binary) GetContent

func (b Binary) GetContent() (string, error)

GetContent returns a string which is the plaintext content of a binary

func (*Binary) SetContent

func (b *Binary) SetContent(c []byte) error

SetContent encodes and (if Compressed=true) compresses c and sets b's content

func (Binary) String

func (b Binary) String() string

type BinaryReference

type BinaryReference struct {
	Name  string `xml:"Key"`
	Value struct {
		ID int `xml:"Ref,attr"`
	} `xml:"Value"`
}

BinaryReference stores a reference to a binary which appears in the xml of an entry

func NewBinaryReference

func NewBinaryReference(name string, id int) BinaryReference

NewbinaryReference creates a new BinaryReference with the given name and id

func (*BinaryReference) Find

func (br *BinaryReference) Find(bs Binaries) *Binary

Find returns a reference to a binary in the slice of binaries bs with the same id as br, or nil if none is found

func (BinaryReference) String

func (br BinaryReference) String() string

type DBContent

type DBContent struct {
	XMLName xml.Name  `xml:"KeePassFile"`
	Meta    *MetaData `xml:"Meta"`
	Root    *RootData `xml:"Root"`
}

DBContent is a container for all elements of a keepass database

func NewDBContent

func NewDBContent() *DBContent

NewDBContent creates a new DB content with some good defaults

type DBCredentials

type DBCredentials struct {
	Passphrase []byte //Passphrase if using one, stored in sha256 hash
	Key        []byte //Contents of the keyfile if using one, stored in sha256 hash
	Windows    []byte //Whatever is returned from windows user account auth, stored in sha256 hash
}

DBCredentials holds the key used to lock and unlock the database

func NewKeyCredentials

func NewKeyCredentials(location string) (*DBCredentials, error)

NewKeyCredentials builds new DBCredentials from a key file at the path specified by location

func NewPasswordCredentials

func NewPasswordCredentials(password string) *DBCredentials

NewPasswordCredentials builds a new DBCredentials from a Password string

func (*DBCredentials) String

func (c *DBCredentials) String() string

type Database

type Database struct {
	Signature   *FileSignature
	Headers     *FileHeaders
	Credentials *DBCredentials
	Content     *DBContent
}

Database stores all contents nessesary for a keepass database file

func NewDatabase

func NewDatabase() *Database

NewDatabase creates a new database with some sensable default settings. To create a database with no settigns per-set, use gokeepasslib.Database{}

func (*Database) LockProtectedEntries

func (db *Database) LockProtectedEntries() error

LockProtectedEntries goes through the entire database and decrypts any Values in entries with protected=true set. Warning: Do not call this if entries are already locked Warning: Encoding a database calls LockProtectedEntries automatically

func (*Database) StreamManager

func (db *Database) StreamManager() ProtectedStreamManager

StreamManager returns a ProtectedStreamManager bassed on the db headers, or nil if the type is unsupported Can be used to lock only certain entries instead of calling

func (*Database) String

func (db *Database) String() string

func (*Database) UnlockProtectedEntries

func (db *Database) UnlockProtectedEntries() error

UnlockProtectedEntries goes through the entire database and encrypts any Values in entries with protected=true set. This should be called after decoding if you want to view plaintext password in an entry Warning: If you call this when entry values are already unlocked, it will cause them to be unreadable

type Decoder

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

Decoder stores a reader which is expected to be in kdbx format

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

func (*Decoder) Decode

func (d *Decoder) Decode(db *Database) error

type DeletedObjectData

type DeletedObjectData struct {
	XMLName      xml.Name   `xml:"DeletedObject"`
	UUID         UUID       `xml:"UUID"`
	DeletionTime *time.Time `xml:"DeletionTime"`
}

type Encoder

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

Encoder is used to automaticaly encrypt and write a database to a file, network, etc

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

NewEncoder creates a new encoder with writer w, identical to gokeepasslib.Encoder{w}

func (*Encoder) Encode

func (e *Encoder) Encode(db *Database) error

Encode writes db to e's internal writer

type Entry

type Entry struct {
	UUID            UUID              `xml:"UUID"`
	IconID          int64             `xml:"IconID"`
	ForegroundColor string            `xml:"ForegroundColor"`
	BackgroundColor string            `xml:"BackgroundColor"`
	OverrideURL     string            `xml:"OverrideURL"`
	Tags            string            `xml:"Tags"`
	Times           TimeData          `xml:"Times"`
	Values          []ValueData       `xml:"String,omitempty"`
	AutoType        AutoTypeData      `xml:"AutoType"`
	Histories       []History         `xml:"History"`
	Password        []byte            `xml:"-"`
	Binaries        []BinaryReference `xml:"Binary,omitempty"`
}

Entry is the structure which holds information about a parsed entry in a keepass database

func NewEntry

func NewEntry() Entry

NewEntry return a new entry with time data and uuid set

func (*Entry) Get

func (e *Entry) Get(key string) *ValueData

Get returns the value in e corresponding with key k, or an empty string otherwise

func (*Entry) GetContent

func (e *Entry) GetContent(key string) string

GetContent returns the content of the value belonging to the given key in string form

func (*Entry) GetIndex

func (e *Entry) GetIndex(key string) int

GetIndex returns the index of the Value belonging to the given key, or -1 if none is found

func (*Entry) GetPassword

func (e *Entry) GetPassword() string

GetPassword returns the password of an entry

func (*Entry) GetPasswordIndex

func (e *Entry) GetPasswordIndex() int

GetPasswordIndex returns the index in the values slice belonging to the password

func (*Entry) GetTitle

func (e *Entry) GetTitle() string

GetTitle returns the title of an entry

type FileHeaders

type FileHeaders struct {
	Comment             []byte // FieldID:  1
	CipherID            []byte // FieldID:  2
	CompressionFlags    uint32 // FieldID:  3
	MasterSeed          []byte // FieldID:  4
	TransformSeed       []byte // FieldID:  5
	TransformRounds     uint64 // FieldID:  6
	EncryptionIV        []byte // FieldID:  7
	ProtectedStreamKey  []byte // FieldID:  8
	StreamStartBytes    []byte // FieldID:  9
	InnerRandomStreamID uint32 // FieldID: 10
}

FileHeaders holds the header information of the Keepass File.

func NewFileHeaders

func NewFileHeaders() *FileHeaders

NewFileHeaders creates a new FileHeaders with good defaults

func ReadHeaders

func ReadHeaders(r io.Reader) (*FileHeaders, error)

ReadHeaders reads the headers from an io.Reader and creates a structure containing the parsed header information

func (FileHeaders) String

func (h FileHeaders) String() string

func (*FileHeaders) WriteHeaders

func (h *FileHeaders) WriteHeaders(w io.Writer) error

WriteHeaders takes the contents of the corresponding FileHeaders struct and writes them to the given io.Writer

type FileSignature

type FileSignature struct {
	BaseSignature    [4]byte
	VersionSignature [4]byte
	FileVersion      [4]byte
}

FileSignature holds the Keepass File Signature. The first 4 Bytes are the Base Signature, followed by 4 Bytes for the Version of the Format which is followed by 4 Bytes for the File Version

func ReadSignature

func ReadSignature(r io.Reader) (*FileSignature, error)

func (FileSignature) String

func (s FileSignature) String() string

func (*FileSignature) WriteSignature

func (s *FileSignature) WriteSignature(w io.Writer) error

type Group

type Group struct {
	UUID                    UUID        `xml:"UUID"`
	Name                    string      `xml:"Name"`
	Notes                   string      `xml:"Notes"`
	IconID                  int64       `xml:"IconID"`
	Times                   TimeData    `xml:"Times"`
	IsExpanded              boolWrapper `xml:"IsExpanded"`
	DefaultAutoTypeSequence string      `xml:"DefaultAutoTypeSequence"`
	EnableAutoType          string      `xml:"EnableAutoType"`
	EnableSearching         string      `xml:"EnableSearching"`
	LastTopVisibleEntry     string      `xml:"LastTopVisibleEntry"`
	Groups                  []Group     `xml:"Group,omitempty"`
	Entries                 []Entry     `xml:"Entry,omitempty"`
}

Group is a structure to store entries in their named groups for organization

func NewGroup

func NewGroup() Group

NewGroup returns a new group with time data and uuid set

type History

type History struct {
	Entries []Entry `xml:"Entry"`
}

History stores information about changes made to an entry, in the form of a list of previous versions of that entry

type InsecureStreamManager

type InsecureStreamManager struct{}

InsecureStreamManager is a stream manger which does not encrypt, just stores the plaintext payload

func (InsecureStreamManager) Pack

func (i InsecureStreamManager) Pack(payload []byte) string

Pack returns the string belonging to the given byte slice payload without any packaging to be done

func (InsecureStreamManager) Unpack

func (i InsecureStreamManager) Unpack(payload string) []byte

Unpack returns the given string as a byte slice without any other action being taken

type MemProtection

type MemProtection struct {
	ProtectTitle    boolWrapper `xml:"ProtectTitle"`
	ProtectUserName boolWrapper `xml:"ProtectUserName"`
	ProtectPassword boolWrapper `xml:"ProtectPassword"`
	ProtectURL      boolWrapper `xml:"ProtectURL"`
	ProtectNotes    boolWrapper `xml:"ProtectNotes"`
}

MemProtection is a structure containing settings for MemoryProtection

type MetaData

type MetaData struct {
	Generator                  string        `xml:"Generator"`
	HeaderHash                 string        `xml:"HeaderHash"`
	DatabaseName               string        `xml:"DatabaseName"`
	DatabaseNameChanged        *time.Time    `xml:"DatabaseNameChanged"`
	DatabaseDescription        string        `xml:"DatabaseDescription"`
	DatabaseDescriptionChanged *time.Time    `xml:"DatabaseDescriptionChanged"`
	DefaultUserName            string        `xml:"DefaultUserName"`
	DefaultUserNameChanged     *time.Time    `xml:"DefaultUserNameChanged"`
	MaintenanceHistoryDays     string        `xml:"MaintenanceHistoryDays"`
	Color                      string        `xml:"Color"`
	MasterKeyChanged           *time.Time    `xml:"MasterKeyChanged"`
	MasterKeyChangeRec         int64         `xml:"MasterKeyChangeRec"`
	MasterKeyChangeForce       int64         `xml:"MasterKeyChangeForce"`
	MemoryProtection           MemProtection `xml:"MemoryProtection"`
	RecycleBinEnabled          boolWrapper   `xml:"RecycleBinEnabled"`
	RecycleBinUUID             UUID          `xml:"RecycleBinUUID"`
	RecycleBinChanged          *time.Time    `xml:"RecycleBinChanged"`
	EntryTemplatesGroup        string        `xml:"EntryTemplatesGroup"`
	EntryTemplatesGroupChanged *time.Time    `xml:"EntryTemplatesGroupChanged"`
	HistoryMaxItems            int64         `xml:"HistoryMaxItems"`
	HistoryMaxSize             int64         `xml:"HistoryMaxSize"`
	LastSelectedGroup          string        `xml:"LastSelectedGroup"`
	LastTopVisibleGroup        string        `xml:"LastTopVisibleGroup"`
	Binaries                   Binaries      `xml:"Binaries>Binary"`
	CustomData                 string        `xml:"CustomData"`
}

MetaData is the structure for the metadata headers at the top of kdbx files, it contains things like the name of the database

func NewMetaData

func NewMetaData() *MetaData

NewMetaData creates a MetaData struct with some defaults set

type ProtectedStreamManager

type ProtectedStreamManager interface {
	Unpack(payload string) []byte
	Pack(payload []byte) string
}

ProtectedStreamManager is an interface for the different types of StreamManagers which might be used for protecting certain values

type RootData

type RootData struct {
	Groups         []Group             `xml:"Group"`
	DeletedObjects []DeletedObjectData `xml:"DeletedObjects>DeletedObject"`
}

RootData stores the actual content of a database (all enteries sorted into groups and the recycle bin)

func NewRootData

func NewRootData() *RootData

NewRootData returns a RootData struct with good defaults

type SalsaManager

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

SalsaManager is a structure holding the salsa key to lock and unlock protected entries.

func NewSalsaManager

func NewSalsaManager(key [32]byte) SalsaManager

NewSalsaManager returns an instance of SalsaManager

func (SalsaManager) Pack

func (m SalsaManager) Pack(payload []byte) string

Pack locks a given payload using the golang.org/x/crypto/salsa20 implementation

func (SalsaManager) Unpack

func (m SalsaManager) Unpack(payload string) []byte

Unpack unlocks a given payload using the golang.org/x/crypto/salsa20 implementation

type TimeData

type TimeData struct {
	CreationTime         *time.Time  `xml:"CreationTime"`
	LastModificationTime *time.Time  `xml:"LastModificationTime"`
	LastAccessTime       *time.Time  `xml:"LastAccessTime"`
	ExpiryTime           *time.Time  `xml:"ExpiryTime"`
	Expires              boolWrapper `xml:"Expires"`
	UsageCount           int64       `xml:"UsageCount"`
	LocationChanged      *time.Time  `xml:"LocationChanged"`
}

TimeData contains all metadata related to times for groups and entries e.g. the last modification time or the creation time

func NewTimeData

func NewTimeData() TimeData

NewTimeData returns a TimeData struct with good defaults (no expire time, all times set to now)

type UUID

type UUID [16]byte

UUID stores a universal identifier for each group+entry

func NewUUID

func NewUUID() UUID

NewUUID returns a new randomly generated UUID

func (UUID) Compare

func (u UUID) Compare(c UUID) bool

Compares check if c and u are equal, used for searching for a uuid

func (UUID) MarshalText

func (u UUID) MarshalText() (text []byte, err error)

func (*UUID) UnmarshalText

func (u *UUID) UnmarshalText(text []byte) error

type V

type V struct {
	Content   string      `xml:",innerxml"`
	Protected boolWrapper `xml:"Protected,attr,omitempty"`
}

V is a wrapper for the content of a value, so that it can store whether it is protected

type ValueData

type ValueData struct {
	Key   string `xml:"Key"`
	Value V      `xml:"Value"`
}

ValueData is a structure containing key value pairs of information stored in an entry

Jump to

Keyboard shortcuts

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