crypto

package
v0.5.8 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2020 License: MPL-2.0 Imports: 15 Imported by: 26

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	IncorrectEncryptedContentType = errors.New("event content is not instance of *event.EncryptedEventContent")
	NoSessionFound                = errors.New("failed to decrypt megolm event: no session with given ID found")
	DuplicateMessageIndex         = errors.New("duplicate message index")
	WrongRoom                     = errors.New("encrypted megolm event is not intended for this room")
	DeviceKeyMismatch             = errors.New("device keys in event and verified device info do not match")
)
View Source
var (
	UnsupportedAlgorithm                = errors.New("unsupported event encryption algorithm")
	NotEncryptedForMe                   = errors.New("olm event doesn't contain ciphertext for this device")
	UnsupportedOlmMessageType           = errors.New("unsupported olm message type")
	DecryptionFailedWithMatchingSession = errors.New("decryption failed with matching session")
	DecryptionFailedForNormalMessage    = errors.New("decryption failed for normal message")
	SenderMismatch                      = errors.New("mismatched sender in olm payload")
	RecipientMismatch                   = errors.New("mismatched recipient in olm payload")
	RecipientKeyMismatch                = errors.New("mismatched recipient key in olm payload")
)
View Source
var (
	MismatchingDeviceID   = errors.New("mismatching device ID in parameter and keys object")
	MismatchingUserID     = errors.New("mismatching user ID in parameter and keys object")
	MismatchingSigningKey = errors.New("received update for device with different signing key")
	NoSigningKeyFound     = errors.New("didn't find ed25519 signing key")
	NoIdentityKeyFound    = errors.New("didn't find curve25519 identity key")
	InvalidKeySignature   = errors.New("invalid signature on device keys")
)
View Source
var (
	AlreadyShared  = errors.New("group session already shared")
	NoGroupSession = errors.New("no group session created")
)
View Source
var (
	SessionNotShared = errors.New("session has not been shared")
	SessionExpired   = errors.New("session has expired")
)

Functions

func IsShareError added in v0.5.3

func IsShareError(err error) bool

IsShareError returns true if the error is caused by the lack of an outgoing megolm session and can be solved with OlmMachine.ShareGroupSession

Types

type DecryptedOlmEvent added in v0.5.3

type DecryptedOlmEvent struct {
	Source *event.Event `json:"-"`

	SenderKey id.SenderKey `json:"-"`

	Sender        id.UserID    `json:"sender"`
	SenderDevice  id.DeviceID  `json:"sender_device"`
	Keys          OlmEventKeys `json:"keys"`
	Recipient     id.UserID    `json:"recipient"`
	RecipientKeys OlmEventKeys `json:"recipient_keys"`

	Type    event.Type    `json:"type"`
	Content event.Content `json:"content"`
}

DecryptedOlmEvent represents an event that was decrypted from an event encrypted with the m.olm.v1.curve25519-aes-sha2 algorithm.

type DeviceIdentity

type DeviceIdentity struct {
	UserID      id.UserID
	DeviceID    id.DeviceID
	IdentityKey id.Curve25519
	SigningKey  id.Ed25519

	Trust   TrustState
	Deleted bool
	Name    string
}

DeviceIdentity contains the identity details of a device and some additional info.

type ExpirationMixin

type ExpirationMixin struct {
	TimeMixin
	MaxAge time.Duration
}

func (*ExpirationMixin) Expired

func (exp *ExpirationMixin) Expired() bool

type GobStore

type GobStore struct {
	Account          *OlmAccount
	Sessions         map[id.SenderKey]OlmSessionList
	GroupSessions    map[id.RoomID]map[id.SenderKey]map[id.SessionID]*InboundGroupSession
	OutGroupSessions map[id.RoomID]*OutboundGroupSession
	MessageIndices   map[messageIndexKey]messageIndexValue
	Devices          map[id.UserID]map[id.DeviceID]*DeviceIdentity
	// contains filtered or unexported fields
}

GobStore is a simple Store implementation that dumps everything into a .gob file.

func NewGobStore

func NewGobStore(path string) (*GobStore, error)

NewGobStore creates a new GobStore that saves everything to the given file.

func (*GobStore) AddOutboundGroupSession added in v0.4.4

