add vendoring

This commit is contained in:
Aine
2022-11-16 12:08:51 +02:00
parent 14751cbf3a
commit c1d33fe3cb
1104 changed files with 759066 additions and 0 deletions

177
vendor/maunium.net/go/mautrix/crypto/olm/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,177 @@
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

2
vendor/maunium.net/go/mautrix/crypto/olm/README.md generated vendored Normal file
View File

@@ -0,0 +1,2 @@
# Go olm bindings
Based on [Dhole/go-olm](https://github.com/Dhole/go-olm)

398
vendor/maunium.net/go/mautrix/crypto/olm/account.go generated vendored Normal file
View File

@@ -0,0 +1,398 @@
package olm
// #cgo LDFLAGS: -lolm -lstdc++
// #include <olm/olm.h>
import "C"
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"unsafe"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"maunium.net/go/mautrix/crypto/canonicaljson"
"maunium.net/go/mautrix/id"
)
// Account stores a device account for end to end encrypted messaging.
type Account struct {
int *C.OlmAccount
mem []byte
}
// AccountFromPickled loads an Account from a pickled base64 string. Decrypts
// the Account using the supplied key. Returns error on failure. If the key
// doesn't match the one used to encrypt the Account then the error will be
// "BAD_ACCOUNT_KEY". If the base64 couldn't be decoded then the error will be
// "INVALID_BASE64".
func AccountFromPickled(pickled, key []byte) (*Account, error) {
if len(pickled) == 0 {
return nil, EmptyInput
}
a := NewBlankAccount()
return a, a.Unpickle(pickled, key)
}
func NewBlankAccount() *Account {
memory := make([]byte, accountSize())
return &Account{
int: C.olm_account(unsafe.Pointer(&memory[0])),
mem: memory,
}
}
// NewAccount creates a new Account.
func NewAccount() *Account {
a := NewBlankAccount()
random := make([]byte, a.createRandomLen()+1)
_, err := rand.Read(random)
if err != nil {
panic(NotEnoughGoRandom)
}
r := C.olm_create_account(
(*C.OlmAccount)(a.int),
unsafe.Pointer(&random[0]),
C.size_t(len(random)))
if r == errorVal() {
panic(a.lastError())
} else {
return a
}
}
// accountSize returns the size of an account object in bytes.
func accountSize() uint {
return uint(C.olm_account_size())
}
// lastError returns an error describing the most recent error to happen to an
// account.
func (a *Account) lastError() error {
return convertError(C.GoString(C.olm_account_last_error((*C.OlmAccount)(a.int))))
}
// Clear clears the memory used to back this Account.
func (a *Account) Clear() error {
r := C.olm_clear_account((*C.OlmAccount)(a.int))
if r == errorVal() {
return a.lastError()
} else {
return nil
}
}
// pickleLen returns the number of bytes needed to store an Account.
func (a *Account) pickleLen() uint {
return uint(C.olm_pickle_account_length((*C.OlmAccount)(a.int)))
}
// createRandomLen returns the number of random bytes needed to create an
// Account.
func (a *Account) createRandomLen() uint {
return uint(C.olm_create_account_random_length((*C.OlmAccount)(a.int)))
}
// identityKeysLen returns the size of the output buffer needed to hold the
// identity keys.
func (a *Account) identityKeysLen() uint {
return uint(C.olm_account_identity_keys_length((*C.OlmAccount)(a.int)))
}
// signatureLen returns the length of an ed25519 signature encoded as base64.
func (a *Account) signatureLen() uint {
return uint(C.olm_account_signature_length((*C.OlmAccount)(a.int)))
}
// oneTimeKeysLen returns the size of the output buffer needed to hold the one
// time keys.
func (a *Account) oneTimeKeysLen() uint {
return uint(C.olm_account_one_time_keys_length((*C.OlmAccount)(a.int)))
}
// genOneTimeKeysRandomLen returns the number of random bytes needed to
// generate a given number of new one time keys.
func (a *Account) genOneTimeKeysRandomLen(num uint) uint {
return uint(C.olm_account_generate_one_time_keys_random_length(
(*C.OlmAccount)(a.int),
C.size_t(num)))
}
// 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 := make([]byte, a.pickleLen())
r := C.olm_pickle_account(
(*C.OlmAccount)(a.int),
unsafe.Pointer(&key[0]),
C.size_t(len(key)),
unsafe.Pointer(&pickled[0]),
C.size_t(len(pickled)))
if r == errorVal() {
panic(a.lastError())
}
return pickled[:r]
}
func (a *Account) Unpickle(pickled, key []byte) error {
if len(key) == 0 {
return NoKeyProvided
}
r := C.olm_unpickle_account(
(*C.OlmAccount)(a.int),
unsafe.Pointer(&key[0]),
C.size_t(len(key)),
unsafe.Pointer(&pickled[0]),
C.size_t(len(pickled)))
if r == errorVal() {
return a.lastError()
}
return nil
}
func (a *Account) GobEncode() ([]byte, error) {
pickled := a.Pickle(pickleKey)
length := base64.RawStdEncoding.DecodedLen(len(pickled))
rawPickled := make([]byte, length)
_, err := base64.RawStdEncoding.Decode(rawPickled, pickled)
return rawPickled, err
}
func (a *Account) GobDecode(rawPickled []byte) error {
if a.int == nil {
*a = *NewBlankAccount()
}
length := base64.RawStdEncoding.EncodedLen(len(rawPickled))
pickled := make([]byte, length)
base64.RawStdEncoding.Encode(pickled, rawPickled)
return a.Unpickle(pickled, pickleKey)
}
func (a *Account) MarshalJSON() ([]byte, error) {
pickled := a.Pickle(pickleKey)
quotes := make([]byte, len(pickled)+2)
quotes[0] = '"'
quotes[len(quotes)-1] = '"'
copy(quotes[1:len(quotes)-1], pickled)
return quotes, nil
}
func (a *Account) UnmarshalJSON(data []byte) error {
if len(data) == 0 || data[0] != '"' || data[len(data)-1] != '"' {
return InputNotJSONString
}
if a.int == nil {
*a = *NewBlankAccount()
}
return a.Unpickle(data[1:len(data)-1], pickleKey)
}
// IdentityKeysJSON returns the public parts of the identity keys for the Account.
func (a *Account) IdentityKeysJSON() []byte {
identityKeys := make([]byte, a.identityKeysLen())
r := C.olm_account_identity_keys(
(*C.OlmAccount)(a.int),
unsafe.Pointer(&identityKeys[0]),
C.size_t(len(identityKeys)))
if r == errorVal() {
panic(a.lastError())
} else {
return identityKeys
}
}
// IdentityKeys returns the public parts of the Ed25519 and Curve25519 identity
// keys for the Account.
func (a *Account) IdentityKeys() (id.Ed25519, id.Curve25519) {
identityKeysJSON := a.IdentityKeysJSON()
results := gjson.GetManyBytes(identityKeysJSON, "ed25519", "curve25519")
return id.Ed25519(results[0].Str), id.Curve25519(results[1].Str)
}
// 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 := make([]byte, a.signatureLen())
r := C.olm_account_sign(
(*C.OlmAccount)(a.int),
unsafe.Pointer(&message[0]),
C.size_t(len(message)),
unsafe.Pointer(&signature[0]),
C.size_t(len(signature)))
if r == errorVal() {
panic(a.lastError())
}
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
}
// OneTimeKeys returns the public parts of the unpublished one time keys for
// the Account.
//
// The returned data is a struct with the single value "Curve25519", which is
// itself an object mapping key id to base64-encoded Curve25519 key. For
// example:
//
// {
// Curve25519: {
// "AAAAAA": "wo76WcYtb0Vk/pBOdmduiGJ0wIEjW4IBMbbQn7aSnTo",
// "AAAAAB": "LRvjo46L1X2vx69sS9QNFD29HWulxrmW11Up5AfAjgU"
// }
// }
func (a *Account) OneTimeKeys() map[string]id.Curve25519 {
oneTimeKeysJSON := make([]byte, a.oneTimeKeysLen())
r := C.olm_account_one_time_keys(
(*C.OlmAccount)(a.int),
unsafe.Pointer(&oneTimeKeysJSON[0]),
C.size_t(len(oneTimeKeysJSON)))
if r == errorVal() {
panic(a.lastError())
}
var oneTimeKeys struct {
Curve25519 map[string]id.Curve25519 `json:"curve25519"`
}
err := json.Unmarshal(oneTimeKeysJSON, &oneTimeKeys)
if err != nil {
panic(err)
}
return oneTimeKeys.Curve25519
}
// MarkKeysAsPublished marks the current set of one time keys as being
// published.
func (a *Account) MarkKeysAsPublished() {
C.olm_account_mark_keys_as_published((*C.OlmAccount)(a.int))
}
// MaxNumberOfOneTimeKeys returns the largest number of one time keys this
// Account can store.
func (a *Account) MaxNumberOfOneTimeKeys() uint {
return uint(C.olm_account_max_number_of_one_time_keys((*C.OlmAccount)(a.int)))
}
// 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) {
random := make([]byte, a.genOneTimeKeysRandomLen(num)+1)
_, err := rand.Read(random)
if err != nil {
panic(NotEnoughGoRandom)
}
r := C.olm_account_generate_one_time_keys(
(*C.OlmAccount)(a.int),
C.size_t(num),
unsafe.Pointer(&random[0]),
C.size_t(len(random)))
if r == errorVal() {
panic(a.lastError())
}
}
// NewOutboundSession creates a new out-bound session for sending messages to a
// given curve25519 identityKey and oneTimeKey. Returns error on failure. If the
// keys couldn't be decoded as base64 then the error will be "INVALID_BASE64"
func (a *Account) NewOutboundSession(theirIdentityKey, theirOneTimeKey id.Curve25519) (*Session, error) {
if len(theirIdentityKey) == 0 || len(theirOneTimeKey) == 0 {
return nil, EmptyInput
}
s := NewBlankSession()
random := make([]byte, s.createOutboundRandomLen()+1)
_, err := rand.Read(random)
if err != nil {
panic(NotEnoughGoRandom)
}
r := C.olm_create_outbound_session(
(*C.OlmSession)(s.int),
(*C.OlmAccount)(a.int),
unsafe.Pointer(&([]byte(theirIdentityKey)[0])),
C.size_t(len(theirIdentityKey)),
unsafe.Pointer(&([]byte(theirOneTimeKey)[0])),
C.size_t(len(theirOneTimeKey)),
unsafe.Pointer(&random[0]),
C.size_t(len(random)))
if r == errorVal() {
return nil, s.lastError()
}
return s, nil
}
// NewInboundSession creates a new in-bound session for sending/receiving
// messages from an incoming PRE_KEY message. Returns error on failure. If
// the base64 couldn't be decoded then the error will be "INVALID_BASE64". If
// the message was for an unsupported protocol version then the error will be
// "BAD_MESSAGE_VERSION". If the message couldn't be decoded then then the
// error will be "BAD_MESSAGE_FORMAT". If the message refers to an unknown one
// time key then the error will be "BAD_MESSAGE_KEY_ID".
func (a *Account) NewInboundSession(oneTimeKeyMsg string) (*Session, error) {
if len(oneTimeKeyMsg) == 0 {
return nil, EmptyInput
}
s := NewBlankSession()
r := C.olm_create_inbound_session(
(*C.OlmSession)(s.int),
(*C.OlmAccount)(a.int),
unsafe.Pointer(&([]byte(oneTimeKeyMsg)[0])),
C.size_t(len(oneTimeKeyMsg)))
if r == errorVal() {
return nil, s.lastError()
}
return s, nil
}
// NewInboundSessionFrom creates a new in-bound session for sending/receiving
// messages from an incoming PRE_KEY message. Returns error on failure. If
// the base64 couldn't be decoded then the error will be "INVALID_BASE64". If
// the message was for an unsupported protocol version then the error will be
// "BAD_MESSAGE_VERSION". If the message couldn't be decoded then then the
// error will be "BAD_MESSAGE_FORMAT". If the message refers to an unknown one
// time key then the error will be "BAD_MESSAGE_KEY_ID".
func (a *Account) NewInboundSessionFrom(theirIdentityKey id.Curve25519, oneTimeKeyMsg string) (*Session, error) {
if len(theirIdentityKey) == 0 || len(oneTimeKeyMsg) == 0 {
return nil, EmptyInput
}
s := NewBlankSession()
r := C.olm_create_inbound_session_from(
(*C.OlmSession)(s.int),
(*C.OlmAccount)(a.int),
unsafe.Pointer(&([]byte(theirIdentityKey)[0])),
C.size_t(len(theirIdentityKey)),
unsafe.Pointer(&([]byte(oneTimeKeyMsg)[0])),
C.size_t(len(oneTimeKeyMsg)))
if r == errorVal() {
return nil, s.lastError()
}
return s, nil
}
// RemoveOneTimeKeys removes the one time keys that the session used from the
// Account. Returns error on failure. If the Account doesn't have any
// matching one time keys then the error will be "BAD_MESSAGE_KEY_ID".
func (a *Account) RemoveOneTimeKeys(s *Session) error {
r := C.olm_remove_one_time_keys(
(*C.OlmAccount)(a.int),
(*C.OlmSession)(s.int))
if r == errorVal() {
return a.lastError()
}
return nil
}

