Debian Codegraph @

crypto/olm/account.go

raw
1 package olm
2
3 // #cgo LDFLAGS: -lolm -lstdc++
4 // #include <olm/olm.h>
5 import "C"
6
7 import (
8 "crypto/rand"
9 "encoding/json"
10 "unsafe"
11
12 "github.com/tidwall/gjson"
13 "github.com/tidwall/sjson"
14
15 "maunium.net/go/mautrix/crypto/canonicaljson"
16 "maunium.net/go/mautrix/id"
17 )
18
19 // Account stores a device account for end to end encrypted messaging.
20 type Account struct {
21 int *C.OlmAccount
22 mem []byte
23 }
24
25 // AccountFromPickled loads an Account from a pickled base64 string. Decrypts
26 // the Account using the supplied key. Returns error on failure. If the key
27 // doesn't match the one used to encrypt the Account then the error will be
28 // "BAD_ACCOUNT_KEY". If the base64 couldn't be decoded then the error will be
29 // "INVALID_BASE64".
30 func AccountFromPickled(pickled, key []byte) (*Account, error) {
31 if len(pickled) == 0 {
32 return nil, EmptyInput
33 }
34 a := NewBlankAccount()
35 return a, a.Unpickle(pickled, key)
36 }
37
38 func NewBlankAccount() *Account {
39 memory := make([]byte, accountSize())
40 return &Account{
41 int: C.olm_account(unsafe.Pointer(&memory[0])),
42 mem: memory,
43 }
44 }
45
46 // NewAccount creates a new Account.
47 func NewAccount() *Account {
48 a := NewBlankAccount()
49 random := make([]byte, a.createRandomLen()+1)
50 _, err := rand.Read(random)
51 if err != nil {
52 panic(NotEnoughGoRandom)
53 }
54 r := C.olm_create_account(
55 (*C.OlmAccount)(a.int),
56 unsafe.Pointer(&random[0]),
57 C.size_t(len(random)))
58 if r == errorVal() {
59 panic(a.lastError())
60 } else {
61 return a
62 }
63 }
64
65 // accountSize returns the size of an account object in bytes.
66 func accountSize() uint {
67 return uint(C.olm_account_size())
68 }
69
70 // lastError returns an error describing the most recent error to happen to an
71 // account.
72 func (a *Account) lastError() error {
73 return convertError(C.GoString(C.olm_account_last_error((*C.OlmAccount)(a.int))))
74 }
75
76 // Clear clears the memory used to back this Account.
77 func (a *Account) Clear() error {
78 r := C.olm_clear_account((*C.OlmAccount)(a.int))
79 if r == errorVal() {
80 return a.lastError()
81 } else {
82 return nil
83 }
84 }
85
86 // pickleLen returns the number of bytes needed to store an Account.
87 func (a *Account) pickleLen() uint {
88 return uint(C.olm_pickle_account_length((*C.OlmAccount)(a.int)))
89 }
90
91 // createRandomLen returns the number of random bytes needed to create an
92 // Account.
93 func (a *Account) createRandomLen() uint {
94 return uint(C.olm_create_account_random_length((*C.OlmAccount)(a.int)))
95 }
96
97 // identityKeysLen returns the size of the output buffer needed to hold the
98 // identity keys.
99 func (a *Account) identityKeysLen() uint {
100 return uint(C.olm_account_identity_keys_length((*C.OlmAccount)(a.int)))
101 }
102
103 // signatureLen returns the length of an ed25519 signature encoded as base64.
104 func (a *Account) signatureLen() uint {
105 return uint(C.olm_account_signature_length((*C.OlmAccount)(a.int)))
106 }
107
108 // oneTimeKeysLen returns the size of the output buffer needed to hold the one
109 // time keys.
110 func (a *Account) oneTimeKeysLen() uint {
111 return uint(C.olm_account_one_time_keys_length((*C.OlmAccount)(a.int)))
112 }
113
114 // genOneTimeKeysRandomLen returns the number of random bytes needed to
115 // generate a given number of new one time keys.
116 func (a *Account) genOneTimeKeysRandomLen(num uint) uint {
117 return uint(C.olm_account_generate_one_time_keys_random_length(
118 (*C.OlmAccount)(a.int),
119 C.size_t(num)))
120 }
121
122 // Pickle returns an Account as a base64 string. Encrypts the Account using the
123 // supplied key.
124 func (a *Account) Pickle(key []byte) []byte {
125 if len(key) == 0 {
126 panic(NoKeyProvided)
127 }
128 pickled := make([]byte, a.pickleLen())
129 r := C.olm_pickle_account(
130 (*C.OlmAccount)(a.int),
131 unsafe.Pointer(&key[0]),
132 C.size_t(len(key)),
133 unsafe.Pointer(&pickled[0]),
134 C.size_t(len(pickled)))
135 if r == errorVal() {
136 panic(a.lastError())
137 }
138 return pickled[:r]
139 }
140
141 func (a *Account) Unpickle(pickled, key []byte) error {
142 if len(key) == 0 {
143 return NoKeyProvided
144 }
145 r := C.olm_unpickle_account(
146 (*C.OlmAccount)(a.int),
147 unsafe.Pointer(&key[0]),
148 C.size_t(len(key)),
149 unsafe.Pointer(&pickled[0]),
150 C.size_t(len(pickled)))
151 if r == errorVal() {
152 return a.lastError()
153 }
154 return nil
155 }
156
157 func (a *Account) GobEncode() ([]byte, error) {
158 pickled := a.Pickle(pickleKey)
159 length := unpaddedBase64.DecodedLen(len(pickled))
160 rawPickled := make([]byte, length)
161 _, err := unpaddedBase64.Decode(rawPickled, pickled)
162 return rawPickled, err
163 }
164
165 func (a *Account) GobDecode(rawPickled []byte) error {
166 if a.int == nil {
167 *a = *NewBlankAccount()
168 }
169 length := unpaddedBase64.EncodedLen(len(rawPickled))
170 pickled := make([]byte, length)
171 unpaddedBase64.Encode(pickled, rawPickled)
172 return a.Unpickle(pickled, pickleKey)
173 }
174
175 func (a *Account) MarshalJSON() ([]byte, error) {
176 pickled := a.Pickle(pickleKey)
177 quotes := make([]byte, len(pickled)+2)
178 quotes[0] = '"'
179 quotes[len(quotes)-1] = '"'
180 copy(quotes[1:len(quotes)-1], pickled)
181 return quotes, nil
182 }
183
184 func (a *Account) UnmarshalJSON(data []byte) error {
185 if len(data) == 0 || data[0] != '"' || data[len(data)-1] != '"' {
186 return InputNotJSONString
187 }
188 if a.int == nil {
189 *a = *NewBlankAccount()
190 }
191 return a.Unpickle(data[1:len(data)-1], pickleKey)
192 }
193
194 // IdentityKeysJSON returns the public parts of the identity keys for the Account.
195 func (a *Account) IdentityKeysJSON() []byte {
196 identityKeys := make([]byte, a.identityKeysLen())
197 r := C.olm_account_identity_keys(
198 (*C.OlmAccount)(a.int),
199 unsafe.Pointer(&identityKeys[0]),
200 C.size_t(len(identityKeys)))
201 if r == errorVal() {
202 panic(a.lastError())
203 } else {
204 return identityKeys
205 }
206 }
207
208 // IdentityKeys returns the public parts of the Ed25519 and Curve25519 identity
209 // keys for the Account.
210 func (a *Account) IdentityKeys() (id.Ed25519, id.Curve25519) {
211 identityKeysJSON := a.IdentityKeysJSON()
212 results := gjson.GetManyBytes(identityKeysJSON, "ed25519", "curve25519")
213 return id.Ed25519(results[0].Str), id.Curve25519(results[1].Str)
214 }
215
216 // Sign returns the signature of a message using the ed25519 key for this
217 // Account.
218 func (a *Account) Sign(message []byte) []byte {
219 if len(message) == 0 {
220 panic(EmptyInput)
221 }
222 signature := make([]byte, a.signatureLen())
223 r := C.olm_account_sign(
224 (*C.OlmAccount)(a.int),
225 unsafe.Pointer(&message[0]),
226 C.size_t(len(message)),
227 unsafe.Pointer(&signature[0]),
228 C.size_t(len(signature)))
229 if r == errorVal() {
230 panic(a.lastError())
231 }
232 return signature
233 }
234
235 // SignJSON signs the given JSON object following the Matrix specification:
236 // https://matrix.org/docs/spec/appendices#signing-json
237 func (a *Account) SignJSON(obj interface{}) (string, error) {
238 objJSON, err := json.Marshal(obj)
239 if err != nil {
240 return "", err
241 }
242 objJSON, _ = sjson.DeleteBytes(objJSON, "unsigned")
243 objJSON, _ = sjson.DeleteBytes(objJSON, "signatures")
244 return string(a.Sign(canonicaljson.CanonicalJSONAssumeValid(objJSON))), nil
245 }
246
247 // OneTimeKeys returns the public parts of the unpublished one time keys for
248 // the Account.
249 //
250 // The returned data is a struct with the single value "Curve25519", which is
251 // itself an object mapping key id to base64-encoded Curve25519 key. For
252 // example:
253 // {
254 // Curve25519: {
255 // "AAAAAA": "wo76WcYtb0Vk/pBOdmduiGJ0wIEjW4IBMbbQn7aSnTo",
256 // "AAAAAB": "LRvjo46L1X2vx69sS9QNFD29HWulxrmW11Up5AfAjgU"
257 // }
258 // }
259 func (a *Account) OneTimeKeys() map[string]id.Curve25519 {
260 oneTimeKeysJSON := make([]byte, a.oneTimeKeysLen())
261 r := C.olm_account_one_time_keys(
262 (*C.OlmAccount)(a.int),
263 unsafe.Pointer(&oneTimeKeysJSON[0]),
264 C.size_t(len(oneTimeKeysJSON)))
265 if r == errorVal() {
266 panic(a.lastError())
267 }
268 var oneTimeKeys struct {
269 Curve25519 map[string]id.Curve25519 `json:"curve25519"`
270 }
271 err := json.Unmarshal(oneTimeKeysJSON, &oneTimeKeys)
272 if err != nil {
273 panic(err)
274 }
275 return oneTimeKeys.Curve25519
276 }
277
278 // MarkKeysAsPublished marks the current set of one time keys as being
279 // published.
280 func (a *Account) MarkKeysAsPublished() {
281 C.olm_account_mark_keys_as_published((*C.OlmAccount)(a.int))
282 }
283
284 // MaxNumberOfOneTimeKeys returns the largest number of one time keys this
285 // Account can store.
286 func (a *Account) MaxNumberOfOneTimeKeys() uint {
287 return uint(C.olm_account_max_number_of_one_time_keys((*C.OlmAccount)(a.int)))
288 }
289
290 // GenOneTimeKeys generates a number of new one time keys. If the total number
291 // of keys stored by this Account exceeds MaxNumberOfOneTimeKeys then the old
292 // keys are discarded.
293 func (a *Account) GenOneTimeKeys(num uint) {
294 random := make([]byte, a.genOneTimeKeysRandomLen(num)+1)
295 _, err := rand.Read(random)
296 if err != nil {
297 panic(NotEnoughGoRandom)
298 }
299 r := C.olm_account_generate_one_time_keys(
300 (*C.OlmAccount)(a.int),
301 C.size_t(num),
302 unsafe.Pointer(&random[0]),
303 C.size_t(len(random)))
304 if r == errorVal() {
305 panic(a.lastError())
306 }
307 }
308
309 // NewOutboundSession creates a new out-bound session for sending messages to a
310 // given curve25519 identityKey and oneTimeKey. Returns error on failure. If the
311 // keys couldn't be decoded as base64 then the error will be "INVALID_BASE64"
312 func (a *Account) NewOutboundSession(theirIdentityKey, theirOneTimeKey id.Curve25519) (*Session, error) {
313 if len(theirIdentityKey) == 0 || len(theirOneTimeKey) == 0 {
314 return nil, EmptyInput
315 }
316 s := NewBlankSession()
317 random := make([]byte, s.createOutboundRandomLen()+1)
318 _, err := rand.Read(random)
319 if err != nil {
320 panic(NotEnoughGoRandom)
321 }
322 r := C.olm_create_outbound_session(
323 (*C.OlmSession)(s.int),
324 (*C.OlmAccount)(a.int),
325 unsafe.Pointer(&([]byte(theirIdentityKey)[0])),
326 C.size_t(len(theirIdentityKey)),
327 unsafe.Pointer(&([]byte(theirOneTimeKey)[0])),
328 C.size_t(len(theirOneTimeKey)),
329 unsafe.Pointer(&random[0]),
330 C.size_t(len(random)))
331 if r == errorVal() {
332 return nil, s.lastError()
333 }
334 return s, nil
335 }
336
337 // NewInboundSession creates a new in-bound session for sending/receiving
338 // messages from an incoming PRE_KEY message. Returns error on failure. If
339 // the base64 couldn't be decoded then the error will be "INVALID_BASE64". If
340 // the message was for an unsupported protocol version then the error will be
341 // "BAD_MESSAGE_VERSION". If the message couldn't be decoded then then the
342 // error will be "BAD_MESSAGE_FORMAT". If the message refers to an unknown one
343 // time key then the error will be "BAD_MESSAGE_KEY_ID".
344 func (a *Account) NewInboundSession(oneTimeKeyMsg string) (*Session, error) {
345 if len(oneTimeKeyMsg) == 0 {
346 return nil, EmptyInput
347 }
348 s := NewBlankSession()
349 r := C.olm_create_inbound_session(
350 (*C.OlmSession)(s.int),
351 (*C.OlmAccount)(a.int),
352 unsafe.Pointer(&([]byte(oneTimeKeyMsg)[0])),
353 C.size_t(len(oneTimeKeyMsg)))
354 if r == errorVal() {
355 return nil, s.lastError()
356 }
357 return s, nil
358 }
359
360 // NewInboundSessionFrom creates a new in-bound session for sending/receiving
361 // messages from an incoming PRE_KEY message. Returns error on failure. If
362 // the base64 couldn't be decoded then the error will be "INVALID_BASE64". If
363 // the message was for an unsupported protocol version then the error will be
364 // "BAD_MESSAGE_VERSION". If the message couldn't be decoded then then the
365 // error will be "BAD_MESSAGE_FORMAT". If the message refers to an unknown one
366 // time key then the error will be "BAD_MESSAGE_KEY_ID".
367 func (a *Account) NewInboundSessionFrom(theirIdentityKey id.Curve25519, oneTimeKeyMsg string) (*Session, error) {
368 if len(theirIdentityKey) == 0 || len(oneTimeKeyMsg) == 0 {
369 return nil, EmptyInput
370 }
371 s := NewBlankSession()
372 r := C.olm_create_inbound_session_from(
373 (*C.OlmSession)(s.int),
374 (*C.OlmAccount)(a.int),
375 unsafe.Pointer(&([]byte(theirIdentityKey)[0])),
376 C.size_t(len(theirIdentityKey)),
377 unsafe.Pointer(&([]byte(oneTimeKeyMsg)[0])),
378 C.size_t(len(oneTimeKeyMsg)))
379 if r == errorVal() {
380 return nil, s.lastError()
381 }
382 return s, nil
383 }
384
385 // RemoveOneTimeKeys removes the one time keys that the session used from the
386 // Account. Returns error on failure. If the Account doesn't have any
387 // matching one time keys then the error will be "BAD_MESSAGE_KEY_ID".
388 func (a *Account) RemoveOneTimeKeys(s *Session) error {
389 r := C.olm_remove_one_time_keys(
390 (*C.OlmAccount)(a.int),
391 (*C.OlmSession)(s.int))
392 if r == errorVal() {
393 return a.lastError()
394 }
395 return nil
396 }