Compare commits

..

11 commits

View file

@ -15,7 +15,7 @@ description: 'Secure and private messaging with XMPP and OMEMO encryption.'
I find it funny that twenty years ago I was already trying I find it funny that twenty years ago I was already trying
to promote XMPP over ICQ to my classmates. to promote XMPP over ICQ to my classmates.
At that time, the proprietary messenger once again made life harder At the time, the proprietary messenger kept making life harder
for users of alternative clients. for users of alternative clients.
Thats when I realized that I prefer protocols over services. Thats when I realized that I prefer protocols over services.
@ -50,21 +50,21 @@ it on a&nbsp;<a
href='https://contrapunctus.codeberg.page/the-quick-and-easy-guide-to-xmpp.html' href='https://contrapunctus.codeberg.page/the-quick-and-easy-guide-to-xmpp.html'
target='_blank'>dedicated page by Daniel Gultsch</a>. target='_blank'>dedicated page by Daniel Gultsch</a>.
Хочу также отметить, **Client**, in this post,
что я буду использовать слово Client для обозначения конкретных инстансов means a specific instance of an XMPP application on a user device.
приложений на пользовательских устройствах. В документации, связанной с OMEMO <br>OMEMO-related documentation uses the term Device,
для этого использвется термин Device, но мне он кажется запутывающим: but I find it potentially confusing:
в реальности на одном устройстве может быть несколько независимых клиентов. in practice, a single physical device can run multiple independent clients.
## Basic Concepts ## Basic Concepts
Here I'm going to explain some basic ideas behind e2e. This section introduces some basic ideas behind end-to-end encryption.
Если основные концепции и терминология вам знакомы, If you're already familiar with the concepts and terminology,
то можете смело пропустить этот раздел you can skip ahead to&nbsp;<a
и перейти к особенностям их практического применения касательно XMPP. href='#'>how end-to-end encryption affects the XMPP user experience</a>
or jump straight to the <a
Или даже сразу перейти к описанию workflow, которого я придерживаюсь сам. href='#'>step-by-step workflow</a>&nbsp;I personally use.
### Trade-offs Between Safety and Convenience ### Trade-offs Between Safety and Convenience
@ -108,247 +108,240 @@ is actually based on XMPP, but incompatibly altered and defederated.
### Keys, Fingerprints and Trust ### Keys, Fingerprints and Trust
OMEMO построен вокруг Double Ratchet Algorithm. OMEMO is based on the Double Ratchet Algorithm.
Там внутри всё очень интересно, While the internal details are quite interesting,
но нам для практического применения важно только то, for practical purposes it's enough to know that
что каждый клиент пользователя хранит в себе какие-то там ключи, each client stores some cryptographic keys
и умеет получать из них какой-то там хэш, and can derive a hash from them, commonly called a fingerprint.
который принято называть fingerprint.
Ключи обычно как-то автоматически управляются XMPP клиентом Keys are usually managed automatically by the XMPP client,
и в норме вам никогда не стоит трогать их руками. and in normal use you should never need to handle them manually.
Возможно, вам лучше даже и не знать, как они выглядят. In fact, you probably dont even need to know what they look like.
Единственное, что с ними нужно делать --
держать в секрете и бэкапить при необходимости.
Фингерпринт позволяет отличать конкретный A fingerprint lets you identify a specific client of your contact
клиент собеседника и быть уверенным, что его не подмененили. and verify that it hasnt been spoofed.
Список фингерпринтов для конкретного аккаунта Fingerprints for an account are not secret:
не является чем-то секретным: clients publish their own fingerprints to the XMPP server
клиентские приложения сами анонсируют свои фингерпнинты на сервере and automatically receive the fingerprints of others.
и автоматически пополняют список чужих. Only fingerprints you explicitly mark as trusted are relevant.
Значение имеют только те,
которые вы пометили как фингерпринты довереных клиентов.
В идеале, человек должен лично при встрече In an ideal scenario, the contact should confirm in person
или по уже довереному и безопасному каналу связи or through an already trusted and secure communication channel
сказать вам "Да, фингерпринт XXX принадлежит моему устройству" that the fingerprint belongs to their device,
и только после этого вы помечаете XXX доверенным. and only then you mark it as trusted.
Обычно в интерфейсе это просто проставление чекбокса или сканирование QR-кода. In most XMPP clients this is simply done by ticking a checkbox
or by scanning a QR code.
Некоторые клиенты для удобства пользователя The list of trusted fingerprints is used at the moment a message is sent.
довериют любым новым фингерпринтам контактов по-умолчанию, Behind the scenes, OMEMO performs a certain amount of key management,
но я не стал бы рекомендовать использовать такую политику, and only the clients that are present in the trusted list
это легкомысленно и небезопасно. at the time of encryption will be able to decrypt the message later.
Политики доверия или недоверия
можно посмотреть или поменять в настройках вашего клиента.
Список доверенных фингерпринтов используется в момент отправки сообщения: It's important to understand that trust cannot be applied retroactively:
OMEMO творит какую-то магию с жонглированием ключами и it's not possible to "extend" trust to new clients
ни один клиент, кроме перечисленных в списке на момент зашифровки, after a message has already been encrypted and sent.
не сможет его впоследствии расшифровать.
Передать как-то доверие в прошлое, увы, невозможно.
## Реалии OMEMO и XMPP ## Practical Aspects of OMEMO and XMPP
## Особенности OMEMO и XMPP
### Chat History ### Chat History
Вообще, XMPP поддерживает хранение истории переписок на сервере. In theory, XMPP supports server-side message history storage via
За это отвечает **XEP-0313: Message Archive Management**. **XEP-0313: Message Archive Management**.
В реальности поддержка этого XEP, In practice, support for this XEP,
политика хранения истории и особенно сроки хранения сообщений as well as retention policies and message lifetime,
зависят от конкретного сервера. depends on the specific server.
Рассчитывать по-умолчанию на бессрочное хранение всех переписок не стоит. You should never assume that all conversations are stored
indefinitely by default.
From a practical standpoint,
the server-side MAM archive is better considered a cache:
it can help you handle recent messages after a short period offline
or synchronize conversations across multiple devices.
В конечном счёте, At the end of the day, keeping your chat history is your responsibility,
ответственность за хранение переписок лежит исключительно на вас and this is a good place to apply a local-first approach.
и это разумное место для применения local-first подхода.
С практической точки зрения
проще всего рассматривать серверный архив сообщений
как некоторый кэш, который выручит вас по возвращении
из непродолжительного офлайна
или поможет с синхронизацей текущей переписки между разными устройствами.
### Synchronisation ### Synchronisation
За бесшовное переключение между клиентами отвечает Seamless switching between clients is handled by
**XEP-0280: Message Carbons**. **XEP-0280: Message Carbons**.
До его внедрения можно было переключиться с телефона на лэптоп Before its introduction, only incoming messages were synced between devices,
и пялиться в загруженную историю переписки, while your own outgoing messages were not.
состоящей только из входящих сообщений от собеседника. Protocol-level mirroring of your own messages
Отправка своих же сообщений ещё и самому себе is a rather non-obvious feature :D
на уровне протокола -- это довольно неочевидная фича.
Тут важно упомянуть, что при использовании e2e шифрования, It's important to note that with end-to-end encryption,
упомянутая выше концепция доверенных отпечатков пальцев the concept of trusted fingerprints also applies to your own clients.
распространяется и на свои клиенты тоже. For seamless synchronisation of outgoing messages,
all your clients must trust each other's fingerprints.
A new client,
or an old one that was not trusted at the time messages were sent,
will receive the full history from MAM but will not be able to decrypt it.
<br>Yes, even your own messages.
Для бесшовной синхронизации исходящих сообщений In theory, re-encrypting messages on already trusted clients
все ваши клиенты должны считать фингерпринты друг друга доверенными, could solve this issue, but no XMPP client implements it yet.
иначе можно столкнуться с ситуацией, So in practice you may need to manually resend
когда не получается прочитать своё же сообщение. some data to a new device.
Логичное, но неприятное следствие:
Новый клиент или старый,
который не был в списке доверенных на момент отправки сообщений,
получит историю из MAM, но не сможет её расшифровать.
Да, даже ваши сообщения.
Теоретически, перепаковка сообщений
на старых доверенных клиентах вроде как возможна,
но на практике, никто такое пока не имплементировал
и важные вещи придётся пересылать вручную.
### Message Correction ### Message Correction
Тут же стоит отметить, что такие простые и понятные на первый взгляд фичи Its worth keeping in mind that
как редактирование и удаление сообщений вообще-то полагаются на features that seem simple and straightforward at first glance,
клиентский код и могут не сработать у вашего собеседника так, such as message editing and deletion,
как вы этого ожидаете. actually rely on client-side implementation
Ими можно пользоваться, and may not behave for your recipient the way you expect.
это удобно и некоторые клиенты их отлично поддерживают,
но полагаться на них для сокрытия чего-либо не стоит. Theyre fine to use and are well supported in some clients,
but you shouldnt rely on them to hide anything.
### Maintenance ### Maintenance
OMEMO был задуман как решение, которое после настройки не требует какого-то OMEMO was designed as a set-it-and-forget-it solution,
дополнительного вмешательства. and it mostly succeeds in that goal.
Можно считать, что этой заявленной цели удалось достичь If you have a basic understanding of how the protocol works
и при наличии базового понимания работы протокола и регулярном онлайне and check in online from time to time,
никаких сюрпризов быть не должно. there shouldnt be any surprises.
Всё обслуживание заключается в регулярных бэкапах и All maintenance comes down to making regular backups
уведомлении своих контактов о фингерпринтах, and notifying your contacts
которые стоит добавить в список доверенных или убрать из него. when fingerprints are added or no longer valid
В нашем локальном хакспейсе мы даже проводим для этого регулярные события =) so they can keep their trust list up to date.
## Step-by-step guide ## Step-by-step Guide
Представим, что у меня есть аккаунт jid@some.server и несколько устройств: Lets say I have a XMPP account, me@some.server,
телефон, ноутбук и настольный компьютер. and a few devices: a phone, a laptop, and a desktop computer.
Сначала я опишу воркфлоу общими словами, First Ill describe my mindset at a high level,
а потом дам уточнения про использование конкретных приложений. then Ill add some notes about specific clients.
Я предпочитаю следовать такому майндсету: ### Client Roles
С одной стороны,
у меня есть мобильное устройство, On the one hand, I have my phone.
которое всегда со мной и практические всегда онлайн: Its almost always with me and almost always online.
на нём я храню полную историю переписок и получаю уведомления в реальном Thats where I keep the full chat history and get real-time notifications.
времени.
С другой стороны, у меня есть несколько десктопных приложений: On the other hand, I have a couple of desktop applications.
я открываю их только когда мне нужно обсудить что-нибудь с использованием I only open them when I need to discuss something using my keyboard
клавиатуры или копи-пастинга. or move some text between devices.
Мне нравится думать о них, как о приложениях-сателлитах. I like to think of them as ad-hoc or satellite clients.
### Before the Start ### Before the Start
Первым делом мне нужно сгенерировать на каждом устройстве приватные ключи. First, enable OMEMO encryption on every client if it isn't enabled by default.
Обычно это происходит автоматически. The client will usually generate the keys and fingerprint automatically.
Потом я должен на каждом своём устройстве добавить остальные: The next step is to add all clients to the trust list on each device:
телефон должен считать все мои компьютеры доверенными устройствами, my phone should trust all my computers,
а компьютеры доверять друг другу и телефону. and my computers should trust each other as well as my phone.
Фингерпринты публичные, Fingerprints do not have to be secret, so they can be published on
их можно даже разместить у себя на какой-нибудь личной странице. your website or even on social media profiles.
Вот, например, моя: https://oddsquat.org/about/keys/ Here is my page with the fingerprints:
https://oddsquat.org/about/keys/
### Start the Conversation in Person ### Start the Conversation in Person
Предположим, я встретил Алису и мы решили обменяться контактами. Lets say I meet Alice,
Я открыл на телефоне специальный QR-код, we start talking, and decide to continue the conversation online.
затем Алиса считала его своим клиентом.
В этот QR-код уже зашиты фингерпринты всех моих устройств, так что
дополнительных действий не требуется.
Аналогично, я своим мобильным клиентом считываю QR-код с экрана Алисы.
Теперь мы оба уверены, что в переписке будем участвовать именно мы, I open a special QR code on my phone, and Alice scans it with her client.
а все наши сообщения будут доступны на всех наших устройствах и только на них. This QR code already contains the fingerprints of all my devices,
so no extra steps are needed.
Then I do the same and scan the QR code from Alices screen
with my mobile client.
Now we are both sure that its really us in the conversation,
and that all messages will be available on all our devices and only on them.
### Start the Conversation Online ### Start the Conversation Online
Предположим, что мы начали обсуждать что-то с Бобом где-то в сети Lets say Bob and I start discussing something
(на форуме, в федиверсе, не важно) и решили продолжить обсуждение в мессенджере. on a forum or in the Fediverse,
and then decide to move to XMPP.
Боб инициирует переписку, я слепо доверяю первому устройству, Bob starts the chat. I trust the first device he messages me from,
с которого он мне написал и уже потом мы обмениваемся в переписке and then we exchange fingerprints for our other devices, if we have any.
фингерпринтами остальных наших устройств, если они есть. This approach is called TOFU (Trust On First Use).
Такая стратегия называется ToFu.
Опять же Боб может убедиться, что я это я с помощью моей страницы с ключами, Bob can confirm its really me using my page with fingerprints.
а я могу убедиться, что Боб на форуме -- тот же самый Боб, попросив его I can confirm its really him by asking him to send his fingerprints
прислать мне фингерпринты прямо в личных сообщениях на том же самом форуме или in a private message on the same forum or via email.
отдельно посредством email, например.
В идеальном случае, Ideally, Bob also has a public page with his fingerprints.
у Боба тоже есть какая-то публичная страница с фингерпринтами. That way, we can both independently verify
Тогда мы оба можем независимо убедиться, that we are who we say we are.
что мы именно те, за кого себя выдаём =)
### New or Lost Devices ### New or Lost Devices
Если я решил начать использовать If I start using a new device or install another client application,
какое-то новое устройство или установить куда-нибудь the first thing I do is add it to the list of trusted clients
ещё одно клиентское приложение, on my existing devices.
то первым делом я должен добавить его в список доверенных клиентов
на остальных моих существующих устройствах.
Если я по каким-либо причинам потеряю любое из своих устройств If I lose one of my devices or delete any private keys,
или зачем-то удалю один из своих приватных ключей, the first thing I do is remove the corresponding client
то первым делом я должен исключить такой клиент из списка доверенных from the trusted list on my other devices.
на остальных моих устройствах.
После актуализации моих личных списков доверенных устройств Once Ive updated all my personal lists,
стоит сообщить об изменениях моим собеседникам по довереным каналам. I should inform my contacts about changes via trusted channels.
Я могу просто попросить Алису считать мой новый QR-код при следующей встрече,
а Бобу отправить сообщение о том, I can simply ask Alice to scan my new QR code the next time we meet,
что утраченому устройству доверять больше не стоит, and send Bob a message introducing my new client or letting him know
настоящих сообщений с него уже никогда не придёт. that the lost device is no longer trusted
and that no real messages will ever come from it again.
## Client Applications ## Client Applications
Этот раздел описывает особенности применения OMEMO для конкретных клиентов, This section describes how OMEMO is used in specific client applications
которыми я пользуюсь сам. that I personally use.
### Conversations, Monocles and Other Forks ### Conversations and Forks
Conversation - это современное полнофункциональное чат-приложение. Conversations is a modern, fully featured chat application for Android.
Оно поддерживает всё, что должно поддерживать: It supports everything a messaging app should support:
переписки, звонки, отправку фотографий и файлов. chats, voice calls, and sharing photos and files.
У него есть несколько форков, в которых UX может отличаться,
но core-фичи работают абсолютно одинаково.
На экране с информацией о конакте (в том числе и о своём аккаунте) There are several forks of it where the UI or UX may differ,
можно увидеть список фингерпринтов, but the core features work exactly the same.
вручную отметить галочкой доверенные или отозвать доверие. I personally use Monocles Chat.
Упростить все эти рутинные вещи призвана система с QR-кодами: On the Contact Details screen (including your own account),
прямо на главном можно показать свой код или считать чужой. you can see a list of published fingerprints
Так верификация устройств при личной встрече становится простой и ненапряжной. and manually mark them as trusted or revoke trust.
Правило большого пальца - сканируй QR-код при каждом удобном случае. To simplify all these routine operations, a QR-code-based system is used:
You can show your own QR code or scan other peoples codes
directly from the main screen.
This makes device verification during in-person meetings simple and effortless.
### Dino ### Dino
Это лёгкий GUI-клиент, построенный на GTK фреймвоке. Dino is a lightweight GTK-based GUI client.
Опять же, все вопросы доверия и недоверия
можно легко решить на экране "Детали контакта" с помощью чекбоксов.
К сожалению, по умолчанию, Dino настроен на автоматическое доверие It can be considered a fully functional one,
новым фингерпринтам, я рекомендую эту функцию отключить. although some non-essential features are still not supported or implemented.
For example,
it is not possible to clear local chat history using built-in methods :D
Trust and untrust decisions can be easily managed
in the Encryption tab of the Conversation Details window.
It is important to note that, by default, Dino is configured
to automatically trust new fingerprints.
I recommend disabling this feature.
### Profanity ### Profanity
Это могучий TUI-клиент, Profanity is a powerful TUI client
где всё-всё-всё реализовано через встроенную систему команд. where everything is controlled through a built-in command system.
Если вы зачем-то намерены им пользоваться, If you somehow intend to use it,
то ниже вас ожидает небольшой читшит по использованию OMEMO, below you will find a small cheat sheet for using OMEMO.
но я настойчиво рекомендую ознакомиться с полной документацией самостоятельно. However, I strongly recommend reading the full documentation.
- Генерация ключа и добавление своих устройств: - Generate a key and add your other clients:
```text ```text
/omemo gen /omemo gen
/omemo trust me@some.server some-cool-fingerprint-01 /omemo trust me@some.server some-cool-fingerprint-01
@ -356,26 +349,26 @@ Conversation - это современное полнофункциональн
/omemo qrcode /omemo qrcode
``` ```
- Увидеть список своих или чужих fingerprint'ов: - View the list of your own or someone elses fingerprints:
```text ```text
/omemo fingerprint me@some.server /omemo fingerprint me@some.server
/omemo fingerprint alice@another.server /omemo fingerprint alice@another.server
``` ```
Доверенные будут помечены как `trusted`. Trusted ones will be marked as `trusted`.
- Начать зашифрованный диалог: - Start an encrypted conversation:
```text ```text
/omemo start alice@another.server /omemo start alice@another.server
``` ```
- Добавить чужой фингерпринт в список доверенных: - Add fingerprints to the trusted list:
```text ```text
/omemo trust alice@another.server some-cool-fingerprint-02 /omemo trust alice@another.server some-cool-fingerprint-02
/omemo trust alice@another.server some-cool-fingerprint-03 /omemo trust alice@another.server some-cool-fingerprint-03
/omemo trust bob@another.server some-cool-fingerprint-04 /omemo trust bob@another.server some-cool-fingerprint-04
``` ```
- Перестать доверять кокретному клиенту: - Revoke trust for a specific client:
```text ```text
/omemo untrust alice@another.server some-cool-fingerprint-02 /omemo untrust alice@another.server some-cool-fingerprint-02
``` ```