func (gs *GobStore) AddOutboundGroupSession(session *OutboundGroupSession) error

func (*GobStore) AddSession

func (gs *GobStore) AddSession(senderKey id.SenderKey, session *OlmSession) error

func (*GobStore) FilterTrackedUsers added in v0.3.1

func (gs *GobStore) FilterTrackedUsers(users []id.UserID) []id.UserID

func (*GobStore) Flush

func (gs *GobStore) Flush() error

func (*GobStore) GetAccount

func (gs *GobStore) GetAccount() (*OlmAccount, error)

func (*GobStore) GetDevice added in v0.4.7

func (gs *GobStore) GetDevice(userID id.UserID, deviceID id.DeviceID) (*DeviceIdentity, error)

func (*GobStore) GetDevices

func (gs *GobStore) GetDevices(userID id.UserID) (map[id.DeviceID]*DeviceIdentity, error)

func (*GobStore) GetGroupSession

func (gs *GobStore) GetGroupSession(roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID) (*InboundGroupSession, error)

func (*GobStore) GetLatestSession

func (gs *GobStore) GetLatestSession(senderKey id.SenderKey) (*OlmSession, error)

func (*GobStore) GetOutboundGroupSession

func (gs *GobStore) GetOutboundGroupSession(roomID id.RoomID) (*OutboundGroupSession, error)

func (*GobStore) GetSessions

func (gs *GobStore) GetSessions(senderKey id.SenderKey) (OlmSessionList, error)

func (*GobStore) HasSession

func (gs *GobStore) HasSession(senderKey id.SenderKey) bool

func (*GobStore) PutAccount

func (gs *GobStore) PutAccount(account *OlmAccount) error

func (*GobStore) PutDevices

func (gs *GobStore) PutDevices(userID id.UserID, devices map[id.DeviceID]*DeviceIdentity) error

func (*GobStore) PutGroupSession

func (gs *GobStore) PutGroupSession(roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID, igs *InboundGroupSession) error

func (*GobStore) RemoveOutboundGroupSession added in v0.4.4

func (gs *GobStore) RemoveOutboundGroupSession(roomID id.RoomID) error

func (*GobStore) UpdateOutboundGroupSession added in v0.4.4

func (gs *GobStore) UpdateOutboundGroupSession(session *OutboundGroupSession) error

func (*GobStore) UpdateSession added in v0.4.3

func (gs *GobStore) UpdateSession(key id.SenderKey, session *OlmSession) error

func (*GobStore) ValidateMessageIndex

func (gs *GobStore) ValidateMessageIndex(senderKey id.SenderKey, sessionID id.SessionID, eventID id.EventID, index uint, timestamp int64) bool

type InboundGroupSession

type InboundGroupSession struct {
	Internal olm.InboundGroupSession

	SigningKey id.Ed25519
	SenderKey  id.Curve25519
	RoomID     id.RoomID

	ForwardingChains []string
	// contains filtered or unexported fields
}

func NewInboundGroupSession

func NewInboundGroupSession(senderKey id.SenderKey, signingKey id.Ed25519, roomID id.RoomID, sessionKey string) (*InboundGroupSession, error)

func (*InboundGroupSession) ID

func (igs *InboundGroupSession) ID() id.SessionID

type Logger

type Logger interface {
	Error(message string, args ...interface{})
	Warn(message string, args ...interface{})
	Debug(message string, args ...interface{})
	Trace(message string, args ...interface{})
}

Logger is a simple logging struct for OlmMachine. Implementations are recommended to use fmt.Sprintf and manually add a newline after the message.

type OGSState

type OGSState int
const (
	OGSNotShared OGSState = iota
	OGSAlreadyShared
	OGSIgnored
)

type OlmAccount

type OlmAccount struct {
	Internal olm.Account

	Shared bool
	// contains filtered or unexported fields
}

func NewOlmAccount added in v0.4.1

func NewOlmAccount() *OlmAccount

func (*OlmAccount) IdentityKey added in v0.5.3

func (account *OlmAccount) IdentityKey() id.IdentityKey

func (*OlmAccount) Keys added in v0.5.3

func (account *OlmAccount) Keys() (id.SigningKey, id.IdentityKey)

