package migrate import ( "bytes" "crypto/hmac" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "io" "math" "regexp" "sort" "strconv" "strings" "unicode/utf8" ) // MarkerKey is where a moved event's content says what it was moved from. It travels inside the // ciphertext: only the app, after decrypting, reads it. const MarkerKey = "com.xessenger.migrated" // MarkerVersion is the version of the markers a move writes. const MarkerVersion = 2 // DigestKeySize is the size of a room's digest key, which every marker of the room carries. const DigestKeySize = 32 // Marker is the content under MarkerKey. Seq counts a room's moved events from 1, in the order of // their original timestamps. Key is the room's digest key (DigestKeySize random bytes, unpadded // standard base64), the same in every marker of the room: the digest is keyed with it, so the digest // the API and the bridge database keep gives away nothing of a short message. Sender is set on an // event the bridge's bot wrote for someone who can no longer write in the room (who left it): the // original sender, with Name, their display name in the old room then, when it was known. The app // takes Sender and Name only from an event the bot wrote (docs/e2ee/work-plan.md 4.2 ⑦). // // Readers (MarkerOf here, markerOf in apps/api/src/e2ee/migration/digest.ts, which the app uses) take // a key only as 43 characters of [A-Za-z0-9+/] that decode to DigestKeySize bytes, and compare keys // as strings. They keep Sender only when it has the shape of a user ID and Name only when it is more // than white space; a marker with another sender or name is still read, without them. type Marker struct { V int `json:"v"` From string `json:"from"` Seq int `json:"seq"` Key string `json:"key"` Sender string `json:"sender,omitempty"` Name string `json:"name,omitempty"` } // MarkerOf reads the marker of a moved event's (decrypted) content. func MarkerOf(content json.RawMessage) (Marker, bool) { var holder map[string]json.RawMessage if json.Unmarshal(content, &holder) != nil { return Marker{}, false } var raw struct { V int `json:"v"` From string `json:"from"` Seq int `json:"seq"` Key string `json:"key"` Sender any `json:"sender"` Name any `json:"name"` } if json.Unmarshal(holder[MarkerKey], &raw) != nil || raw.V != MarkerVersion || raw.Seq < 1 || raw.From == "" { return Marker{}, false } // The decoder skips line breaks, which the app's reader does not take: the length rules them out. if len(raw.Key) != base64.RawStdEncoding.EncodedLen(DigestKeySize) { return Marker{}, false } if key, err := base64.RawStdEncoding.DecodeString(raw.Key); err != nil || len(key) != DigestKeySize { return Marker{}, false } marker := Marker{V: raw.V, From: raw.From, Seq: raw.Seq, Key: raw.Key} if sender, _ := raw.Sender.(string); len(sender) <= maxUserID && userID.MatchString(sender) { marker.Sender = sender } if name, _ := raw.Name.(string); strings.TrimFunc(name, jsSpace) != "" { marker.Name = name } return marker, true } // userID is the shape a marker's sender must have, the same as the app's reader takes: '@', a // localpart of printable ASCII without ':', ':' and a server name of printable ASCII. maxUserID is // Matrix's limit on a user ID's length. var userID = regexp.MustCompile(`^@[!-9;-~]+:[!-~]+$`) const maxUserID = 255 // jsSpace is white space as JavaScript's String.prototype.trim sees it, so that a name the app reads // as blank is blank here too. func jsSpace(r rune) bool { switch r { case '\t', '\n', '\v', '\f', '\r', ' ', 0xa0, 0x1680, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000, 0xfeff: return true } return r >= 0x2000 && r <= 0x200a } // EncodeDigestKey writes a room's digest key as its markers carry it. func EncodeDigestKey(key []byte) string { return base64.RawStdEncoding.EncodeToString(key) } // Moved is one moved event: its marker's seq and from, and its whole content as encrypted. type Moved struct { Seq int `json:"seq"` From string `json:"from"` Content json.RawMessage `json:"content"` } var ( ErrNotInteger = errors.New("canonical JSON takes integers only") ErrDuplicateSeq = errors.New("two moved events share a seq") // ErrDigestKey is a room whose moved events do not all carry one digest key in a marker: the // bridge writes one key into every marker of a room, so the app has an event it did not write. ErrDigestKey = errors.New("the moved events do not carry one digest key") ) // maxSafe is the largest integer JavaScript (the app) reads exactly. const maxSafe = 1<<53 - 1 // Digest summarises a room's moved events: the lowercase hex HMAC-SHA256, keyed with the room's // digest key (the markers' Key), of one line per event, in seq order, "\t\t\n". // A room with no moved events has no key, and its digest is the SHA-256 of nothing. The bridge // computes it from what it encrypts and the app from what it decrypts; they agree only if the app // decrypted every moved event intact. Events whose markers do not all carry one key are refused // (ErrDigestKey). func Digest(moved []Moved) (string, error) { entries := make([]digestEntry, len(moved)) var key string for i, event := range moved { marker, ok := MarkerOf(event.Content) if !ok || (i > 0 && marker.Key != key) { return "", fmt.Errorf("seq %d: %w", event.Seq, ErrDigestKey) } key = marker.Key hash, err := ContentHash(event.Content) if err != nil { return "", fmt.Errorf("seq %d: %w", event.Seq, err) } entries[i] = digestEntry{Seq: event.Seq, From: event.From, Hash: hash} } raw, err := base64.RawStdEncoding.DecodeString(key) if err != nil { return "", ErrDigestKey } return digestOf(raw, entries) } // digestEntry is one moved event of a digest, with its content already hashed (the bridge keeps the // hashes, not the content). type digestEntry struct { Seq int From string Hash string } // digestOf is Digest over hashed entries, keyed with the room's digest key. func digestOf(key []byte, entries []digestEntry) (string, error) { if len(entries) == 0 { empty := sha256.Sum256(nil) return hex.EncodeToString(empty[:]), nil } if len(key) != DigestKeySize { return "", ErrDigestKey } sorted := append([]digestEntry(nil), entries...) sort.SliceStable(sorted, func(i, j int) bool { return sorted[i].Seq < sorted[j].Seq }) sum := hmac.New(sha256.New, key) for i, entry := range sorted { if i > 0 && sorted[i-1].Seq == entry.Seq { return "", ErrDuplicateSeq } fmt.Fprintf(sum, "%d\t%s\t%s\n", entry.Seq, entry.From, entry.Hash) } return hex.EncodeToString(sum.Sum(nil)), nil } // ContentHash is the lowercase hex SHA-256 of an event content's canonical form. func ContentHash(content json.RawMessage) (string, error) { canonical, err := Canonical(content) if err != nil { return "", err } sum := sha256.Sum256(canonical) return hex.EncodeToString(sum[:]), nil } // Canonical encodes JSON in the one form both the bridge and the app produce: object keys sorted // by their UTF-8 bytes (that is, by code point), no whitespace, strings escaped as // gomatrixserverlib's CompactJSON escapes them (only the quote, the backslash and control // characters: \b \t \n \f \r short, the others as \u00XX in upper-case hex; everything else, U+2028 // and <>& included, as raw UTF-8), and numbers as integers (1.0 is 1; 1.5, or an integer JavaScript // cannot hold exactly, is refused). It is Matrix's canonical JSON, written out here so that it does // not change with the mautrix version a bridge happens to build with. func Canonical(raw json.RawMessage) ([]byte, error) { decoder := json.NewDecoder(bytes.NewReader(raw)) decoder.UseNumber() var value any if err := decoder.Decode(&value); err != nil { return nil, err } if _, err := decoder.Token(); err != io.EOF { return nil, errors.New("trailing data after JSON value") } var out bytes.Buffer if err := writeCanonical(&out, value); err != nil { return nil, err } return out.Bytes(), nil } func writeCanonical(out *bytes.Buffer, value any) error { switch v := value.(type) { case nil: out.WriteString("null") case bool: out.WriteString(strconv.FormatBool(v)) case json.Number: number, err := strconv.ParseFloat(string(v), 64) if err != nil || number != math.Trunc(number) || math.Abs(number) > maxSafe { return ErrNotInteger } out.WriteString(strconv.FormatInt(int64(number), 10)) case string: writeString(out, v) case []any: out.WriteByte('[') for i, item := range v { if i > 0 { out.WriteByte(',') } if err := writeCanonical(out, item); err != nil { return err } } out.WriteByte(']') case map[string]any: keys := make([]string, 0, len(v)) for key := range v { keys = append(keys, key) } sort.Strings(keys) out.WriteByte('{') for i, key := range keys { if i > 0 { out.WriteByte(',') } writeString(out, key) out.WriteByte(':') if err := writeCanonical(out, v[key]); err != nil { return err } } out.WriteByte('}') default: return fmt.Errorf("unexpected JSON value %T", value) } return nil } func writeString(out *bytes.Buffer, value string) { out.WriteByte('"') for _, r := range value { switch r { case '"': out.WriteString(`\"`) case '\\': out.WriteString(`\\`) case '\b': out.WriteString(`\b`) case '\f': out.WriteString(`\f`) case '\n': out.WriteString(`\n`) case '\r': out.WriteString(`\r`) case '\t': out.WriteString(`\t`) default: if r < 0x20 { fmt.Fprintf(out, `\u%04X`, r) } else { var buf [utf8.UTFMax]byte out.Write(buf[:utf8.EncodeRune(buf[:], r)]) } } } out.WriteByte('"') } // EncryptedFileURLs are the URLs of the encrypted files a decrypted content carries, wherever they // sit in it (the file, its thumbnail, a link preview's picture): every object shaped like Matrix's // EncryptedFile (an mxc:// url, an "oct" key, an iv, a SHA-256 hash and v2), each URL once, sorted. // The bridge and the app count a room's moved files this way. func EncryptedFileURLs(content json.RawMessage) []string { var value any if json.Unmarshal(content, &value) != nil { return nil } found := map[string]bool{} collectEncryptedFiles(value, found) urls := make([]string, 0, len(found)) for url := range found { urls = append(urls, url) } sort.Strings(urls) return urls } func collectEncryptedFiles(value any, found map[string]bool) { switch v := value.(type) { case map[string]any: if url, ok := encryptedFileURL(v); ok { found[url] = true return } for _, item := range v { collectEncryptedFiles(item, found) } case []any: for _, item := range v { collectEncryptedFiles(item, found) } } } func encryptedFileURL(v map[string]any) (string, bool) { url, _ := v["url"].(string) key, _ := v["key"].(map[string]any) hashes, _ := v["hashes"].(map[string]any) _, iv := v["iv"].(string) _, sha := hashes["sha256"].(string) if !strings.HasPrefix(url, "mxc://") || key == nil || key["kty"] != "oct" || !iv || !sha || v["v"] != "v2" { return "", false } return url, true }