60
vendor/maunium.net/go/mautrix/crypto/olm/error.go generated vendored Normal file
View File

@@ -0,0 +1,60 @@
package olm
import (
"errors"
"fmt"
)
// Error codes from go-olm
var (
EmptyInput = errors.New("empty input")
NoKeyProvided = errors.New("no pickle key provided")
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 (
NotEnoughRandom = errors.New("not enough entropy was supplied")
OutputBufferTooSmall = errors.New("supplied output buffer is too small")
BadMessageVersion = errors.New("the message version is unsupported")
BadMessageFormat = errors.New("the message couldn't be decoded")
BadMessageMAC = errors.New("the message couldn't be decrypted")
BadMessageKeyID = errors.New("the message references an unknown key ID")
InvalidBase64 = errors.New("the input base64 was invalid")
BadAccountKey = errors.New("the supplied account key is invalid")
UnknownPickleVersion = errors.New("the pickled object is too new")
CorruptedPickle = errors.New("the pickled object couldn't be decoded")
BadSessionKey = errors.New("attempt to initialise an inbound group session from an invalid session key")
UnknownMessageIndex = errors.New("attempt to decode a message whose index is earlier than our earliest known session key")
BadLegacyAccountPickle = errors.New("attempt to unpickle an account which uses pickle version 1")
BadSignature = errors.New("received message had a bad signature")
InputBufferTooSmall = errors.New("the input data was too small to be valid")
)
var errorMap = map[string]error{
"NOT_ENOUGH_RANDOM": NotEnoughRandom,
"OUTPUT_BUFFER_TOO_SMALL": OutputBufferTooSmall,
"BAD_MESSAGE_VERSION": BadMessageVersion,
"BAD_MESSAGE_FORMAT": BadMessageFormat,
"BAD_MESSAGE_MAC": BadMessageMAC,
"BAD_MESSAGE_KEY_ID": BadMessageKeyID,
"INVALID_BASE64": InvalidBase64,
"BAD_ACCOUNT_KEY": BadAccountKey,
"UNKNOWN_PICKLE_VERSION": UnknownPickleVersion,
"CORRUPTED_PICKLE": CorruptedPickle,
"BAD_SESSION_KEY": BadSessionKey,
"UNKNOWN_MESSAGE_INDEX": UnknownMessageIndex,
"BAD_LEGACY_ACCOUNT_PICKLE": BadLegacyAccountPickle,
"BAD_SIGNATURE": BadSignature,
"INPUT_BUFFER_TOO_SMALL": InputBufferTooSmall,
}
func convertError(errCode string) error {
err, ok := errorMap[errCode]
if ok {
return err
}
return fmt.Errorf("unknown error: %s", errCode)
}

View File

@@ -0,0 +1,302 @@
package olm
// #cgo LDFLAGS: -lolm -lstdc++
// #include <olm/olm.h>
import "C"
import (
"encoding/base64"
"unsafe"
"maunium.net/go/mautrix/id"
)
// InboundGroupSession stores an inbound encrypted messaging session for a
// group.
type InboundGroupSession struct {
int *C.OlmInboundGroupSession
mem []byte
}
// InboundGroupSessionFromPickled loads an InboundGroupSession from a pickled
// base64 string. Decrypts the InboundGroupSession using the supplied key.
// Returns error on failure. If the key doesn't match the one used to encrypt
// the InboundGroupSession then the error will be "BAD_SESSION_KEY". If the
// base64 couldn't be decoded then the error will be "INVALID_BASE64".
func InboundGroupSessionFromPickled(pickled, key []byte) (*InboundGroupSession, error) {
if len(pickled) == 0 {
return nil, EmptyInput
}
lenKey := len(key)
if lenKey == 0 {
key = []byte(" ")
}
s := NewBlankInboundGroupSession()
return s, s.Unpickle(pickled, key)
}
// NewInboundGroupSession creates a new inbound group session from a key
// exported from OutboundGroupSession.Key(). Returns error on failure.
// If the sessionKey is not valid base64 the error will be
// "OLM_INVALID_BASE64". If the session_key is invalid the error will be
// "OLM_BAD_SESSION_KEY".
func NewInboundGroupSession(sessionKey []byte) (*InboundGroupSession, error) {
if len(sessionKey) == 0 {
return nil, EmptyInput
}
s := NewBlankInboundGroupSession()
r := C.olm_init_inbound_group_session(
(*C.OlmInboundGroupSession)(s.int),
(*C.uint8_t)(&sessionKey[0]),
C.size_t(len(sessionKey)))
if r == errorVal() {
return nil, s.lastError()
}
return s, nil
}
// InboundGroupSessionImport imports an inbound group session from a previous
// export. Returns error on failure. If the sessionKey is not valid base64
// the error will be "OLM_INVALID_BASE64". If the session_key is invalid the
// error will be "OLM_BAD_SESSION_KEY".
func InboundGroupSessionImport(sessionKey []byte) (*InboundGroupSession, error) {
if len(sessionKey) == 0 {
return nil, EmptyInput
}
s := NewBlankInboundGroupSession()
r := C.olm_import_inbound_group_session(
(*C.OlmInboundGroupSession)(s.int),
(*C.uint8_t)(&sessionKey[0]),
C.size_t(len(sessionKey)))
if r == errorVal() {
return nil, s.lastError()
}
return s, nil
}
// inboundGroupSessionSize is the size of an inbound group session object in
// bytes.
func inboundGroupSessionSize() uint {
return uint(C.olm_inbound_group_session_size())
}
// newInboundGroupSession initialises an empty InboundGroupSession.
func NewBlankInboundGroupSession() *InboundGroupSession {
memory := make([]byte, inboundGroupSessionSize())
return &InboundGroupSession{
int: C.olm_inbound_group_session(unsafe.Pointer(&memory[0])),
mem: memory,
}
}
// lastError returns an error describing the most recent error to happen to an
// inbound group session.
func (s *InboundGroupSession) lastError() error {
return convertError(C.GoString(C.olm_inbound_group_session_last_error((*C.OlmInboundGroupSession)(s.int))))
}
// Clear clears the memory used to back this InboundGroupSession.
func (s *InboundGroupSession) Clear() error {
r := C.olm_clear_inbound_group_session((*C.OlmInboundGroupSession)(s.int))
if r == errorVal() {
return s.lastError()
}
return nil
}
// pickleLen returns the number of bytes needed to store an inbound group
// session.
func (s *InboundGroupSession) pickleLen() uint {
return uint(C.olm_pickle_inbound_group_session_length((*C.OlmInboundGroupSession)(s.int)))
}
// 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 := make([]byte, s.pickleLen())
r := C.olm_pickle_inbound_group_session(
(*C.OlmInboundGroupSession)(s.int),
unsafe.Pointer(&key[0]),
C.size_t(len(key)),
unsafe.Pointer(&pickled[0]),
C.size_t(len(pickled)))
if r == errorVal() {
panic(s.lastError())
}
return pickled[:r]
}
func (s *InboundGroupSession) Unpickle(pickled, key []byte) error {
if len(key) == 0 {
return NoKeyProvided
} else if len(pickled) == 0 {
return EmptyInput
}
r := C.olm_unpickle_inbound_group_session(
(*C.OlmInboundGroupSession)(s.int),
unsafe.Pointer(&key[0]),
C.size_t(len(key)),
unsafe.Pointer(&pickled[0]),
C.size_t(len(pickled)))
if r == errorVal() {
return s.lastError()
}
return nil
}
func (s *InboundGroupSession) GobEncode() ([]byte, error) {
pickled := s.Pickle(pickleKey)
length := base64.RawStdEncoding.DecodedLen(len(pickled))
rawPickled := make([]byte, length)
_, err := base64.RawStdEncoding.Decode(rawPickled, pickled)
return rawPickled, err
}
func (s *InboundGroupSession) GobDecode(rawPickled []byte) error {
if s == nil || s.int == nil {
*s = *NewBlankInboundGroupSession()
}
length := base64.RawStdEncoding.EncodedLen(len(rawPickled))
pickled := make([]byte, length)
base64.RawStdEncoding.Encode(pickled, rawPickled)
return s.Unpickle(pickled, pickleKey)
}
func (s *InboundGroupSession) MarshalJSON() ([]byte, error) {
pickled := s.Pickle(pickleKey)
quotes := make([]byte, len(pickled)+2)
quotes[0] = '"'
quotes[len(quotes)-1] = '"'
copy(quotes[1:len(quotes)-1], pickled)
return quotes, nil
}
func (s *InboundGroupSession) UnmarshalJSON(data []byte) error {
if len(data) == 0 || data[0] != '"' || data[len(data)-1] != '"' {
return InputNotJSONString
}
if s == nil || s.int == nil {
*s = *NewBlankInboundGroupSession()
}
return s.Unpickle(data[1:len(data)-1], pickleKey)
}
func clone(original []byte) []byte {
clone := make([]byte, len(original))
copy(clone, original)
return clone
}
// decryptMaxPlaintextLen returns the maximum number of bytes of plain-text a
// given message could decode to. The actual size could be different due to
// padding. Returns error on failure. If the message base64 couldn't be
// decoded then the error will be "INVALID_BASE64". If the message is for an
// unsupported version of the protocol then the error will be
// "BAD_MESSAGE_VERSION". If the message couldn't be decoded then the error
// will be "BAD_MESSAGE_FORMAT".
func (s *InboundGroupSession) decryptMaxPlaintextLen(message []byte) (uint, error) {
if len(message) == 0 {
return 0, EmptyInput
}
// olm_group_decrypt_max_plaintext_length destroys the input, so we have to clone it
message = clone(message)
r := C.olm_group_decrypt_max_plaintext_length(
(*C.OlmInboundGroupSession)(s.int),
(*C.uint8_t)(&message[0]),
C.size_t(len(message)))
if r == errorVal() {
return 0, s.lastError()
}
return uint(r), nil
}
// Decrypt decrypts a message using the InboundGroupSession. Returns the the
// plain-text and message index on success. Returns error on failure. If the
// base64 couldn't be decoded then the error will be "INVALID_BASE64". If the
// message is for an unsupported version of the protocol then the error will be
// "BAD_MESSAGE_VERSION". If the message couldn't be decoded then the error
// will be BAD_MESSAGE_FORMAT". If the MAC on the message was invalid then the
// error will be "BAD_MESSAGE_MAC". If we do not have a session key
// corresponding to the message's index (ie, it was sent before the session key
// was shared with us) the error will be "OLM_UNKNOWN_MESSAGE_INDEX".
func (s *InboundGroupSession) Decrypt(message []byte) ([]byte, uint, error) {
if len(message) == 0 {
return nil, 0, EmptyInput
}
decryptMaxPlaintextLen, err := s.decryptMaxPlaintextLen(message)
if err != nil {
return nil, 0, err
}
plaintext := make([]byte, decryptMaxPlaintextLen)
var messageIndex uint32
r := C.olm_group_decrypt(
(*C.OlmInboundGroupSession)(s.int),
(*C.uint8_t)(&message[0]),
C.size_t(len(message)),
(*C.uint8_t)(&plaintext[0]),
C.size_t(len(plaintext)),
(*C.uint32_t)(&messageIndex))
if r == errorVal() {
return nil, 0, s.lastError()
}
return plaintext[:r], uint(messageIndex), nil
}
// sessionIdLen returns the number of bytes needed to store a session ID.
func (s *InboundGroupSession) sessionIdLen() uint {
return uint(C.olm_inbound_group_session_id_length((*C.OlmInboundGroupSession)(s.int)))
}
// ID returns a base64-encoded identifier for this session.
func (s *InboundGroupSession) ID() id.SessionID {
sessionID := make([]byte, s.sessionIdLen())
r := C.olm_inbound_group_session_id(
(*C.OlmInboundGroupSession)(s.int),
(*C.uint8_t)(&sessionID[0]),
C.size_t(len(sessionID)))
if r == errorVal() {
panic(s.lastError())
}
return id.SessionID(sessionID[:r])
}
// FirstKnownIndex returns the first message index we know how to decrypt.
func (s *InboundGroupSession) FirstKnownIndex() uint32 {
return uint32(C.olm_inbound_group_session_first_known_index((*C.OlmInboundGroupSession)(s.int)))
}
// 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 {
return uint(C.olm_inbound_group_session_is_verified((*C.OlmInboundGroupSession)(s.int)))
}
// exportLen returns the number of bytes needed to export an inbound group
// session.
func (s *InboundGroupSession) exportLen() uint {
return uint(C.olm_export_inbound_group_session_length((*C.OlmInboundGroupSession)(s.int)))
}
// 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
// "OLM_UNKNOWN_MESSAGE_INDEX".
func (s *InboundGroupSession) Export(messageIndex uint32) (string, error) {
key := make([]byte, s.exportLen())
r := C.olm_export_inbound_group_session(
(*C.OlmInboundGroupSession)(s.int),
(*C.uint8_t)(&key[0]),
C.size_t(len(key)),
C.uint32_t(messageIndex))
if r == errorVal() {
return "", s.lastError()
}
return string(key[:r]), nil
}

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