func (*OlmAccount) NewInboundSessionFrom

func (account *OlmAccount) NewInboundSessionFrom(senderKey id.Curve25519, ciphertext string) (*OlmSession, error)

func (*OlmAccount) SigningKey added in v0.5.3

func (account *OlmAccount) SigningKey() id.SigningKey

type OlmEventKeys

type OlmEventKeys struct {
	Ed25519 id.Ed25519 `json:"ed25519"`
}

type OlmMachine

type OlmMachine struct {
	Client *mautrix.Client
	Log    Logger

	CryptoStore Store
	StateStore  StateStore

	AllowUnverifiedDevices bool
	// contains filtered or unexported fields
}

OlmMachine is the main struct for handling Matrix end-to-end encryption.

func NewOlmMachine

func NewOlmMachine(client *mautrix.Client, log Logger, cryptoStore Store, stateStore StateStore) *OlmMachine

NewOlmMachine creates an OlmMachine with the given client, logger and stores.

func (*OlmMachine) DecryptMegolmEvent

func (mach *OlmMachine) DecryptMegolmEvent(evt *event.Event) (*event.Event, error)

DecryptMegolmEvent decrypts an m.room.encrypted event where the algorithm is m.megolm.v1.aes-sha2

func (*OlmMachine) EncryptMegolmEvent

func (mach *OlmMachine) EncryptMegolmEvent(roomID id.RoomID, evtType event.Type, content interface{}) (*event.EncryptedEventContent, error)

EncryptMegolmEvent encrypts data with the m.megolm.v1.aes-sha2 algorithm.

If you use the event.Content struct, make sure you pass a pointer to the struct, as JSON serialization will not work correctly otherwise.

func (*OlmMachine) Fingerprint added in v0.3.3

func (mach *OlmMachine) Fingerprint() string

Fingerprint returns the fingerprint of the Olm account that can be used for non-interactive verification.

func (*OlmMachine) FlushStore

func (mach *OlmMachine) FlushStore() error

FlushStore calls the Flush method of the CryptoStore.

func (*OlmMachine) HandleMemberEvent

func (mach *OlmMachine) HandleMemberEvent(evt *event.Event)

HandleMemberEvent handles a single membership event.

Currently this is not automatically called, so you must add a listener yourself:

client.Syncer.(*mautrix.DefaultSyncer).OnSync(c.crypto.ProcessSyncResponse)

func (*OlmMachine) HandleToDeviceEvent

func (mach *OlmMachine) HandleToDeviceEvent(evt *event.Event)

HandleToDeviceEvent handles a single to-device event. This is automatically called by ProcessSyncResponse, so you don't need to add any custom handlers if you use that method.

func (*OlmMachine) Load

func (mach *OlmMachine) Load() (err error)

Load loads the Olm account information from the crypto store. If there's no olm account, a new one is created. This must be called before using the machine.

func (*OlmMachine) OnDevicesChanged

func (mach *OlmMachine) OnDevicesChanged(userID id.UserID)

OnDevicesChanged finds all shared rooms with the given user and invalidates outbound sessions in those rooms.

This is called automatically whenever a device list change is noticed in ProcessSyncResponse and usually does not need to be called manually.

func (*OlmMachine) ProcessSyncResponse

func (mach *OlmMachine) ProcessSyncResponse(resp *mautrix.RespSync, since string)

ProcessSyncResponse processes a single /sync response.

This can be easily registered into a mautrix client using .OnSync():

client.Syncer.(*mautrix.DefaultSyncer).OnSync(c.crypto.ProcessSyncResponse)

func (*OlmMachine) ShareGroupSession

func (mach *OlmMachine) ShareGroupSession(roomID id.RoomID, users []id.UserID) error

ShareGroupSession shares a group session for a specific room with all the devices of the given user list.

For devices with TrustStateBlacklisted, a m.room_key.withheld event with code=m.blacklisted is sent. If AllowUnverifiedDevices is false, a similar event with code=m.unverified is sent to devices with TrustStateUnset

func (*OlmMachine) ShareKeys

func (mach *OlmMachine) ShareKeys(currentOTKCount int) error

ShareKeys uploads necessary keys to the server.

