Debian Codegraph @

crypto/olm/utility.go

raw
1 package olm
2
3 // #cgo LDFLAGS: -lolm -lstdc++
4 // #include <olm/olm.h>
5 import "C"
6
7 import (
8 "encoding/json"
9 "fmt"
10 "strings"
11 "unsafe"
12
13 "github.com/tidwall/gjson"
14 "github.com/tidwall/sjson"
15
16 "maunium.net/go/mautrix/crypto/canonicaljson"
17 "maunium.net/go/mautrix/id"
18 )
19
20 // Utility stores the necessary state to perform hash and signature
21 // verification operations.
22 type Utility struct {
23 int *C.OlmUtility
24 mem []byte
25 }
26
27 // utilitySize returns the size of a utility object in bytes.
28 func utilitySize() uint {
29 return uint(C.olm_utility_size())
30 }
31
32 // sha256Len returns the length of the buffer needed to hold the SHA-256 hash.
33 func (u *Utility) sha256Len() uint {
34 return uint(C.olm_sha256_length((*C.OlmUtility)(u.int)))
35 }
36
37 // lastError returns an error describing the most recent error to happen to a
38 // utility.
39 func (u *Utility) lastError() error {
40 return convertError(C.GoString(C.olm_utility_last_error((*C.OlmUtility)(u.int))))
41 }
42
43 // Clear clears the memory used to back this utility.
44 func (u *Utility) Clear() error {
45 r := C.olm_clear_utility((*C.OlmUtility)(u.int))
46 if r == errorVal() {
47 return u.lastError()
48 }
49 return nil
50 }
51
52 // NewUtility creates a new utility.
53 func NewUtility() *Utility {
54 memory := make([]byte, utilitySize())
55 return &Utility{
56 int: C.olm_utility(unsafe.Pointer(&memory[0])),
57 mem: memory,
58 }
59 }
60
61 // Sha256 calculates the SHA-256 hash of the input and encodes it as base64.
62 func (u *Utility) Sha256(input string) string {
63 if len(input) == 0 {
64 panic(EmptyInput)
65 }
66 output := make([]byte, u.sha256Len())
67 r := C.olm_sha256(
68 (*C.OlmUtility)(u.int),
69 unsafe.Pointer(&([]byte(input)[0])),
70 C.size_t(len(input)),
71 unsafe.Pointer(&(output[0])),
72 C.size_t(len(output)))
73 if r == errorVal() {
74 panic(u.lastError())
75 }
76 return string(output)
77 }
78
79 // VerifySignature verifies an ed25519 signature. Returns true if the verification
80 // suceeds or false otherwise. Returns error on failure. If the key was too
81 // small then the error will be "INVALID_BASE64".
82 func (u *Utility) VerifySignature(message string, key id.Ed25519, signature string) (ok bool, err error) {
83 if len(message) == 0 || len(key) == 0 || len(signature) == 0 {
84 return false, EmptyInput
85 }
86 r := C.olm_ed25519_verify(
87 (*C.OlmUtility)(u.int),
88 unsafe.Pointer(&([]byte(key)[0])),
89 C.size_t(len(key)),
90 unsafe.Pointer(&([]byte(message)[0])),
91 C.size_t(len(message)),
92 unsafe.Pointer(&([]byte(signature)[0])),
93 C.size_t(len(signature)))
94 if r == errorVal() {
95 err = u.lastError()
96 if err == BadMessageMAC {
97 err = nil
98 }
99 } else {
100 ok = true
101 }
102 return ok, err
103 }
104
105 var gjsonEscaper = strings.NewReplacer(
106 `\`, `\\`,
107 ".", `\.`,
108 "|", `\|`,
109 "#", `\#`,
110 "@", `\@`,
111 "*", `\*`,
112 "?", `\?`)
113
114 func gjsonPath(path ...string) string {
115 var result strings.Builder
116 for i, part := range path {
117 _, _ = gjsonEscaper.WriteString(&result, part)
118 if i < len(path)-1 {
119 result.WriteRune('.')
120 }
121 }
122 return result.String()
123 }
124
125 // VerifySignatureJSON verifies the signature in the JSON object _obj following
126 // the Matrix specification:
127 // https://matrix.org/speculator/spec/drafts%2Fe2e/appendices.html#signing-json
128 // If the _obj is a struct, the `json` tags will be honored.
129 func (u *Utility) VerifySignatureJSON(obj interface{}, userID id.UserID, keyName string, key id.Ed25519) (bool, error) {
130 objJSON, err := json.Marshal(obj)
131 if err != nil {
132 return false, err
133 }
134 sig := gjson.GetBytes(objJSON, gjsonPath("signatures", string(userID), fmt.Sprintf("ed25519:%s", keyName)))
135 if !sig.Exists() || sig.Type != gjson.String {
136 return false, SignatureNotFound
137 }
138 objJSON, err = sjson.DeleteBytes(objJSON, "unsigned")
139 if err != nil {
140 return false, err
141 }
142 objJSON, err = sjson.DeleteBytes(objJSON, "signatures")
143 if err != nil {
144 return false, err
145 }
146 objJSONString := string(canonicaljson.CanonicalJSONAssumeValid(objJSON))
147 return u.VerifySignature(objJSONString, key, sig.Str)
148 }
149
150 // VerifySignatureJSON verifies the signature in the JSON object _obj following
151 // the Matrix specification:
152 // https://matrix.org/speculator/spec/drafts%2Fe2e/appendices.html#signing-json
153 // This function is a wrapper over Utility.VerifySignatureJSON that creates and
154 // destroys the Utility object transparently.
155 // If the _obj is a struct, the `json` tags will be honored.
156 func VerifySignatureJSON(obj interface{}, userID id.UserID, keyName string, key id.Ed25519) (bool, error) {
157 u := NewUtility()
158 defer u.Clear()
159 return u.VerifySignatureJSON(obj, userID, keyName, key)
160 }