@@ -0,0 +1,32 @@
package olm
// #cgo LDFLAGS: -lolm -lstdc++
// #include <olm/olm.h>
import "C"
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) {
C.olm_get_library_version(
(*C.uint8_t)(&major),
(*C.uint8_t)(&minor),
(*C.uint8_t)(&patch))
return
}
// errorVal returns the value that olm functions return if there was an error.
func errorVal() C.size_t {
return C.olm_error()
}
var pickleKey = []byte("maunium.net/go/mautrix/crypto/olm")
// SetPickleKey sets the global pickle key used when encoding structs with Gob or JSON.
func SetPickleKey(key []byte) {
pickleKey = key
}

View File

@@ -0,0 +1,233 @@
package olm
// #cgo LDFLAGS: -lolm -lstdc++
// #include <olm/olm.h>
import "C"
import (
"crypto/rand"
"encoding/base64"
"unsafe"
"maunium.net/go/mautrix/id"
)
// OutboundGroupSession stores an outbound encrypted messaging session for a
// group.
type OutboundGroupSession struct {
int *C.OlmOutboundGroupSession
mem []byte
}
// 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
}
s := NewBlankOutboundGroupSession()
return s, s.Unpickle(pickled, key)
}
// NewOutboundGroupSession creates a new outbound group session.
func NewOutboundGroupSession() *OutboundGroupSession {
s := NewBlankOutboundGroupSession()
random := make([]byte, s.createRandomLen()+1)
_, err := rand.Read(random)
if err != nil {
panic(NotEnoughGoRandom)
}
r := C.olm_init_outbound_group_session(
(*C.OlmOutboundGroupSession)(s.int),
(*C.uint8_t)(&random[0]),
C.size_t(len(random)))
if r == errorVal() {
panic(s.lastError())
}
return s
}
// outboundGroupSessionSize is the size of an outbound group session object in
// bytes.
func outboundGroupSessionSize() uint {
return uint(C.olm_outbound_group_session_size())
}
// newOutboundGroupSession initialises an empty OutboundGroupSession.
func NewBlankOutboundGroupSession() *OutboundGroupSession {
memory := make([]byte, outboundGroupSessionSize())
return &OutboundGroupSession{
int: C.olm_outbound_group_session(unsafe.Pointer(&memory[0])),
mem: memory,
}
}
// lastError returns an error describing the most recent error to happen to an
// outbound group session.
func (s *OutboundGroupSession) lastError() error {
return convertError(C.GoString(C.olm_outbound_group_session_last_error((*C.OlmOutboundGroupSession)(s.int))))
}
// Clear clears the memory used to back this OutboundGroupSession.
func (s *OutboundGroupSession) Clear() error {
r := C.olm_clear_outbound_group_session((*C.OlmOutboundGroupSession)(s.int))
if r == errorVal() {
return s.lastError()
} else {
return nil
}
}
// pickleLen returns the number of bytes needed to store an outbound group
// session.
func (s *OutboundGroupSession) pickleLen() uint {
return uint(C.olm_pickle_outbound_group_session_length((*C.OlmOutboundGroupSession)(s.int)))
}
// 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 := make([]byte, s.pickleLen())
r := C.olm_pickle_outbound_group_session(
(*C.OlmOutboundGroupSession)(s.int),
unsafe.Pointer(&key[0]),
C.size_t(len(key)),
unsafe.Pointer(&pickled[0]),
C.size_t(len(pickled)))
if r == errorVal() {
panic(s.lastError())
}
return pickled[:r]
}
func (s *OutboundGroupSession) Unpickle(pickled, key []byte) error {
if len(key) == 0 {
return NoKeyProvided
}
r := C.olm_unpickle_outbound_group_session(
(*C.OlmOutboundGroupSession)(s.int),
unsafe.Pointer(&key[0]),
C.size_t(len(key)),
unsafe.Pointer(&pickled[0]),
C.size_t(len(pickled)))
if r == errorVal() {
return s.lastError()
}
return nil
}
func (s *OutboundGroupSession) GobEncode() ([]byte, error) {
pickled := s.Pickle(pickleKey)
length := base64.RawStdEncoding.DecodedLen(len(pickled))
rawPickled := make([]byte, length)
_, err := base64.RawStdEncoding.Decode(rawPickled, pickled)
return rawPickled, err
}
func (s *OutboundGroupSession) GobDecode(rawPickled []byte) error {
if s == nil || s.int == nil {
*s = *NewBlankOutboundGroupSession()
}
length := base64.RawStdEncoding.EncodedLen(len(rawPickled))
pickled := make([]byte, length)
base64.RawStdEncoding.Encode(pickled, rawPickled)
return s.Unpickle(pickled, pickleKey)
}
func (s *OutboundGroupSession) MarshalJSON() ([]byte, error) {
pickled := s.Pickle(pickleKey)
quotes := make([]byte, len(pickled)+2)
quotes[0] = '"'
quotes[len(quotes)-1] = '"'
copy(quotes[1:len(quotes)-1], pickled)
return quotes, nil
}
func (s *OutboundGroupSession) UnmarshalJSON(data []byte) error {
if len(data) == 0 || data[0] != '"' || data[len(data)-1] != '"' {
return InputNotJSONString
}
if s == nil || s.int == nil {
*s = *NewBlankOutboundGroupSession()
}
return s.Unpickle(data[1:len(data)-1], pickleKey)
}
// createRandomLen returns the number of random bytes needed to create an
// Account.
func (s *OutboundGroupSession) createRandomLen() uint {
return uint(C.olm_init_outbound_group_session_random_length((*C.OlmOutboundGroupSession)(s.int)))
}
// encryptMsgLen returns the size of the next message in bytes for the given
// number of plain-text bytes.
func (s *OutboundGroupSession) encryptMsgLen(plainTextLen int) uint {
return uint(C.olm_group_encrypt_message_length((*C.OlmOutboundGroupSession)(s.int), C.size_t(plainTextLen)))
}
// 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 := make([]byte, s.encryptMsgLen(len(plaintext)))
r := C.olm_group_encrypt(
(*C.OlmOutboundGroupSession)(s.int),
(*C.uint8_t)(&plaintext[0]),
C.size_t(len(plaintext)),
(*C.uint8_t)(&message[0]),
C.size_t(len(message)))
if r == errorVal() {
panic(s.lastError())
}
return message[:r]
}
// sessionIdLen returns the number of bytes needed to store a session ID.
func (s *OutboundGroupSession) sessionIdLen() uint {
return uint(C.olm_outbound_group_session_id_length((*C.OlmOutboundGroupSession)(s.int)))
}
// ID returns a base64-encoded identifier for this session.
func (s *OutboundGroupSession) ID() id.SessionID {
sessionID := make([]byte, s.sessionIdLen())
r := C.olm_outbound_group_session_id(
(*C.OlmOutboundGroupSession)(s.int),
(*C.uint8_t)(&sessionID[0]),
C.size_t(len(sessionID)))
if r == errorVal() {
panic(s.lastError())
}
return id.SessionID(sessionID[:r])
}
// 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(C.olm_outbound_group_session_message_index((*C.OlmOutboundGroupSession)(s.int)))
}
// sessionKeyLen returns the number of bytes needed to store a session key.
func (s *OutboundGroupSession) sessionKeyLen() uint {
return uint(C.olm_outbound_group_session_key_length((*C.OlmOutboundGroupSession)(s.int)))
}
// Key returns the base64-encoded current ratchet key for this session.
func (s *OutboundGroupSession) Key() string {
sessionKey := make([]byte, s.sessionKeyLen())
r := C.olm_outbound_group_session_key(
(*C.OlmOutboundGroupSession)(s.int),
(*C.uint8_t)(&sessionKey[0]),
C.size_t(len(sessionKey)))
if r == errorVal() {
panic(s.lastError())
}
return string(sessionKey[:r])
}