If the Olm account hasn't been shared, the account keys will be uploaded. If currentOTKCount is less than half of the limit (100 / 2 = 50), enough one-time keys will be uploaded so exactly half of the limit is filled.

type OlmSession

type OlmSession struct {
	Internal olm.Session
	ExpirationMixin
	// contains filtered or unexported fields
}

func (*OlmSession) Decrypt

func (session *OlmSession) Decrypt(ciphertext string, msgType id.OlmMsgType) ([]byte, error)

func (*OlmSession) Encrypt

func (session *OlmSession) Encrypt(plaintext []byte) (id.OlmMsgType, []byte)

func (*OlmSession) ID

func (session *OlmSession) ID() id.SessionID

type OlmSessionList

type OlmSessionList []*OlmSession

OlmSessionList is a list of OlmSessions. It implements sort.Interface in a way that sorts items in reverse alphabetic order, which means the newest session is first.

func (OlmSessionList) Len

func (o OlmSessionList) Len() int

func (OlmSessionList) Less

func (o OlmSessionList) Less(i, j int) bool

func (OlmSessionList) Swap

func (o OlmSessionList) Swap(i, j int)

type OutboundGroupSession

type OutboundGroupSession struct {
	Internal olm.OutboundGroupSession

	ExpirationMixin
	MaxMessages  int
	MessageCount int

	Users  map[UserDevice]OGSState
	RoomID id.RoomID
	Shared bool
	// contains filtered or unexported fields
}

func NewOutboundGroupSession

func NewOutboundGroupSession(roomID id.RoomID) *OutboundGroupSession

func (*OutboundGroupSession) Encrypt

func (ogs *OutboundGroupSession) Encrypt(plaintext []byte) ([]byte, error)

func (*OutboundGroupSession) Expired

func (ogs *OutboundGroupSession) Expired() bool

func (*OutboundGroupSession) ID

func (ogs *OutboundGroupSession) ID() id.SessionID

func (*OutboundGroupSession) ShareContent

func (ogs *OutboundGroupSession) ShareContent() event.Content

type SQLCryptoStore added in v0.5.4

type SQLCryptoStore struct {
	DB      *sql.DB
	Log     Logger
	Dialect string

	DeviceID  id.DeviceID
	SyncToken string
	PickleKey []byte
	Account   *OlmAccount
}

SQLCryptoStore is an implementation of a crypto Store for a database backend.

func NewSQLCryptoStore added in v0.5.4

func NewSQLCryptoStore(db *sql.DB, dialect string, deviceID id.DeviceID, pickleKey []byte, log Logger) *SQLCryptoStore

NewSQLCryptoStore initializes a new crypto Store using the given database, for a device's crypto material. The stored material will be encrypted with the given key.

func (*SQLCryptoStore) AddOutboundGroupSession added in v0.5.4

func (store *SQLCryptoStore) AddOutboundGroupSession(session *OutboundGroupSession) (err error)

AddOutboundGroupSession stores an outbound Megolm session, along with the information about the room and involved devices.

func (*SQLCryptoStore) AddSession added in v0.5.4

func (store *SQLCryptoStore) AddSession(key id.SenderKey, session *OlmSession) error

AddSession persists an Olm session for a sender in the database.

func (*SQLCryptoStore) CreateTables added in v0.5.4

func (store *SQLCryptoStore) CreateTables() error

CreateTables creates the necessary tables in the database for the Store.

func (*SQLCryptoStore) FilterTrackedUsers added in v0.5.4

func (store *SQLCryptoStore) FilterTrackedUsers(users []id.UserID) []id.UserID

FilterTrackedUsers finds all of the user IDs out of the given ones for which the database contains identity information.

func (*SQLCryptoStore) Flush added in v0.5.4

func (store *SQLCryptoStore) Flush() error

Flush does nothing for this implementation as data is already persisted in the database.

func (*SQLCryptoStore) GetAccount added in v0.5.4

func (store *SQLCryptoStore) GetAccount() (*OlmAccount, error)

GetAccount retrieves an OlmAccount from the database.

func (*SQLCryptoStore) GetDevice added in v0.5.4

func (store *SQLCryptoStore) GetDevice(userID id.UserID, deviceID id.DeviceID) (*DeviceIdentity, error)

