refactor to mautrix 0.17.x; update deps

This commit is contained in:
Aine
2024-02-11 20:47:04 +02:00
parent 0a9701f4c9
commit dd0ad4c245
237 changed files with 9091 additions and 3317 deletions

View File

@@ -1,177 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

View File

@@ -1,2 +1,4 @@
# Go olm bindings
Based on [Dhole/go-olm](https://github.com/Dhole/go-olm)
The original project is licensed under the Apache 2.0 license.

View File

@@ -1,3 +1,5 @@
//go:build !goolm
package olm
// #cgo LDFLAGS: -lolm -lstdc++
@@ -155,6 +157,7 @@ func (a *Account) Unpickle(pickled, key []byte) error {
return nil
}
// Deprecated
func (a *Account) GobEncode() ([]byte, error) {
pickled := a.Pickle(pickleKey)
length := base64.RawStdEncoding.DecodedLen(len(pickled))
@@ -163,6 +166,7 @@ func (a *Account) GobEncode() ([]byte, error) {
return rawPickled, err
}
// Deprecated
func (a *Account) GobDecode(rawPickled []byte) error {
if a.int == nil {
*a = *NewBlankAccount()
@@ -173,6 +177,7 @@ func (a *Account) GobDecode(rawPickled []byte) error {
return a.Unpickle(pickled, pickleKey)
}
// Deprecated
func (a *Account) MarshalJSON() ([]byte, error) {
pickled := a.Pickle(pickleKey)
quotes := make([]byte, len(pickled)+2)
@@ -182,6 +187,7 @@ func (a *Account) MarshalJSON() ([]byte, error) {
return quotes, nil
}
// Deprecated
func (a *Account) UnmarshalJSON(data []byte) error {
if len(data) == 0 || data[0] != '"' || data[len(data)-1] != '"' {
return InputNotJSONString

View File

@@ -0,0 +1,154 @@
//go:build goolm
package olm
import (
"encoding/json"
"github.com/tidwall/sjson"
"maunium.net/go/mautrix/crypto/canonicaljson"
"maunium.net/go/mautrix/crypto/goolm/account"
"maunium.net/go/mautrix/id"
)
// Account stores a device account for end to end encrypted messaging.
type Account struct {
account.Account
}
// NewAccount creates a new Account.
func NewAccount() *Account {
a, err := account.NewAccount(nil)
if err != nil {
panic(err)
}
ac := &Account{}
ac.Account = *a
return ac
}
func NewBlankAccount() *Account {
return &Account{}
}
// Clear clears the memory used to back this Account.
func (a *Account) Clear() error {
a.Account = account.Account{}
return nil
}
// Pickle returns an Account as a base64 string. Encrypts the Account using the
// supplied key.
func (a *Account) Pickle(key []byte) []byte {
if len(key) == 0 {
panic(NoKeyProvided)
}
pickled, err := a.Account.Pickle(key)
if err != nil {
panic(err)
}
return pickled
}
// IdentityKeysJSON returns the public parts of the identity keys for the Account.
func (a *Account) IdentityKeysJSON() []byte {
identityKeys, err := a.Account.IdentityKeysJSON()
if err != nil {
panic(err)
}
return identityKeys
}
// Sign returns the signature of a message using the ed25519 key for this
// Account.
func (a *Account) Sign(message []byte) []byte {
if len(message) == 0 {
panic(EmptyInput)
}
signature, err := a.Account.Sign(message)
if err != nil {
panic(err)
}
return signature
}
// SignJSON signs the given JSON object following the Matrix specification:
// https://matrix.org/docs/spec/appendices#signing-json
func (a *Account) SignJSON(obj interface{}) (string, error) {
objJSON, err := json.Marshal(obj)
if err != nil {
return "", err
}
objJSON, _ = sjson.DeleteBytes(objJSON, "unsigned")
objJSON, _ = sjson.DeleteBytes(objJSON, "signatures")
return string(a.Sign(canonicaljson.CanonicalJSONAssumeValid(objJSON))), nil
}
// MaxNumberOfOneTimeKeys returns the largest number of one time keys this
// Account can store.
func (a *Account) MaxNumberOfOneTimeKeys() uint {
return uint(account.MaxOneTimeKeys)
}
// GenOneTimeKeys generates a number of new one time keys. If the total number
// of keys stored by this Account exceeds MaxNumberOfOneTimeKeys then the old
// keys are discarded.
func (a *Account) GenOneTimeKeys(num uint) {
err := a.Account.GenOneTimeKeys(nil, num)
if err != nil {
panic(err)
}
}
// NewOutboundSession creates a new out-bound session for sending messages to a
// given curve25519 identityKey and oneTimeKey. Returns error on failure.
func (a *Account) NewOutboundSession(theirIdentityKey, theirOneTimeKey id.Curve25519) (*Session, error) {
if len(theirIdentityKey) == 0 || len(theirOneTimeKey) == 0 {
return nil, EmptyInput
}
s := &Session{}
newSession, err := a.Account.NewOutboundSession(theirIdentityKey, theirOneTimeKey)
if err != nil {
return nil, err
}
s.OlmSession = *newSession
return s, nil
}
// NewInboundSession creates a new in-bound session for sending/receiving
// messages from an incoming PRE_KEY message. Returns error on failure.
func (a *Account) NewInboundSession(oneTimeKeyMsg string) (*Session, error) {
if len(oneTimeKeyMsg) == 0 {
return nil, EmptyInput
}
s := &Session{}
newSession, err := a.Account.NewInboundSession(nil, []byte(oneTimeKeyMsg))
if err != nil {
return nil, err
}
s.OlmSession = *newSession
return s, nil
}
// NewInboundSessionFrom creates a new in-bound session for sending/receiving
// messages from an incoming PRE_KEY message. Returns error on failure.
func (a *Account) NewInboundSessionFrom(theirIdentityKey id.Curve25519, oneTimeKeyMsg string) (*Session, error) {
if len(theirIdentityKey) == 0 || len(oneTimeKeyMsg) == 0 {
return nil, EmptyInput
}
s := &Session{}
newSession, err := a.Account.NewInboundSession(&theirIdentityKey, []byte(oneTimeKeyMsg))
if err != nil {
return nil, err
}
s.OlmSession = *newSession
return s, nil
}
// RemoveOneTimeKeys removes the one time keys that the session used from the
// Account. Returns error on failure.
func (a *Account) RemoveOneTimeKeys(s *Session) error {
a.Account.RemoveOneTimeKeys(&s.OlmSession)
return nil
}

View File

@@ -1,3 +1,5 @@
//go:build !goolm
package olm
import (

View File

@@ -0,0 +1,23 @@
//go:build goolm
package olm
import (
"errors"
"maunium.net/go/mautrix/crypto/goolm"
)
// Error codes from go-olm
var (
EmptyInput = goolm.ErrEmptyInput
NoKeyProvided = goolm.ErrNoKeyProvided
NotEnoughGoRandom = errors.New("couldn't get enough randomness from crypto/rand")
SignatureNotFound = errors.New("input JSON doesn't contain signature from specified device")
InputNotJSONString = errors.New("input doesn't look like a JSON string")
)
// Error codes from olm code
var (
UnknownMessageIndex = goolm.ErrRatchetNotAvailable
)

View File

@@ -1,3 +1,5 @@
//go:build !goolm
package olm
// #cgo LDFLAGS: -lolm -lstdc++
@@ -147,6 +149,7 @@ func (s *InboundGroupSession) Unpickle(pickled, key []byte) error {
return nil
}
// Deprecated
func (s *InboundGroupSession) GobEncode() ([]byte, error) {
pickled := s.Pickle(pickleKey)
length := base64.RawStdEncoding.DecodedLen(len(pickled))
@@ -155,6 +158,7 @@ func (s *InboundGroupSession) GobEncode() ([]byte, error) {
return rawPickled, err
}
// Deprecated
func (s *InboundGroupSession) GobDecode(rawPickled []byte) error {
if s == nil || s.int == nil {
*s = *NewBlankInboundGroupSession()
@@ -165,6 +169,7 @@ func (s *InboundGroupSession) GobDecode(rawPickled []byte) error {
return s.Unpickle(pickled, pickleKey)
}
// Deprecated
func (s *InboundGroupSession) MarshalJSON() ([]byte, error) {
pickled := s.Pickle(pickleKey)
quotes := make([]byte, len(pickled)+2)
@@ -174,6 +179,7 @@ func (s *InboundGroupSession) MarshalJSON() ([]byte, error) {
return quotes, nil
}
// Deprecated
func (s *InboundGroupSession) UnmarshalJSON(data []byte) error {
if len(data) == 0 || data[0] != '"' || data[len(data)-1] != '"' {
return InputNotJSONString

View File

@@ -0,0 +1,149 @@
//go:build goolm
package olm
import (
"maunium.net/go/mautrix/crypto/goolm/session"
"maunium.net/go/mautrix/id"
)
// InboundGroupSession stores an inbound encrypted messaging session for a
// group.
type InboundGroupSession struct {
session.MegolmInboundSession
}
// InboundGroupSessionFromPickled loads an InboundGroupSession from a pickled
// base64 string. Decrypts the InboundGroupSession using the supplied key.
// Returns error on failure.
func InboundGroupSessionFromPickled(pickled, key []byte) (*InboundGroupSession, error) {
if len(pickled) == 0 {
return nil, EmptyInput
}
lenKey := len(key)
if lenKey == 0 {
key = []byte(" ")
}
megolmSession, err := session.MegolmInboundSessionFromPickled(pickled, key)
if err != nil {
return nil, err
}
return &InboundGroupSession{
MegolmInboundSession: *megolmSession,
}, nil
}
// NewInboundGroupSession creates a new inbound group session from a key
// exported from OutboundGroupSession.Key(). Returns error on failure.
func NewInboundGroupSession(sessionKey []byte) (*InboundGroupSession, error) {
if len(sessionKey) == 0 {
return nil, EmptyInput
}
megolmSession, err := session.NewMegolmInboundSession(sessionKey)
if err != nil {
return nil, err
}
return &InboundGroupSession{
MegolmInboundSession: *megolmSession,
}, nil
}
// InboundGroupSessionImport imports an inbound group session from a previous
// export. Returns error on failure.
func InboundGroupSessionImport(sessionKey []byte) (*InboundGroupSession, error) {
if len(sessionKey) == 0 {
return nil, EmptyInput
}
megolmSession, err := session.NewMegolmInboundSessionFromExport(sessionKey)
if err != nil {
return nil, err
}
return &InboundGroupSession{
MegolmInboundSession: *megolmSession,
}, nil
}
func NewBlankInboundGroupSession() *InboundGroupSession {
return &InboundGroupSession{}
}
// Clear clears the memory used to back this InboundGroupSession.
func (s *InboundGroupSession) Clear() error {
s.MegolmInboundSession = session.MegolmInboundSession{}
return nil
}
// Pickle returns an InboundGroupSession as a base64 string. Encrypts the
// InboundGroupSession using the supplied key.
func (s *InboundGroupSession) Pickle(key []byte) []byte {
if len(key) == 0 {
panic(NoKeyProvided)
}
pickled, err := s.MegolmInboundSession.Pickle(key)
if err != nil {
panic(err)
}
return pickled
}
func (s *InboundGroupSession) Unpickle(pickled, key []byte) error {
if len(key) == 0 {
return NoKeyProvided
} else if len(pickled) == 0 {
return EmptyInput
}
sOlm, err := session.MegolmInboundSessionFromPickled(pickled, key)
if err != nil {
return err
}
s.MegolmInboundSession = *sOlm
return nil
}
// Decrypt decrypts a message using the InboundGroupSession. Returns the the
// plain-text and message index on success. Returns error on failure.
func (s *InboundGroupSession) Decrypt(message []byte) ([]byte, uint, error) {
if len(message) == 0 {
return nil, 0, EmptyInput
}
plaintext, messageIndex, err := s.MegolmInboundSession.Decrypt(message)
if err != nil {
return nil, 0, err
}
return plaintext, uint(messageIndex), nil
}
// ID returns a base64-encoded identifier for this session.
func (s *InboundGroupSession) ID() id.SessionID {
return s.MegolmInboundSession.SessionID()
}
// FirstKnownIndex returns the first message index we know how to decrypt.
func (s *InboundGroupSession) FirstKnownIndex() uint32 {
return s.MegolmInboundSession.InitialRatchet.Counter
}
// IsVerified check if the session has been verified as a valid session. (A
// session is verified either because the original session share was signed, or
// because we have subsequently successfully decrypted a message.)
func (s *InboundGroupSession) IsVerified() uint {
if s.MegolmInboundSession.SigningKeyVerified {
return 1
}
return 0
}
// Export returns the base64-encoded ratchet key for this session, at the given
// index, in a format which can be used by
// InboundGroupSession.InboundGroupSessionImport(). Encrypts the
// InboundGroupSession using the supplied key. Returns error on failure.
// if we do not have a session key corresponding to the given index (ie, it was
// sent before the session key was shared with us) the error will be
// returned.
func (s *InboundGroupSession) Export(messageIndex uint32) ([]byte, error) {
res, err := s.MegolmInboundSession.SessionExportMessage(messageIndex)
if err != nil {
return nil, err
}
return res, nil
}

View File

@@ -1,3 +1,5 @@
//go:build !goolm
package olm
// #cgo LDFLAGS: -lolm -lstdc++

20
vendor/maunium.net/go/mautrix/crypto/olm/olm_goolm.go generated vendored Normal file
View File

@@ -0,0 +1,20 @@
//go:build goolm
package olm
import (
"maunium.net/go/mautrix/id"
)
// Signatures is the data structure used to sign JSON objects.
type Signatures map[id.UserID]map[id.DeviceKeyID]string
// Version returns the version number of the olm library.
func Version() (major, minor, patch uint8) {
return 3, 2, 15
}
// SetPickleKey sets the global pickle key used when encoding structs with Gob or JSON.
func SetPickleKey(key []byte) {
panic("gob and json encoding is deprecated and not supported with goolm")
}

View File

@@ -1,3 +1,5 @@
//go:build !goolm
package olm
// #cgo LDFLAGS: -lolm -lstdc++
@@ -122,6 +124,7 @@ func (s *OutboundGroupSession) Unpickle(pickled, key []byte) error {
return nil
}
// Deprecated
func (s *OutboundGroupSession) GobEncode() ([]byte, error) {
pickled := s.Pickle(pickleKey)
length := base64.RawStdEncoding.DecodedLen(len(pickled))
@@ -130,6 +133,7 @@ func (s *OutboundGroupSession) GobEncode() ([]byte, error) {
return rawPickled, err
}
// Deprecated
func (s *OutboundGroupSession) GobDecode(rawPickled []byte) error {
if s == nil || s.int == nil {
*s = *NewBlankOutboundGroupSession()
@@ -140,6 +144,7 @@ func (s *OutboundGroupSession) GobDecode(rawPickled []byte) error {
return s.Unpickle(pickled, pickleKey)
}
// Deprecated
func (s *OutboundGroupSession) MarshalJSON() ([]byte, error) {
pickled := s.Pickle(pickleKey)
quotes := make([]byte, len(pickled)+2)
@@ -149,6 +154,7 @@ func (s *OutboundGroupSession) MarshalJSON() ([]byte, error) {
return quotes, nil
}
// Deprecated
func (s *OutboundGroupSession) UnmarshalJSON(data []byte) error {
if len(data) == 0 || data[0] != '"' || data[len(data)-1] != '"' {
return InputNotJSONString

View File

@@ -0,0 +1,111 @@
//go:build goolm
package olm
import (
"maunium.net/go/mautrix/crypto/goolm/session"
"maunium.net/go/mautrix/id"
)
// OutboundGroupSession stores an outbound encrypted messaging session for a
// group.
type OutboundGroupSession struct {
session.MegolmOutboundSession
}
// OutboundGroupSessionFromPickled loads an OutboundGroupSession from a pickled
// base64 string. Decrypts the OutboundGroupSession using the supplied key.
// Returns error on failure. If the key doesn't match the one used to encrypt
// the OutboundGroupSession then the error will be "BAD_SESSION_KEY". If the
// base64 couldn't be decoded then the error will be "INVALID_BASE64".
func OutboundGroupSessionFromPickled(pickled, key []byte) (*OutboundGroupSession, error) {
if len(pickled) == 0 {
return nil, EmptyInput
}
lenKey := len(key)
if lenKey == 0 {
key = []byte(" ")
}
megolmSession, err := session.MegolmOutboundSessionFromPickled(pickled, key)
if err != nil {
return nil, err
}
return &OutboundGroupSession{
MegolmOutboundSession: *megolmSession,
}, nil
}
// NewOutboundGroupSession creates a new outbound group session.
func NewOutboundGroupSession() *OutboundGroupSession {
megolmSession, err := session.NewMegolmOutboundSession()
if err != nil {
panic(err)
}
return &OutboundGroupSession{
MegolmOutboundSession: *megolmSession,
}
}
// newOutboundGroupSession initialises an empty OutboundGroupSession.
func NewBlankOutboundGroupSession() *OutboundGroupSession {
return &OutboundGroupSession{}
}
// Clear clears the memory used to back this OutboundGroupSession.
func (s *OutboundGroupSession) Clear() error {
s.MegolmOutboundSession = session.MegolmOutboundSession{}
return nil
}
// Pickle returns an OutboundGroupSession as a base64 string. Encrypts the
// OutboundGroupSession using the supplied key.
func (s *OutboundGroupSession) Pickle(key []byte) []byte {
if len(key) == 0 {
panic(NoKeyProvided)
}
pickled, err := s.MegolmOutboundSession.Pickle(key)
if err != nil {
panic(err)
}
return pickled
}
func (s *OutboundGroupSession) Unpickle(pickled, key []byte) error {
if len(key) == 0 {
return NoKeyProvided
}
return s.MegolmOutboundSession.Unpickle(pickled, key)
}
// Encrypt encrypts a message using the Session. Returns the encrypted message
// as base64.
func (s *OutboundGroupSession) Encrypt(plaintext []byte) []byte {
if len(plaintext) == 0 {
panic(EmptyInput)
}
message, err := s.MegolmOutboundSession.Encrypt(plaintext)
if err != nil {
panic(err)
}
return message
}
// ID returns a base64-encoded identifier for this session.
func (s *OutboundGroupSession) ID() id.SessionID {
return s.MegolmOutboundSession.SessionID()
}
// MessageIndex returns the message index for this session. Each message is
// sent with an increasing index; this returns the index for the next message.
func (s *OutboundGroupSession) MessageIndex() uint {
return uint(s.MegolmOutboundSession.Ratchet.Counter)
}
// Key returns the base64-encoded current ratchet key for this session.
func (s *OutboundGroupSession) Key() string {
message, err := s.MegolmOutboundSession.SessionSharingMessage()
if err != nil {
panic(err)
}
return string(message)
}

View File

@@ -1,3 +1,5 @@
//go:build !goolm
package olm
// #cgo LDFLAGS: -lolm -lstdc++

71
vendor/maunium.net/go/mautrix/crypto/olm/pk_goolm.go generated vendored Normal file
View File

@@ -0,0 +1,71 @@
//go:build goolm
package olm
import (
"encoding/json"
"github.com/tidwall/sjson"
"maunium.net/go/mautrix/crypto/canonicaljson"
"maunium.net/go/mautrix/crypto/goolm/pk"
"maunium.net/go/mautrix/id"
)
// PkSigning stores a key pair for signing messages.
type PkSigning struct {
pk.Signing
PublicKey id.Ed25519
Seed []byte
}
// Clear clears the underlying memory of a PkSigning object.
func (p *PkSigning) Clear() {
p.Signing = pk.Signing{}
}
// NewPkSigningFromSeed creates a new PkSigning object using the given seed.
func NewPkSigningFromSeed(seed []byte) (*PkSigning, error) {
p := &PkSigning{}
signing, err := pk.NewSigningFromSeed(seed)
if err != nil {
return nil, err
}
p.Signing = *signing
p.Seed = seed
p.PublicKey = p.Signing.PublicKey()
return p, nil
}
// NewPkSigning creates a new PkSigning object, containing a key pair for signing messages.
func NewPkSigning() (*PkSigning, error) {
p := &PkSigning{}
signing, err := pk.NewSigning()
if err != nil {
return nil, err
}
p.Signing = *signing
p.Seed = signing.Seed
p.PublicKey = p.Signing.PublicKey()
return p, err
}
// Sign creates a signature for the given message using this key.
func (p *PkSigning) Sign(message []byte) ([]byte, error) {
return p.Signing.Sign(message), nil
}
// SignJSON creates a signature for the given object after encoding it to canonical JSON.
func (p *PkSigning) SignJSON(obj interface{}) (string, error) {
objJSON, err := json.Marshal(obj)
if err != nil {
return "", err
}
objJSON, _ = sjson.DeleteBytes(objJSON, "unsigned")
objJSON, _ = sjson.DeleteBytes(objJSON, "signatures")
signature, err := p.Sign(canonicaljson.CanonicalJSONAssumeValid(objJSON))
if err != nil {
return "", err
}
return string(signature), nil
}

View File

@@ -1,3 +1,5 @@
//go:build !goolm
package olm
// #cgo LDFLAGS: -lolm -lstdc++
@@ -155,6 +157,7 @@ func (s *Session) Unpickle(pickled, key []byte) error {
return nil
}
// Deprecated
func (s *Session) GobEncode() ([]byte, error) {
pickled := s.Pickle(pickleKey)
length := base64.RawStdEncoding.DecodedLen(len(pickled))
@@ -163,6 +166,7 @@ func (s *Session) GobEncode() ([]byte, error) {
return rawPickled, err
}
// Deprecated
func (s *Session) GobDecode(rawPickled []byte) error {
if s == nil || s.int == nil {
*s = *NewBlankSession()
@@ -173,6 +177,7 @@ func (s *Session) GobDecode(rawPickled []byte) error {
return s.Unpickle(pickled, pickleKey)
}
// Deprecated
func (s *Session) MarshalJSON() ([]byte, error) {
pickled := s.Pickle(pickleKey)
quotes := make([]byte, len(pickled)+2)
@@ -182,6 +187,7 @@ func (s *Session) MarshalJSON() ([]byte, error) {
return quotes, nil
}
// Deprecated
func (s *Session) UnmarshalJSON(data []byte) error {
if len(data) == 0 || len(data) == 0 || data[0] != '"' || data[len(data)-1] != '"' {
return InputNotJSONString

View File

@@ -0,0 +1,110 @@
//go:build goolm
package olm
import (
"maunium.net/go/mautrix/crypto/goolm/session"
"maunium.net/go/mautrix/id"
)
// Session stores an end to end encrypted messaging session.
type Session struct {
session.OlmSession
}
// SessionFromPickled loads a Session from a pickled base64 string. Decrypts
// the Session using the supplied key. Returns error on failure.
func SessionFromPickled(pickled, key []byte) (*Session, error) {
if len(pickled) == 0 {
return nil, EmptyInput
}
s := NewBlankSession()
return s, s.Unpickle(pickled, key)
}
func NewBlankSession() *Session {
return &Session{}
}
// Clear clears the memory used to back this Session.
func (s *Session) Clear() error {
s.OlmSession = session.OlmSession{}
return nil
}
// Pickle returns a Session as a base64 string. Encrypts the Session using the
// supplied key.
func (s *Session) Pickle(key []byte) []byte {
if len(key) == 0 {
panic(NoKeyProvided)
}
pickled, err := s.OlmSession.Pickle(key)
if err != nil {
panic(err)
}
return pickled
}
func (s *Session) Unpickle(pickled, key []byte) error {
if len(key) == 0 {
return NoKeyProvided
} else if len(pickled) == 0 {
return EmptyInput
}
sOlm, err := session.OlmSessionFromPickled(pickled, key)
if err != nil {
return err
}
s.OlmSession = *sOlm
return nil
}
// MatchesInboundSession checks if the PRE_KEY message is for this in-bound
// Session. This can happen if multiple messages are sent to this Account
// before this Account sends a message in reply. Returns true if the session
// matches. Returns false if the session does not match. Returns error on
// failure.
func (s *Session) MatchesInboundSession(oneTimeKeyMsg string) (bool, error) {
return s.MatchesInboundSessionFrom("", oneTimeKeyMsg)
}
// MatchesInboundSessionFrom checks if the PRE_KEY message is for this in-bound
// Session. This can happen if multiple messages are sent to this Account
// before this Account sends a message in reply. Returns true if the session
// matches. Returns false if the session does not match. Returns error on
// failure.
func (s *Session) MatchesInboundSessionFrom(theirIdentityKey, oneTimeKeyMsg string) (bool, error) {
if theirIdentityKey != "" {
theirKey := id.Curve25519(theirIdentityKey)
return s.OlmSession.MatchesInboundSessionFrom(&theirKey, []byte(oneTimeKeyMsg))
}
return s.OlmSession.MatchesInboundSessionFrom(nil, []byte(oneTimeKeyMsg))
}
// Encrypt encrypts a message using the Session. Returns the encrypted message
// as base64.
func (s *Session) Encrypt(plaintext []byte) (id.OlmMsgType, []byte) {
if len(plaintext) == 0 {
panic(EmptyInput)
}
messageType, message, err := s.OlmSession.Encrypt(plaintext, nil)
if err != nil {
panic(err)
}
return messageType, message
}
// Decrypt decrypts a message using the Session. Returns the the plain-text on
// success. Returns error on failure.
func (s *Session) Decrypt(message string, msgType id.OlmMsgType) ([]byte, error) {
if len(message) == 0 {
return nil, EmptyInput
}
return s.OlmSession.Decrypt([]byte(message), msgType)
}
// Describe generates a string describing the internal state of an olm session for debugging and logging purposes.
func (s *Session) Describe() string {
return s.OlmSession.Describe()
}

View File

@@ -1,3 +1,5 @@
//go:build !goolm
package olm
// #cgo LDFLAGS: -lolm -lstdc++

View File

@@ -0,0 +1,92 @@
//go:build goolm
package olm
import (
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"go.mau.fi/util/exgjson"
"maunium.net/go/mautrix/crypto/canonicaljson"
"maunium.net/go/mautrix/crypto/goolm/utilities"
"maunium.net/go/mautrix/id"
)
// Utility stores the necessary state to perform hash and signature
// verification operations.
type Utility struct{}
// Clear clears the memory used to back this utility.
func (u *Utility) Clear() error {
return nil
}
// NewUtility creates a new utility.
func NewUtility() *Utility {
return &Utility{}
}
// Sha256 calculates the SHA-256 hash of the input and encodes it as base64.
func (u *Utility) Sha256(input string) string {
if len(input) == 0 {
panic(EmptyInput)
}
hash := sha256.Sum256([]byte(input))
return base64.RawStdEncoding.EncodeToString(hash[:])
}
// VerifySignature verifies an ed25519 signature. Returns true if the verification
// suceeds or false otherwise. Returns error on failure. If the key was too
// small then the error will be "INVALID_BASE64".
func (u *Utility) VerifySignature(message string, key id.Ed25519, signature string) (ok bool, err error) {
if len(message) == 0 || len(key) == 0 || len(signature) == 0 {
return false, EmptyInput
}
return utilities.VerifySignature([]byte(message), key, []byte(signature))
}
// VerifySignatureJSON verifies the signature in the JSON object _obj following
// the Matrix specification:
// https://matrix.org/speculator/spec/drafts%2Fe2e/appendices.html#signing-json
// If the _obj is a struct, the `json` tags will be honored.
func (u *Utility) VerifySignatureJSON(obj interface{}, userID id.UserID, keyName string, key id.Ed25519) (bool, error) {
var err error
objJSON, ok := obj.(json.RawMessage)
if !ok {
objJSON, err = json.Marshal(obj)
if err != nil {
return false, err
}
}
sig := gjson.GetBytes(objJSON, exgjson.Path("signatures", string(userID), fmt.Sprintf("ed25519:%s", keyName)))
if !sig.Exists() || sig.Type != gjson.String {
return false, SignatureNotFound
}
objJSON, err = sjson.DeleteBytes(objJSON, "unsigned")
if err != nil {
return false, err
}
objJSON, err = sjson.DeleteBytes(objJSON, "signatures")
if err != nil {
return false, err
}
objJSONString := string(canonicaljson.CanonicalJSONAssumeValid(objJSON))
return u.VerifySignature(objJSONString, key, sig.Str)
}
// VerifySignatureJSON verifies the signature in the JSON object _obj following
// the Matrix specification:
// https://matrix.org/speculator/spec/drafts%2Fe2e/appendices.html#signing-json
// This function is a wrapper over Utility.VerifySignatureJSON that creates and
// destroys the Utility object transparently.
// If the _obj is a struct, the `json` tags will be honored.
func VerifySignatureJSON(obj interface{}, userID id.UserID, keyName string, key id.Ed25519) (bool, error) {
u := NewUtility()
defer u.Clear()
return u.VerifySignatureJSON(obj, userID, keyName, key)
}

View File

@@ -1,3 +1,5 @@
//go:build !nosas && !goolm
package olm
// #cgo LDFLAGS: -lolm -lstdc++

View File

@@ -0,0 +1,23 @@
//go:build !nosas && goolm
package olm
import (
"maunium.net/go/mautrix/crypto/goolm/sas"
)
// SAS stores an Olm Short Authentication String (SAS) object.
type SAS struct {
sas.SAS
}
// NewSAS creates a new SAS object.
func NewSAS() *SAS {
newSAS, err := sas.New()
if err != nil {
panic(err)
}
return &SAS{
SAS: *newSAS,
}
}