111
vendor/maunium.net/go/mautrix/crypto/olm/pk.go generated vendored Normal file
View File

@@ -0,0 +1,111 @@
package olm
// #cgo LDFLAGS: -lolm -lstdc++
// #include <olm/olm.h>
// #include <olm/pk.h>
import "C"
import (
"crypto/rand"
"encoding/json"
"unsafe"
"github.com/tidwall/sjson"
"maunium.net/go/mautrix/crypto/canonicaljson"
"maunium.net/go/mautrix/id"
)
// PkSigning stores a key pair for signing messages.
type PkSigning struct {
int *C.OlmPkSigning
mem []byte
PublicKey id.Ed25519
Seed []byte
}
func pkSigningSize() uint {
return uint(C.olm_pk_signing_size())
}
func pkSigningSeedLength() uint {
return uint(C.olm_pk_signing_seed_length())
}
func pkSigningPublicKeyLength() uint {
return uint(C.olm_pk_signing_public_key_length())
}
func pkSigningSignatureLength() uint {
return uint(C.olm_pk_signature_length())
}
func NewBlankPkSigning() *PkSigning {
memory := make([]byte, pkSigningSize())
return &PkSigning{
int: C.olm_pk_signing(unsafe.Pointer(&memory[0])),
mem: memory,
}
}
// Clear clears the underlying memory of a PkSigning object.
func (p *PkSigning) Clear() {
C.olm_clear_pk_signing((*C.OlmPkSigning)(p.int))
}
// NewPkSigningFromSeed creates a new PkSigning object using the given seed.
func NewPkSigningFromSeed(seed []byte) (*PkSigning, error) {
p := NewBlankPkSigning()
p.Clear()
pubKey := make([]byte, pkSigningPublicKeyLength())
if C.olm_pk_signing_key_from_seed((*C.OlmPkSigning)(p.int),
unsafe.Pointer(&pubKey[0]), C.size_t(len(pubKey)),
unsafe.Pointer(&seed[0]), C.size_t(len(seed))) == errorVal() {
return nil, p.lastError()
}
p.PublicKey = id.Ed25519(pubKey)
p.Seed = seed
return p, nil
}
// NewPkSigning creates a new PkSigning object, containing a key pair for signing messages.
func NewPkSigning() (*PkSigning, error) {
// Generate the seed
seed := make([]byte, pkSigningSeedLength())
_, err := rand.Read(seed)
if err != nil {
panic(NotEnoughGoRandom)
}
pk, err := NewPkSigningFromSeed(seed)
return pk, err
}
// Sign creates a signature for the given message using this key.
func (p *PkSigning) Sign(message []byte) ([]byte, error) {
signature := make([]byte, pkSigningSignatureLength())
if C.olm_pk_sign((*C.OlmPkSigning)(p.int), (*C.uint8_t)(unsafe.Pointer(&message[0])), C.size_t(len(message)),
(*C.uint8_t)(unsafe.Pointer(&signature[0])), C.size_t(len(signature))) == errorVal() {
return nil, p.lastError()
}
return signature, 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
}
// lastError returns the last error that happened in relation to this PkSigning object.
func (p *PkSigning) lastError() error {
return convertError(C.GoString(C.olm_pk_signing_last_error((*C.OlmPkSigning)(p.int))))
}