GetDevice returns the device dentity for a given user and device ID.

func (*SQLCryptoStore) GetDevices added in v0.5.4

func (store *SQLCryptoStore) GetDevices(userID id.UserID) (map[id.DeviceID]*DeviceIdentity, error)

GetDevices returns a map of device IDs to device identities, including the identity and signing keys, for a given user ID.

func (*SQLCryptoStore) GetGroupSession added in v0.5.4

func (store *SQLCryptoStore) GetGroupSession(roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID) (*InboundGroupSession, error)

GetGroupSession retrieves an inbound Megolm group session for a room, sender and session.

func (*SQLCryptoStore) GetLatestSession added in v0.5.4

func (store *SQLCryptoStore) GetLatestSession(key id.SenderKey) (*OlmSession, error)

GetLatestSession retrieves the Olm session for a given sender key from the database that has the largest ID.

func (*SQLCryptoStore) GetNextBatch added in v0.5.4

func (store *SQLCryptoStore) GetNextBatch() string

GetNextBatch retrieves the next sync batch token for the current account.

func (*SQLCryptoStore) GetOutboundGroupSession added in v0.5.4

func (store *SQLCryptoStore) GetOutboundGroupSession(roomID id.RoomID) (*OutboundGroupSession, error)

GetOutboundGroupSession retrieves the outbound Megolm session for the given room ID.

func (*SQLCryptoStore) GetSessions added in v0.5.4

func (store *SQLCryptoStore) GetSessions(key id.SenderKey) (OlmSessionList, error)

GetSessions returns all the known Olm sessions for a sender key.

func (*SQLCryptoStore) HasSession added in v0.5.4

func (store *SQLCryptoStore) HasSession(key id.SenderKey) bool

HasSession returns whether there is an Olm session for the given sender key.

func (*SQLCryptoStore) PutAccount added in v0.5.4

func (store *SQLCryptoStore) PutAccount(account *OlmAccount) error

PutAccount stores an OlmAccount in the database.

func (*SQLCryptoStore) PutDevices added in v0.5.4

func (store *SQLCryptoStore) PutDevices(userID id.UserID, devices map[id.DeviceID]*DeviceIdentity) error

PutDevices stores the device identity information for the given user ID.

func (*SQLCryptoStore) PutGroupSession added in v0.5.4

func (store *SQLCryptoStore) PutGroupSession(roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID, session *InboundGroupSession) error

PutGroupSession stores an inbound Megolm group session for a room, sender and session.

func (*SQLCryptoStore) PutNextBatch added in v0.5.4

func (store *SQLCryptoStore) PutNextBatch(nextBatch string)

PutNextBatch stores the next sync batch token for the current account.

func (*SQLCryptoStore) RemoveOutboundGroupSession added in v0.5.4

func (store *SQLCryptoStore) RemoveOutboundGroupSession(roomID id.RoomID) error

RemoveOutboundGroupSession removes the outbound Megolm session for the given room ID.

func (*SQLCryptoStore) UpdateOutboundGroupSession added in v0.5.4

func (store *SQLCryptoStore) UpdateOutboundGroupSession(session *OutboundGroupSession) error

UpdateOutboundGroupSession replaces an outbound Megolm session with for same room and session ID.

func (*SQLCryptoStore) UpdateSession added in v0.5.4

func (store *SQLCryptoStore) UpdateSession(key id.SenderKey, session *OlmSession) error

UpdateSession replaces the Olm session for a sender in the database.

func (*SQLCryptoStore) ValidateMessageIndex added in v0.5.4

func (store *SQLCryptoStore) ValidateMessageIndex(senderKey id.SenderKey, sessionID id.SessionID, eventID id.EventID, index uint, timestamp int64) bool

ValidateMessageIndex returns whether the given event information match the ones stored in the database for the given sender key, session ID and index. If the event information was not yet stored, it's stored now.

type StateStore

type StateStore interface {
	IsEncrypted(id.RoomID) bool
	FindSharedRooms(id.UserID) []id.RoomID
}

StateStore is used by OlmMachine to get room state information that's needed for encryption.

type Store

