Compare commits

..

No commits in common. "a0766ff728fd76763c3b5bb4f724e60d37736c32" and "5da77a6fc69f33d112aa97a6a766d62d9ce04315" have entirely different histories.

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 the time, the proprietary messenger kept making life harder At that time, the proprietary messenger once again made 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, Хочу также отметить,
means a specific instance of an XMPP application on a user device. что я буду использовать слово Client для обозначения конкретных инстансов
<br>OMEMO-related documentation uses the term Device, приложений на пользовательских устройствах. В документации, связанной с OMEMO
but I find it potentially confusing: для этого использвется термин Device, но мне он кажется запутывающим:
in practice, a single physical device can run multiple independent clients. в реальности на одном устройстве может быть несколько независимых клиентов.
## Basic Concepts ## Basic Concepts
This section introduces some basic ideas behind end-to-end encryption. Here I'm going to explain some basic ideas behind e2e.
If you're already familiar with the concepts and terminology, Если основные концепции и терминология вам знакомы,
you can skip ahead to&nbsp;<a то можете смело пропустить этот раздел
href='#'>how end-to-end encryption affects the XMPP user experience</a> и перейти к особенностям их практического применения касательно XMPP.
or jump straight to the <a
href='#'>step-by-step workflow</a>&nbsp;I personally use. Или даже сразу перейти к описанию workflow, которого я придерживаюсь сам.
### Trade-offs Between Safety and Convenience ### Trade-offs Between Safety and Convenience
@ -108,240 +108,247 @@ is actually based on XMPP, but incompatibly altered and defederated.
### Keys, Fingerprints and Trust ### Keys, Fingerprints and Trust
OMEMO is based on the Double Ratchet Algorithm. OMEMO построен вокруг 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.
Keys are usually managed automatically by the XMPP client, Ключи обычно как-то автоматически управляются XMPP клиентом
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 или по уже довереному и безопасному каналу связи
that the fingerprint belongs to their device, сказать вам "Да, фингерпринт XXX принадлежит моему устройству"
and only then you mark it as trusted. и только после этого вы помечаете XXX доверенным.
In most XMPP clients this is simply done by ticking a checkbox Обычно в интерфейсе это просто проставление чекбокса или сканирование QR-кода.
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: Список доверенных фингерпринтов используется в момент отправки сообщения:
it's not possible to "extend" trust to new clients OMEMO творит какую-то магию с жонглированием ключами и
after a message has already been encrypted and sent. ни один клиент, кроме перечисленных в списке на момент зашифровки,
не сможет его впоследствии расшифровать.
Передать как-то доверие в прошлое, увы, невозможно.
## Practical Aspects of OMEMO and XMPP ## Реалии OMEMO и XMPP
## Особенности OMEMO и XMPP
### Chat History ### Chat History
In theory, XMPP supports server-side message history storage via Вообще, XMPP поддерживает хранение истории переписок на сервере.
**XEP-0313: Message Archive Management**. За это отвечает **XEP-0313: Message Archive Management**.
In practice, support for this XEP, В реальности поддержка этого 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 Отправка своих же сообщений ещё и самому себе
на уровне протокола -- это довольно неочевидная фича.
It's important to note that with end-to-end encryption, Тут важно упомянуть, что при использовании e2e шифрования,
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 was designed as a set-it-and-forget-it solution, OMEMO был задуман как решение, которое после настройки не требует какого-то
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
Lets say I have a XMPP account, me@some.server, Представим, что у меня есть аккаунт jid@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. их можно даже разместить у себя на какой-нибудь личной странице.
Here is my page with the fingerprints: Вот, например, моя: https://oddsquat.org/about/keys/
https://oddsquat.org/about/keys/
### Start the Conversation in Person ### Start the Conversation in Person
Lets say I meet Alice, Предположим, я встретил Алису и мы решили обменяться контактами.
we start talking, and decide to continue the conversation online. Я открыл на телефоне специальный QR-код,
затем Алиса считала его своим клиентом.
В этот 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
This section describes how OMEMO is used in specific client applications Этот раздел описывает особенности применения OMEMO для конкретных клиентов,
that I personally use. которыми я пользуюсь сам.
### Conversations and Forks ### Conversations, Monocles and Other Forks
Conversations is a modern, fully featured chat application for Android. Conversation - это современное полнофункциональное чат-приложение.
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. вручную отметить галочкой доверенные или отозвать доверие.
On the Contact Details screen (including your own account), Упростить все эти рутинные вещи призвана система с QR-кодами:
you can see a list of published fingerprints прямо на главном можно показать свой код или считать чужой.
and manually mark them as trusted or revoke trust. Так верификация устройств при личной встрече становится простой и ненапряжной.
To simplify all these routine operations, a QR-code-based system is used: Правило большого пальца - сканируй QR-код при каждом удобном случае.
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
Dino is a lightweight GTK-based GUI client. Это лёгкий GUI-клиент, построенный на GTK фреймвоке.
Опять же, все вопросы доверия и недоверия
можно легко решить на экране "Детали контакта" с помощью чекбоксов.
It can be considered a fully functional one, К сожалению, по умолчанию, Dino настроен на автоматическое доверие
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
Profanity is a powerful TUI client Это могучий TUI-клиент,
where everything is controlled through a built-in command system. где всё-всё-всё реализовано через встроенную систему команд.
If you somehow intend to use it, Если вы зачем-то намерены им пользоваться,
below you will find a small cheat sheet for using OMEMO. то ниже вас ожидает небольшой читшит по использованию 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
@ -349,26 +356,26 @@ However, I strongly recommend reading the full documentation.
/omemo qrcode /omemo qrcode
``` ```
- View the list of your own or someone elses fingerprints: - Увидеть список своих или чужих fingerprint'ов:
```text ```text
/omemo fingerprint me@some.server /omemo fingerprint me@some.server
/omemo fingerprint alice@another.server /omemo fingerprint alice@another.server
``` ```
Trusted ones will be marked as `trusted`. Доверенные будут помечены как `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
``` ```