355
vendor/maunium.net/go/mautrix/crypto/olm/session.go generated vendored Normal file
View File

@@ -0,0 +1,355 @@
package olm
// #cgo LDFLAGS: -lolm -lstdc++
// #include <olm/olm.h>
// #include <stdlib.h>
// #include <stdio.h>
// void olm_session_describe(OlmSession * session, char *buf, size_t buflen) __attribute__((weak));
// void meowlm_session_describe(OlmSession * session, char *buf, size_t buflen) {
// if (olm_session_describe) {
// olm_session_describe(session, buf, buflen);
// } else {
// sprintf(buf, "olm_session_describe not supported");
// }
// }
import "C"
import (
"crypto/rand"
"encoding/base64"
"unsafe"
"maunium.net/go/mautrix/id"
)
// Session stores an end to end encrypted messaging session.
type Session struct {
int *C.OlmSession
mem []byte
}
// sessionSize is the size of a session object in bytes.
func sessionSize() uint {
return uint(C.olm_session_size())
}
// SessionFromPickled loads a Session from a pickled base64 string. Decrypts
// the Session using the supplied key. Returns error on failure. If the key
// doesn't match the one used to encrypt the Session then the error will be
// "BAD_SESSION_KEY". If the base64 couldn't be decoded then the error will be
// "INVALID_BASE64".
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 {
memory := make([]byte, sessionSize())
return &Session{
int: C.olm_session(unsafe.Pointer(&memory[0])),
mem: memory,
}
}
// lastError returns an error describing the most recent error to happen to a
// session.
func (s *Session) lastError() error {
return convertError(C.GoString(C.olm_session_last_error((*C.OlmSession)(s.int))))
}
// Clear clears the memory used to back this Session.
func (s *Session) Clear() error {
r := C.olm_clear_session((*C.OlmSession)(s.int))
if r == errorVal() {
return s.lastError()
}
return nil
}
// pickleLen returns the number of bytes needed to store a session.
func (s *Session) pickleLen() uint {
return uint(C.olm_pickle_session_length((*C.OlmSession)(s.int)))
}
// createOutboundRandomLen returns the number of random bytes needed to create
// an outbound session.
func (s *Session) createOutboundRandomLen() uint {
return uint(C.olm_create_outbound_session_random_length((*C.OlmSession)(s.int)))
}
// idLen returns the length of the buffer needed to return the id for this
// session.
func (s *Session) idLen() uint {
return uint(C.olm_session_id_length((*C.OlmSession)(s.int)))
}
// encryptRandomLen returns the number of random bytes needed to encrypt the
// next message.
func (s *Session) encryptRandomLen() uint {
return uint(C.olm_encrypt_random_length((*C.OlmSession)(s.int)))
}
// encryptMsgLen returns the size of the next message in bytes for the given
// number of plain-text bytes.
func (s *Session) encryptMsgLen(plainTextLen int) uint {
return uint(C.olm_encrypt_message_length((*C.OlmSession)(s.int), C.size_t(plainTextLen)))
}
// decryptMaxPlaintextLen returns the maximum number of bytes of plain-text a
// given message could decode to. The actual size could be different due to
// padding. Returns error on failure. If the message base64 couldn't be
// decoded then the error will be "INVALID_BASE64". If the message is for an
// unsupported version of the protocol then the error will be
// "BAD_MESSAGE_VERSION". If the message couldn't be decoded then the error
// will be "BAD_MESSAGE_FORMAT".
func (s *Session) decryptMaxPlaintextLen(message string, msgType id.OlmMsgType) (uint, error) {
if len(message) == 0 {
return 0, EmptyInput
}
r := C.olm_decrypt_max_plaintext_length(
(*C.OlmSession)(s.int),
C.size_t(msgType),
unsafe.Pointer(C.CString(message)),
C.size_t(len(message)))
if r == errorVal() {
return 0, s.lastError()
}
return uint(r), 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 := make([]byte, s.pickleLen())
r := C.olm_pickle_session(
(*C.OlmSession)(s.int),
unsafe.Pointer(&key[0]),
C.size_t(len(key)),
unsafe.Pointer(&pickled[0]),
C.size_t(len(pickled)))
if r == errorVal() {
panic(s.lastError())
}
return pickled[:r]
}
func (s *Session) Unpickle(pickled, key []byte) error {
if len(key) == 0 {
return NoKeyProvided
}
r := C.olm_unpickle_session(
(*C.OlmSession)(s.int),
unsafe.Pointer(&key[0]),
C.size_t(len(key)),
unsafe.Pointer(&pickled[0]),
C.size_t(len(pickled)))
if r == errorVal() {
return s.lastError()
}
return nil
}
func (s *Session) GobEncode() ([]byte, error) {
pickled := s.Pickle(pickleKey)
length := base64.RawStdEncoding.DecodedLen(len(pickled))
rawPickled := make([]byte, length)
_, err := base64.RawStdEncoding.Decode(rawPickled, pickled)
return rawPickled, err
}
func (s *Session) GobDecode(rawPickled []byte) error {
if s == nil || s.int == nil {
*s = *NewBlankSession()
}
length := base64.RawStdEncoding.EncodedLen(len(rawPickled))
pickled := make([]byte, length)
base64.RawStdEncoding.Encode(pickled, rawPickled)
return s.Unpickle(pickled, pickleKey)
}
func (s *Session) MarshalJSON() ([]byte, error) {
pickled := s.Pickle(pickleKey)
quotes := make([]byte, len(pickled)+2)
quotes[0] = '"'
quotes[len(quotes)-1] = '"'
copy(quotes[1:len(quotes)-1], pickled)
return quotes, nil
}
func (s *Session) UnmarshalJSON(data []byte) error {
if len(data) == 0 || len(data) == 0 || data[0] != '"' || data[len(data)-1] != '"' {
return InputNotJSONString
}
if s == nil || s.int == nil {
*s = *NewBlankSession()
}
return s.Unpickle(data[1:len(data)-1], pickleKey)
}
// Id returns an identifier for this Session. Will be the same for both ends
// of the conversation.
func (s *Session) ID() id.SessionID {
sessionID := make([]byte, s.idLen())
r := C.olm_session_id(
(*C.OlmSession)(s.int),
unsafe.Pointer(&sessionID[0]),
C.size_t(len(sessionID)))
if r == errorVal() {
panic(s.lastError())
}
return id.SessionID(sessionID)
}
// HasReceivedMessage returns true if this session has received any message.
func (s *Session) HasReceivedMessage() bool {
switch C.olm_session_has_received_message((*C.OlmSession)(s.int)) {
case 0:
return false
default:
return true
}
}
// 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. If the base64 couldn't be decoded then the error will be
// "INVALID_BASE64". If the message was for an unsupported protocol version
// then the error will be "BAD_MESSAGE_VERSION". If the message couldn't be
// decoded then then the error will be "BAD_MESSAGE_FORMAT".
func (s *Session) MatchesInboundSession(oneTimeKeyMsg string) (bool, error) {
if len(oneTimeKeyMsg) == 0 {
return false, EmptyInput
}
r := C.olm_matches_inbound_session(
(*C.OlmSession)(s.int),
unsafe.Pointer(&([]byte(oneTimeKeyMsg))[0]),
C.size_t(len(oneTimeKeyMsg)))
if r == 1 {
return true, nil
} else if r == 0 {
return false, nil
} else { // if r == errorVal()
return false, s.lastError()
}
}
// 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. If the base64 couldn't be decoded then the error will be
// "INVALID_BASE64". If the message was for an unsupported protocol version
// then the error will be "BAD_MESSAGE_VERSION". If the message couldn't be
// decoded then then the error will be "BAD_MESSAGE_FORMAT".
func (s *Session) MatchesInboundSessionFrom(theirIdentityKey, oneTimeKeyMsg string) (bool, error) {
if len(theirIdentityKey) == 0 || len(oneTimeKeyMsg) == 0 {
return false, EmptyInput
}
r := C.olm_matches_inbound_session_from(
(*C.OlmSession)(s.int),
unsafe.Pointer(&([]byte(theirIdentityKey))[0]),
C.size_t(len(theirIdentityKey)),
unsafe.Pointer(&([]byte(oneTimeKeyMsg))[0]),
C.size_t(len(oneTimeKeyMsg)))
if r == 1 {
return true, nil
} else if r == 0 {
return false, nil
} else { // if r == errorVal()
return false, s.lastError()
}
}
// EncryptMsgType returns the type of the next message that Encrypt will
// return. Returns MsgTypePreKey if the message will be a PRE_KEY message.
// Returns MsgTypeMsg if the message will be a normal message. Returns error
// on failure.
func (s *Session) EncryptMsgType() id.OlmMsgType {
switch C.olm_encrypt_message_type((*C.OlmSession)(s.int)) {
case C.size_t(id.OlmMsgTypePreKey):
return id.OlmMsgTypePreKey
case C.size_t(id.OlmMsgTypeMsg):
return id.OlmMsgTypeMsg
default:
panic("olm_encrypt_message_type returned invalid result")
}
}
// 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)
}
// Make the slice be at least length 1
random := make([]byte, s.encryptRandomLen()+1)
_, err := rand.Read(random)
if err != nil {
panic(NotEnoughGoRandom)
}
messageType := s.EncryptMsgType()
message := make([]byte, s.encryptMsgLen(len(plaintext)))
r := C.olm_encrypt(
(*C.OlmSession)(s.int),
unsafe.Pointer(&plaintext[0]),
C.size_t(len(plaintext)),
unsafe.Pointer(&random[0]),
C.size_t(len(random)),
unsafe.Pointer(&message[0]),
C.size_t(len(message)))
if r == errorVal() {
panic(s.lastError())
}
return messageType, message[:r]
}
// Decrypt decrypts a message using the Session. Returns the the plain-text on
// success. Returns error on failure. If the base64 couldn't be decoded then
// the error will be "INVALID_BASE64". If the message is for an unsupported
// version of the protocol then the error will be "BAD_MESSAGE_VERSION". If
// the message couldn't be decoded then the error will be BAD_MESSAGE_FORMAT".
// If the MAC on the message was invalid then the error will be
// "BAD_MESSAGE_MAC".
func (s *Session) Decrypt(message string, msgType id.OlmMsgType) ([]byte, error) {
if len(message) == 0 {
return nil, EmptyInput
}
decryptMaxPlaintextLen, err := s.decryptMaxPlaintextLen(message, msgType)
if err != nil {
return nil, err
}
plaintext := make([]byte, decryptMaxPlaintextLen)
r := C.olm_decrypt(
(*C.OlmSession)(s.int),
C.size_t(msgType),
unsafe.Pointer(&([]byte(message))[0]),
C.size_t(len(message)),
unsafe.Pointer(&plaintext[0]),
C.size_t(len(plaintext)))
if r == errorVal() {
return nil, s.lastError()
}
return plaintext[:r], nil
}
// https://gitlab.matrix.org/matrix-org/olm/-/blob/3.2.8/include/olm/olm.h#L392-393
const maxDescribeSize = 600
// Describe generates a string describing the internal state of an olm session for debugging and logging purposes.
func (s *Session) Describe() string {
desc := (*C.char)(C.malloc(C.size_t(maxDescribeSize)))
defer C.free(unsafe.Pointer(desc))
C.meowlm_session_describe(
(*C.OlmSession)(s.int),
desc,
C.size_t(maxDescribeSize))
return C.GoString(desc)
}