type Store interface {
	// Flush ensures that everything in the store is persisted to disk.
	// This doesn't have to do anything, e.g. for database-backed implementations that persist everything immediately.
	Flush() error

	// PutAccount updates the OlmAccount in the store.
	PutAccount(*OlmAccount) error
	// GetAccount returns the OlmAccount in the store that was previously inserted with PutAccount.
	GetAccount() (*OlmAccount, error)

	// AddSession inserts an Olm session into the store.
	AddSession(id.SenderKey, *OlmSession) error
	// HasSession returns whether or not the store has an Olm session with the given sender key.
	HasSession(id.SenderKey) bool
	// GetSessions returns all Olm sessions in the store with the given sender key.
	GetSessions(id.SenderKey) (OlmSessionList, error)
	// GetLatestSession returns the session with the highest session ID (lexiographically sorting).
	// It's usually safe to return the most recently added session if sorting by session ID is too difficult.
	GetLatestSession(id.SenderKey) (*OlmSession, error)
	// UpdateSession updates a session that has previously been inserted with AddSession.
	UpdateSession(id.SenderKey, *OlmSession) error

	// PutGroupSession inserts an inbound Megolm session into the store.
	PutGroupSession(id.RoomID, id.SenderKey, id.SessionID, *InboundGroupSession) error
	// GetGroupSession gets an inbound Megolm session from the store.
	GetGroupSession(id.RoomID, id.SenderKey, id.SessionID) (*InboundGroupSession, error)

	// AddOutboundGroupSession inserts the given outbound Megolm session into the store.
	//
	// The store should index inserted sessions by the RoomID field to support getting and removing sessions.
	// There will only be one outbound session per room ID at a time.
	AddOutboundGroupSession(*OutboundGroupSession) error
	// UpdateOutboundGroupSession updates the given outbound Megolm session in the store.
	UpdateOutboundGroupSession(*OutboundGroupSession) error
	// GetOutboundGroupSession gets the stored outbound Megolm session for the given room ID from the store.
	GetOutboundGroupSession(id.RoomID) (*OutboundGroupSession, error)
	// RemoveOutboundGroupSession removes the stored outbound Megolm session for the given room ID.
	RemoveOutboundGroupSession(id.RoomID) error

	// ValidateMessageIndex validates that the given message details aren't from a replay attack.
	//
	// Implementations should store a map from (senderKey, sessionID, index) to (eventID, timestamp), then use that map
	// to check whether or not the message index is valid:
	//
	// * If the map key doesn't exist, the given values should be stored and this should return true.
	// * If the map key exists and the stored values match the given values, this should return true.
	// * If the map key exists, but the stored values do not match the given values, this should return false.
	ValidateMessageIndex(senderKey id.SenderKey, sessionID id.SessionID, eventID id.EventID, index uint, timestamp int64) bool

	// GetDevices returns a map from device ID to DeviceIdentity containing all devices of a given user.
	GetDevices(id.UserID) (map[id.DeviceID]*DeviceIdentity, error)
	// GetDevice returns a specific device of a given user.
	GetDevice(id.UserID, id.DeviceID) (*DeviceIdentity, error)
	// PutDevices overrides the stored device list for the given user with the given list.
	PutDevices(id.UserID, map[id.DeviceID]*DeviceIdentity) error
	// FilterTrackedUsers returns a filtered version of the given list that only includes user IDs whose device lists
	// have been stored with PutDevices. A user is considered tracked even if the PutDevices list was empty.
	FilterTrackedUsers([]id.UserID) []id.UserID
}

Store is used by OlmMachine to store Olm and Megolm sessions, user device lists and message indices.

General implementation details: * Get methods should not return errors if the requested data does not exist in the store, they should simply return nil. * Update methods may assume that the pointer is the same as what has earlier been added to or fetched from the store.

type TimeMixin

type TimeMixin struct {
	CreationTime time.Time
	UseTime      time.Time
}

type TrustState

type TrustState int

TrustState determines how trusted a device is.

const (
	TrustStateUnset TrustState = iota
	TrustStateVerified
	TrustStateBlacklisted
	TrustStateIgnored
)

type UserDevice

type UserDevice struct {
	UserID   id.UserID
	DeviceID id.DeviceID
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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