140
vendor/maunium.net/go/mautrix/crypto/olm/utility.go generated vendored Normal file
View File

@@ -0,0 +1,140 @@
package olm
// #cgo LDFLAGS: -lolm -lstdc++
// #include <olm/olm.h>
import "C"
import (
"encoding/json"
"fmt"
"unsafe"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"maunium.net/go/mautrix/crypto/canonicaljson"
"maunium.net/go/mautrix/id"
"maunium.net/go/mautrix/util"
)
// Utility stores the necessary state to perform hash and signature
// verification operations.
type Utility struct {
int *C.OlmUtility
mem []byte
}
// utilitySize returns the size of a utility object in bytes.
func utilitySize() uint {
return uint(C.olm_utility_size())
}
// sha256Len returns the length of the buffer needed to hold the SHA-256 hash.
func (u *Utility) sha256Len() uint {
return uint(C.olm_sha256_length((*C.OlmUtility)(u.int)))
}
// lastError returns an error describing the most recent error to happen to a
// utility.
func (u *Utility) lastError() error {
return convertError(C.GoString(C.olm_utility_last_error((*C.OlmUtility)(u.int))))
}
// Clear clears the memory used to back this utility.
func (u *Utility) Clear() error {
r := C.olm_clear_utility((*C.OlmUtility)(u.int))
if r == errorVal() {
return u.lastError()
}
return nil
}
// NewUtility creates a new utility.
func NewUtility() *Utility {
memory := make([]byte, utilitySize())
return &Utility{
int: C.olm_utility(unsafe.Pointer(&memory[0])),
mem: memory,
}
}
// 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)
}
output := make([]byte, u.sha256Len())
r := C.olm_sha256(
(*C.OlmUtility)(u.int),
unsafe.Pointer(&([]byte(input)[0])),
C.size_t(len(input)),
unsafe.Pointer(&(output[0])),
C.size_t(len(output)))
if r == errorVal() {
panic(u.lastError())
}
return string(output)
}
// 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
}
r := C.olm_ed25519_verify(
(*C.OlmUtility)(u.int),
unsafe.Pointer(&([]byte(key)[0])),
C.size_t(len(key)),
unsafe.Pointer(&([]byte(message)[0])),
C.size_t(len(message)),
unsafe.Pointer(&([]byte(signature)[0])),
C.size_t(len(signature)))
if r == errorVal() {
err = u.lastError()
if err == BadMessageMAC {
err = nil
}
} else {
ok = true
}
return ok, err
}
// 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) {
objJSON, err := json.Marshal(obj)
if err != nil {
return false, err
}
sig := gjson.GetBytes(objJSON, util.GJSONPath("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

@@ -0,0 +1,143 @@
//go:build !nosas
// +build !nosas
package olm
// #cgo LDFLAGS: -lolm -lstdc++
// #include <olm/olm.h>
// #include <olm/sas.h>
import "C"
import (
"crypto/rand"
"unsafe"
)
// SAS stores an Olm Short Authentication String (SAS) object.
type SAS struct {
int *C.OlmSAS
mem []byte
}
// NewBlankSAS initializes an empty SAS object.
func NewBlankSAS() *SAS {
memory := make([]byte, sasSize())
return &SAS{
int: C.olm_sas(unsafe.Pointer(&memory[0])),
mem: memory,
}
}
// sasSize is the size of a SAS object in bytes.
func sasSize() uint {
return uint(C.olm_sas_size())
}
// sasRandomLength is the number of random bytes needed to create an SAS object.
func (sas *SAS) sasRandomLength() uint {
return uint(C.olm_create_sas_random_length(sas.int))
}
// NewSAS creates a new SAS object.
func NewSAS() *SAS {
sas := NewBlankSAS()
random := make([]byte, sas.sasRandomLength()+1)
_, err := rand.Read(random)
if err != nil {
panic(NotEnoughGoRandom)
}
r := C.olm_create_sas(
(*C.OlmSAS)(sas.int),
unsafe.Pointer(&random[0]),
C.size_t(len(random)))
if r == errorVal() {
panic(sas.lastError())
} else {
return sas
}
}
// clear clears the memory used to back an SAS object.
func (sas *SAS) clear() uint {
return uint(C.olm_clear_sas(sas.int))
}
// lastError returns the most recent error to happen to an SAS object.
func (sas *SAS) lastError() error {
return convertError(C.GoString(C.olm_sas_last_error(sas.int)))
}
// pubkeyLength is the size of a public key in bytes.
func (sas *SAS) pubkeyLength() uint {
return uint(C.olm_sas_pubkey_length((*C.OlmSAS)(sas.int)))
}
// GetPubkey gets the public key for the SAS object.
func (sas *SAS) GetPubkey() []byte {
pubkey := make([]byte, sas.pubkeyLength())
r := C.olm_sas_get_pubkey(
(*C.OlmSAS)(sas.int),
unsafe.Pointer(&pubkey[0]),
C.size_t(len(pubkey)))
if r == errorVal() {
panic(sas.lastError())
}
return pubkey
}
// SetTheirKey sets the public key of the other user.
func (sas *SAS) SetTheirKey(theirKey []byte) error {
theirKeyCopy := make([]byte, len(theirKey))
copy(theirKeyCopy, theirKey)
r := C.olm_sas_set_their_key(
(*C.OlmSAS)(sas.int),
unsafe.Pointer(&theirKeyCopy[0]),
C.size_t(len(theirKeyCopy)))
if r == errorVal() {
return sas.lastError()
}
return nil
}
// GenerateBytes generates bytes to use for the short authentication string.
func (sas *SAS) GenerateBytes(info []byte, count uint) ([]byte, error) {
infoCopy := make([]byte, len(info))
copy(infoCopy, info)
output := make([]byte, count)
r := C.olm_sas_generate_bytes(
(*C.OlmSAS)(sas.int),
unsafe.Pointer(&infoCopy[0]),
C.size_t(len(infoCopy)),
unsafe.Pointer(&output[0]),
C.size_t(len(output)))
if r == errorVal() {
return nil, sas.lastError()
}
return output, nil
}
// macLength is the size of a message authentication code generated by olm_sas_calculate_mac.
func (sas *SAS) macLength() uint {
return uint(C.olm_sas_mac_length((*C.OlmSAS)(sas.int)))
}
// CalculateMAC generates a message authentication code (MAC) based on the shared secret.
func (sas *SAS) CalculateMAC(input []byte, info []byte) ([]byte, error) {
inputCopy := make([]byte, len(input))
copy(inputCopy, input)
infoCopy := make([]byte, len(info))
copy(infoCopy, info)
mac := make([]byte, sas.macLength())
r := C.olm_sas_calculate_mac(
(*C.OlmSAS)(sas.int),
unsafe.Pointer(&inputCopy[0]),
C.size_t(len(inputCopy)),
unsafe.Pointer(&infoCopy[0]),
C.size_t(len(infoCopy)),
unsafe.Pointer(&mac[0]),
C.size_t(len(mac)))
if r == errorVal() {
return nil, sas.lastError()
}
return mac, nil
}