Cryptography Whitepaper: VERSION: JUNE 21, 2021
Cryptography Whitepaper: VERSION: JUNE 21, 2021
Overview 4
Open Source 5
End-to-End Encryption 5
Key Generation and Registration 5
Key Distribution and Trust 6
Message Encryption 7
Group Messaging 8
Key Backup 8
Cryptography Details 12
Key Lengths 12
Random Number Generation 13
Forward Secrecy 14
Padding 14
Repudiability 15
Replay Prevention 15
Key Storage 16
iOS 16
Android 16
Push Notifications 17
iOS 17
Android 17
ID Revocation 19
An Example 19
Profile Pictures 19
Web Client 20
Architecture 20
Connection Buildup 21
WebRTC Signaling 22
WebRTC Connection Buildup 22
Trusted Keys / Stored Sessions 23
Push Service 23
Self Hosting 24
Links 24
Threema Calls 24
Signaling 24
Call Encryption 24
Audio Encoding 25
Video Encoding 25
Privacy / IP Exposure 25
Threema Safe 26
Overview 26
Backup Format 27
Encryption 27
Upload/Storage 27
Backup Intervals 28
Restore/Decryption 28
Running a Custom Threema Safe Server 28
These layers and other important aspects of the cryptography in Threema are described in
detail in the following chapters. The crucial part is that the end-to-end encryption layer passes
through the server uninterrupted; the server cannot remove the inner encryption layer.
End-to-End
Encryption Layer
End-to-End Encryption
In Threema, all messages (whether they are simple text messages, or contain media like
images, videos or audio recordings) are end-to-end encrypted. For this purpose, each
Threema user has a unique asymmetric key pair consisting of a public and a private key
based on Elliptic Curve Cryptography. These two keys are mathematically related, but it is not
technically feasible to calculate the private key given only the public key.
When a Threema user sets up the app for the first time, the following process is performed:
1. The app generates a new key pair by choosing a private key at random1, storing it securely
on the device, and calculating the corresponding public key over the Elliptic Curve
(Curve25519).
2. The app sends the public key to the server.
3. The server stores the public key and assigns a new random Threema ID, consisting of 8
characters out of A-Z/0-9.
4. The app stores the received Threema ID along with the public and private key in secure
storage on the device.
1 including entropy generated by user interaction; see section “Random Number Generation” for details
The public key of each user is stored on the directory server, along with its permanently
assigned Threema ID. Any user may obtain the public key for a given Threema ID by querying
the directory server. The following input values can be used for this query:
• a full 8-character Threema ID
• a hash of a E.164 mobile phone number that is linked with a Threema ID (see section
“Address Book Synchronization” for details on the hashing)
• a hash of an email address that is linked with a Threema ID
The Threema app maintains a “verification level” indicator for each contact that it has stored.
The following levels are possible:
Red (level 1): The public key has been obtained from the server because a message
has been received from this contact for the first time, or the ID has been entered manually. No
matching contact was found in the user’s address book (by phone number or email), and
therefore the user cannot be sure that the person is who they claim to be in their messages.
Orange (level 2): The ID has been matched with a contact in the user’s address book
(by phone number or email). Since the server verifies phone numbers and email addresses, the
user can be reasonably sure that the person is who they claim to be.
Green (level 3): The user has personally verified the ID and public key of the contact
by scanning their QR code. Assuming the contact’s device has not been hijacked, the user can
be very sure that messages from this contact were really written by the person that they
indicate.
In the Threema Work app, the following levels are possible in addition to the ones mentioned
above:
Blue (level 2): The ID is a Threema Work internal contact that has not been
personally verified by scanning the QR code.
Blue (level 3): The ID is a Threema Work internal contact that has been personally
verified by scanning the QR code.
To upgrade a contact from the red or orange to the green level, the user must scan that
contact’s public QR code. This QR code is displayed in the “My ID” section of the app, and
uses the following format:
3mid:<identity>,<publicKeyHex>
where <identity> is the 8-character Threema ID, and <publicKeyHex> is the
hexadecimal (lowercase) representation of the user’s 32 byte public key. The app verifies that
Key Fingerprints
The app displays a key fingerprint for each contact, and for the user’s own identity. This can be
used to compare public keys manually. A key fingerprint is created by hashing the raw public
key with SHA-256, and taking the first 16 bytes of the resulting hash as the fingerprint.
Message Encryption
Threema uses the “Box” model of the NaCl Networking and Cryptography Library to encrypt
and authenticate messages. For the purpose of this description, assume that Alice wants to
send a message to Bob. Encryption of the message using NaCl works as follows:
Preconditions
1. Alice and Bob have each generated a key pair consisting of a public and a
private key.
2. Alice has obtained the public key from Bob over an authenticated channel.
By reversing the above steps and using his own private key and Alice’s public key, Bob can
decrypt the message and verify its authenticity.
Random
Nonce
generator
MAC
Ciphertext
Nonce
Group Messaging
In Threema, groups are managed without any involvement of the servers. That is, the servers
do not know which groups exist and which users are members of which groups. When a user
sends a message to a group, it is individually encrypted and sent to each other group member.
This may appear wasteful, but given typical message sizes of 100-300 bytes, the extra traffic
is insignificant. Media files (images, video, audio) are encrypted with a random symmetric key
and uploaded only once. The same key, along with a reference to the uploaded file, is then
distributed to all members of the group.
Key Backup
The user can back up their private key so that they are able to move their Threema ID to
another device, or to restore it in case of loss/damage to the device. The app automatically
reminds the user to do so, as without a backup, there is no way to recover a lost private key.
To generate a backup, the user must first choose a password (min. 8 characters).
The encrypted backup data consists of 80 characters (A-Z, 2-7). It is also displayed in QR
code form so that the user can more easily transfer it to another device.
The chat protocol is used to transport incoming and outgoing messages between the client
(app) and the Threema servers. It is a custom binary protocol that uses the NaCl library to
secure the connection on the application layer. Its properties are:
Requests are authenticated with a challenge/response protocol based on the user’s Threema
ID and key pair.
HTTPS (HTTP with TLS) is used as the transport protocol. Strong TLS cipher suites with
forward secrecy (ECDHE/DHE) and TLS v1.2 are supported. In order to preclude man-in-the-
middle (MITM) attacks even if the system’s trusted CA store has been tampered with, or if a
trusted CA has illegally issued a certificate for a Threema domain name, the app uses public-
key pinning with hardcoded pins to only accept specific, Threema-owned server certificates.
The media servers are used for temporary storage of large media data (e.g. images, videos,
audio recordings). Such media is not sent directly via the chat protocol. Instead, the following
procedure is used:
1. The sender encrypts the media file with a random 256-bit symmetric key using XSalsa20
and adds a Poly1305 authenticator.
2. The sender uploads the encrypted media file to a media server via HTTPS.
3. The media server assigns a unique ID for this upload and returns it to the sender.
4. The sender sends an end-to-end encrypted message to the recipient, which contains the
media ID and the symmetric key.
5. The recipient receives and decrypts the end-to-end encrypted message, obtaining the
media ID and the symmetric key.
6. The recipient uses the media ID to download the encrypted media file from the media
server.
7. The recipient decrypts the media file using the symmetric key.
The media servers use the same TLS configuration (cipher suites with forward secrecy, TLS
v1.2) as the directory servers, and the app uses public-key pinning when accessing them.
Cryptography Details
As mentioned earlier, Threema uses the NaCl Networking and Cryptography Library for both
the end-to-end encryption, and to secure the chat protocol at the transport level. This library
uses a collection of algorithms to provide a simplified interface for protecting a message using
what the authors call “public-key authenticated encryption” against eavesdropping, spoofing
and tampering. By default, and as implemented in Threema, it uses the following algorithms:
• Key derivation: Elliptic Curve Diffie-Hellman (ECDH) over the curve Curve25519
• Symmetric encryption: XSalsa20
• Authentication and integrity protection: Poly1305-AES
It is worth mentioning that the ECC curve used by NaCl (and thus by Threema) is not one
of the NIST-recommended curves that have been suspected of containing deliberately
selected weakening constants in their specification. For more details, see Cryptography in
NaCl.
Key Lengths
The asymmetric keys used in Threema have a length of 256 bits, and their effective ECC
strength is 255 bits.
The shared secrets, which are used as symmetric keys for end-to-end message encryption
(derived from the sender’s private key and the recipient’s public key using ECDH, and
combined with a 192 bit nonce), have a length of 256 bits.
The message authentication code (MAC) that is added to each message to detect tampering
and forgery has a length of 128 bits.
• https://www.imperialviolet.org/2014/05/25/strengthmatching.html
(Adam Langley, Google security researcher)
Threema uses random numbers for the following purposes, listed by descending order of
randomness quality required:
• Private key generation
• Symmetric encryption of media files
• Nonces
• Backup encryption salt
• Padding amount determination
Nonces and salts must never repeat, but they are not required to be hard to guess.
To obtain random numbers, Threema uses the system-provided random number generator
(RNG) intended for cryptographically-secure purposes provided by the device’s operating
system. The exact implementation varies among operating systems:
Note that Threema does not use the flawed Dual_EC_DRBG random number generator.
Forward Secrecy
Due to the inherently asynchronous nature of mobile messengers, providing reliable Forward
Secrecy on the end-to-end layer is difficult. Key negotiation for a new chat session would
require the other party to be online before the first message can be sent. Experimental
schemes like caching pre-generated temporary keys from the clients on the servers increase
the server and protocol complexity, leading to lower reliability and more potential for mistakes
that impact security. The user experience can also be diminished by events that are not under
the control of the sender, for example when the recipient loses their phone’s data, and along
with it the ephemeral keys. Due to these and the following considerations, Threema has
implemented Forward Secrecy on the transport layer only:
• Reliability is very important to ensure that users do not feel negatively impacted by the
cryptography.
• The risk of eavesdropping on any path through the Internet between the sender and the
server, or between the server and the recipient, is orders of magnitude greater than the risk
of eavesdropping on the server itself.
With Threema’s implementation, an attacker who has captured and stored the network traffic
between a client and a Threema server will not be able to decrypt it even if he learns the
private key of the server or the client afterwards.
Padding
In order to thwart attempts to guess the content of short messages by looking at the amount
of data, Threema adds a random amount of PKCS#7 padding to each message before end-to-
end encryption.
1 To avoid the flawed SecureRandom implementation in some Android versions, Threema uses its own implementation
that directly accesses /dev/random (which is not affected by the SecureRandom implementation bug).
In general, cryptographically signed messages also provide non-repudiation; i.e. the sender
cannot deny having sent the message after it has been received. The NaCl library’s box
model uses so-called public-key authenticators instead, which guarantee repudiability (see
http://nacl.cr.yp.to/box.html, “Security model”). Any recipient can forge a message that will
look just like it was actually generated by the purported sender, so the recipient cannot
convince a third party that the message was really generated by the sender and not forged
by the recipient. However, the recipient is still protected against forgeries by third parties.
The reason is that in order to perform such a forgery, the private key of the recipient is needed.
Since the recipient himself will know whether or not he has used his own private key for such
a forgery, he can be sure that no third party could have forged the message.
Replay Prevention
The Threema app remembers the nonce of every message that has been sent in the past,
and rejects messages with duplicate nonces. Since the server cannot successfully modify
the nonce of a message without knowing the private key of one of the parties involved in
the communication, this prevents a malicious server from replaying/duplicating previously
sent messages.
iOS
On iOS, Threema stores local data in a Core Data database, which is backed by files in the
app’s private data directory. The iOS sandbox model ensures that no other apps can access
this data directory. All files stored by Threema are protected using the iOS Data Protection
feature using the Data Protection class NSFileProtectionCompleteUntilFirstUser
Authentication. The encryption key used to protect the files is derived from the device’s
UID key and the user’s passcode. A longer passcode will provide better security (on devices
equipped with a Touch/Face ID sensor, longer passcodes can be used without a loss of
comfort as the passcode only needs to be entered after a reboot).
Note that the private key for the Threema ID is stored separately in the iOS Keychain.
On Android, Threema stores local data in an SQLite database within the app’s private data
directory. Android ensures that no other apps can access this data directory (as long as the
device is not rooted). The database itself is protected by SQLCipher with AES-256, and any
media files (which are stored separately in the app’s private directory within the file system)
are also encrypted using AES. The key is randomly generated when the database is first
created, and can be protected with a user-supplied passphrase (which is of course necessary
if the user wishes to take advantage of this encryption). The passphrase is never written to
permanent storage and therefore needs to be entered whenever the app process restarts (e.g.
after a low-memory situation, or after the device has rebooted). Alternatively, the user may
enable full-device encryption if supported by the device and Android version.
Key Storage
On the user’s mobile device, the private key is stored in such a way as to prevent access by
other apps on the same device, or by unauthorized users. The procedure differs between
platforms.
iOS
• The private key is stored in the iOS Keychain with the attribute
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly.
• Only the Threema app can access this keychain entry.
• While the entire iOS keychain is included in backups via iTunes or iCloud, the
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly attribute causes the keychain entry of
Threema to be encrypted with a device-specific key (“UID key”) that cannot be read directly
and is not known to Apple. Therefore, the keychain entry is only usable if the iTunes/iCloud
backup is restored to the same device.
• When the Threema app is deleted and reinstalled, the keychain entry persists and the
Threema ID is not lost.
Android
• The private key is stored in a file in the app’s private data directory.
• Other apps cannot access this file.
• AES-256-CBC encryption is applied to the private key before it’s written to the file. The
key for this encryption is stored separately and can be protected using a passphrase
(see section “Local Data Encryption” for details).
iOS
Android
The GCM payload is empty; that is, the GCM message only serves to wake up the Threema
app in the background. It then connects to the chat server to retrieve any pending messages,
decrypts them, and shows local notifications for them.
The directory server then compares the list of hashes from the user with the known email/
phone hashes of Threema IDs that have been linked with an email address and/or phone
number. Any matches are returned by the server as a tuple (Threema ID, hash). Only those
hashes that have already been submitted by the user are returned (i.e. if the user submits an
email hash which then matches a Threema ID, the server will only return the email hash of that
ID and not the linked phone number’s hash, even if one exists). After returning the matches to
the client, the directory server discards the submitted hashes.
Linking
If a user chooses to link their Threema ID to an email address or a phone number, the directory
server verifies that the user actually owns the email address or phone number in question.
• For email addresses, a verification email with a hyperlink is sent to the user. The user must
open the hyperlink and confirm in the browser before the ID link is established.
• For phone numbers, the directory server sends an SMS message with a random 6 digit
code. The user must enter that code in the app, which sends it back to the server to verify
the phone number.
• If the user cannot receive the SMS message, he/she may choose to receive an automated
phone call in which the code is read out.
Revocation passwords are hashed with SHA256 on the client side, but only the first four
bytes are sent to and stored/compared on the directory server. This mitigates the possibility
of brute-force hash cracking on the server side to recover the user’s password. Obviously, the
downside is that the stored key has significantly less entropy than a reasonable user password
and a large number of possible passwords correspond to each key. However, the server can
easily limit the number of key revocation attempts over a period of time.
An Example
A user has set an eight character revocation password with a combination of characters
consisting of the lowercase latin alphabet (a-z) and digits. This results in 368 ≅ 241.36
combinations.
Therefore, a given key can correspond with over 600 different passwords of this length and
character set. On the other hand, the probability of randomly choosing the correct hash value
without knowing anything about the password is 2-32 ≅ 0.000000023%. Assuming that a user
gets three attempts per day, the probability of finding the correct hash value within 10 years is
≅ 0.000255%.
Profile Pictures
It is possible for a user to select a photo to be used as his/her “profile picture”. The user can
choose within the app whether he/she wants to share the profile picture with all their contacts,
with only those contacts selected from a list, or with nobody. If he/she chose to share the
profile picture and sends a message to one of the designated recipients, the newly set profile
picture is encrypted with a random symmetric key within the app, and then uploaded to
the media server like a regular image message. A reference to the encrypted picture on the
media server, along with the symmetric key, is subsequently sent as an end-to-end encrypted
message in the background whenever the user sends a regular message to one of the
designated contacts who has not received the current profile picture yet. As the media server
deletes files after two weeks, the profile picture is uploaded again once a week (if necessary),
using a new symmetric key each time.
The following paragraphs explain the general architecture of the Threema web client
implementation as well as some aspects of the signaling protocol. If you want to learn more
about the WebRTC signaling protocol, please refer to the main specification as well as the
WebRTC task specification.
Architecture
1
SaltyRTC Server Handshake
(WebSocket, over TLS)
2
SaltyRTC Client Handshake
and Signaling (E2E
Signaling Server Encrypted)
2
3
WebRTC Data Channel
1a 1b (Android only): E2E
Encrypted with SaltyRTC)
The web client and the app form a client-server relationship. All data about new events and
old conversations is exchanged directly between the two through an end-to-end encrypted
channel.
When the web client is started, it requests the initial data (conversations, contacts, avatars,
etc.) from the app. The app responds with the requested data.
Connection Buildup
The public permanent key of the web client as well as the authentication token and the
protocol version are transferred to the app through a QR code. The app first generates its own
permanent key-pair and then connects to the same WebSocket path as responder.
Both peers conduct the server handshake according to the SaltyRTC protocol.
The two peers each generate a random session key-pair independent of the permanent key-
pair. The public session keys are exchanged. Additionally, the peers exchange information on
how they intend to communicate after the client handshake (the so-called SaltyRTC Task):
• Android devices request to communicate over WebRTC data channels
• iOS devices request to communicate over the signaling channel
The transfer of data between browser and app differs between Android and iOS, due to
platform constraints:
2.1 Android
After the client handshake is successful and both peers know each other’s public session key,
they initiate a WebRTC PeerConnection. The necessary signaling information to build up the
connection (like offer, answer and ICE candidate messages) are exchanged via the WebSocket
connection, encrypted with the session keys.
The two peers now open a second WebRTC data channel in order to exchange application
data. All packets transferred through that data channel are encrypted using the session keys.
2.2 iOS
After the client handshake is successful and both peers know each other’s public session
key, they can immediately start exchanging application data over the established WebSocket
signaling connection. All packets transferred through that channel are encrypted using the
session keys.
WebRTC Signaling
The direct communication channel between the app and the Android web client is established
using a WebRTC PeerConnection. In order to establish such a peer-to-peer connection,
a signaling channel is inevitable. Common signaling server implementations often use
WebSockets without any end-to-end encryption (often even without transport encryption),
meaning that the server can read all (potentially sensitive) network information of the peers
connecting. There is also the risk of a server manipulating the data being transmitted, opening
up possibilities of MITM attacks.
Because networks in the real world don’t always make it possible to establish a direct
connection between two peers due to obstacles like firewalls, NATs, CGNs and the like,
WebRTC connection buildup may have to resort to mechanisms like STUN and TURN. STUN
(Session Traversal Utilities for NAT) is a protocol that allows to find each other’s public IP
despite the existence of NATs. TURN (Traversal Using Relays around NAT) is a protocol that
provides relaying of data packets in case the connection buildup using STUN alone fails.
Note, however, that even though a TURN server relays packets between two peers, it cannot
know anything about the content of these packets as they are both end-to-end encrypted by
WebRTC using DTLS and end-to-end encrypted by SaltyRTC.
In order to prevent having to scan the QR code each time a connection needs to be
established, the public permanent key of the peer can optionally be stored as a trusted key.
To be able to securely store this information in the browser, users must provide a password
if they want to be able to restore the session at a later point in time. The public permanent
key of the app as well as the private permanent key of the web client are then encrypted with
the provided user password using authenticated NaCl secret key encryption (XSalsa20 +
Poly1305) and stored in local browser storage.
On the app side, the public permanent key of the web client and the private permanent key of
the app are stored in the encrypted app database.
When reconnecting to an existing session, instead of creating a new permanent key-pair, the
peers restore the trusted key-pair before initiating the server and client handshake. Note,
however, that new session keys are still created, thus offering perfect forward secrecy on a
session level.
Push Service
On Android devices, if Google Play Services are installed on the device of the user, the FCM
push token (an opaque string provided by Google) is transferred to the web client together
with the initial data.
On iOS devices, the APNs push token (an opaque string provided by Apple) is transferred to
the web client together with the initial data.
If the user requests to persist a session, the token is then stored in the local browser storage
together with the trusted keys, encrypted with a key derived from the user-provided password.
When reconnecting a web client session (e.g. when the user requests to restore a previous
session, or when automatically reconnecting due to connection loss) and if a push token is
available, the browser sends this token via HTTPS to a push relay server provided by Threema,
together with the SHA256 hash of the public permanent key of the initiator. The push relay
server then sends the hash to the app as a FCM/APNs push notification. When the app
receives such a notification, it first checks whether the web client is enabled. If it is enabled
and if a web client session with the specified public key exists, that session is started and
connects to the SaltyRTC server for the handshake and reconnection procedure.
All components of the web client (except the code in the Threema app itself) are published
under open source licenses (see the beginning of this document for repository links).
The URL and public permanent key of the SaltyRTC server to be used are transferred through
the QR code and stored together with the session information. This allows the user to entirely
bypass the web server and SaltyRTC server operated by Threema, if desired. Instructions
on how to set up a self-hosted Threema Web instance can be found in the Threema Web
repository.
The push relay cannot practically be run by an end user, since the FCM API key and the APNs
certificates are not public, but the source code is provided on GitHub for review purposes.
Links
1. https://webrtc.org/
2. https://saltyrtc.org/
3. https://github.com/saltyrtc/saltyrtc-meta/blob/master/Protocol.md
4. https://github.com/saltyrtc/saltyrtc-meta/blob/master/Task-WebRTC.md
5. https://github.com/saltyrtc/saltyrtc-meta/blob/master/Task-RelayedData.md
6. https://github.com/threema-ch/threema-web/blob/master/docs/self_hosting.md
Threema Calls
Threema Calls are based on WebRTC, an open IETF standard. WebRTC uses the ICE, STUN
and TURN protocols to establish a secure peer-to-peer connection.
Signaling
Signaling data is sent through Threema messages, thus providing the same end-to-end
security and trust level as a regular Threema conversation. If you have verified your contact,
you can also trust your phone calls with that contact.
Call Encryption
The audio stream is encrypted with the SRTP protocol, with DTLS-SRTP being used for
the key exchange. The certificates used for the DTLS session are cryptographically linked
to the keys used for Threema’s end-to-end encryption by means of including the certificate
fingerprints in signaling messages. DTLS version 1.2 is enforced.
The SRTP ciphersuites offered by the Threema app are (in that order):
• SRTP_AEAD_AES_256_GCM (0x0008)
• SRTP_AEAD_AES_128_GCM (0x0007)
• SRTP_AES128_CM_HMAC_SHA1_80 (0x0001)
Audio Encoding
Audio data is encoded using the state-of-the-art Opus codec at 48 kHz. To avoid potential
privacy and security issues associated with variable bitrate audio codecs1, Threema Calls
always enforce constant bitrate to encode the audio stream.
Video Encoding
Privacy / IP Exposure
WebRTC connections can be established in two ways: Either a direct connection between the
two devices is used (using STUN to help with NAT traversal), or one or both sides use a TURN
server to relay the encrypted packets.
Relaying has the advantage of hiding the public IP address from the call partner, thus
providing added privacy when the peer is not trusted. On the other hand it exposes some
metadata towards the TURN server, and the connection quality (especially latency) may
be worse than in a direct call. By default, Threema enforces relaying through TURN for all
unverified contacts (with a single red dot as verification status). Optionally, users can enforce
relaying for all calls through the “Always relay calls” option in the “Privacy” settings.
Threema Safe is an encrypted server-based backup solution that encompasses the following
user-specific data:
• Threema ID
• Private key
• Profile information
• Nickname
• Profile photo
• Linked email address and phone number
• Contact list
• Contact Threema ID
• Public key
• Name
• Verification level
• Group definitions
• Group ID
• Creator
• Group name
• List of members
• Distribution lists
• Name
• List of members
• App settings
Messages and media data are not part of a Threema Safe backup.
The rationale behind Threema Safe is to give users a secure backup option that allows them
to restore their Threema ID and important related data, or to move it to another device, using
nothing but the knowledge of their Threema ID and the Threema Safe password that they
have chosen.
The use of Threema Safe is optional; the user can choose to enable or disable it at any time.
By default, encrypted backups are stored on Threema servers, but the user can use their own
server as a backup store instead. A Threema Safe backup server cannot tell which backup
belongs to which Threema user by looking at the uploaded data.
The Threema app compiles the information mentioned in the previous section as a JSON
document (binary values like the private key or profile photo are encoded in Base64). This
JSON document is then compressed with gzip and encrypted as follows. The resulting
encrypted backup typically has a size of only a few dozen kilobytes (depending mostly on the
profile photo size, number of contacts and groups).
Encryption
In order to set up Threema Safe, the user must choose a password consisting of at least 8
characters. The app checks whether the password is on a list of the most frequently used
passwords, and warns the user if that is the caseFrom the password and the Threema ID of
the user, a Threema Safe Master Key is derived as follows:
• threemaSafeMasterKey = scrypt(P = Password, S = Threema ID, N =
65536, r = 8, p = 1, dkLen = 64)
The scrypt parameters have been chosen to provide a reasonable trade-off between
calculation time, memory usage and security without precluding the use on older/lower-end
devices.
The scrypt output is then split into two parts of 32 bytes each as follows:
• threemaSafeBackupId = threemaSafeMasterKey[0..31]
• threemaSafeEncryptionKey = threemaSafeMasterKey[32..63]
The Threema Safe backup data in the form of a UTF-8 encoded JSON string (plaintext)
is then encrypted as follows:
1. Compress using gzip: gzippedPlaintext = gzip(plaintext)
2. Generate random 24 byte nonce: nonce = randombytes(24)
3. threemaSafeEncryptedBackup = nonce ||
crypto_secretbox(gzippedPlaintext,
threemaSafeEncryptionKey, nonce)
|| = concatenation
The crypto_secretbox operation is described in the NaCl documentation.
Upload/Storage
When Threema Safe is enabled and a backup password is set, the Threema app generates
a backup once per day when the app is in use. If the backup data has changed since the last
upload, or if more than half of the server-specified backup retention time has passed, then
the backup is uploaded to the server, replacing any existing backup with the same ID that may
already exist on the server.
Restore/Decryption
The decrypted and decompressed JSON document (plaintext) is then used to restore the
Threema ID and other information.
When setting up Threema Safe, a custom backup server URL may be specified by the
user. This URL must start with https:// and may include username/password information
(e.g. https://username:[email protected]/path). The server must use a TLS
certificate trusted by the operating system.
The server must respond to the following requests (paths relative to the backup URL):
Code Description
Example Response
{
"maxBackupBytes": 524288,
"retentionDays": 180
}
The app uses maxBackupBytes to determine whether a backup is too big to be uploaded
(in which case the user is alerted). retentionDays is used to determine backup expiration:
if retentionDays/2 days have elapsed since the last backup, the backup is uploaded again
even if the backup data has not changed, to keep the backup from expiring.
Create/Update Backup
PUT backups/<threemaSafeBackupId>
Content-Type: application/octet-stream
Validation
• The threemaSafeBackupId must be a 64 character lowercase hex string
• The Content-Type header must be set to application/octet-stream
Response Codes
Code Description
200 OK The backup was created or updated (for servers that do not differentiate
between the two).
Validation
• The threemaSafeBackupId must be a 64 character lowercase hex string
• The Accept header must be set to application/octet-stream
Response Codes
Code Description
Delete Backup
DELETE backups/<threemaSafeBackupId>
Validation
• The threemaSafeBackupId must be a 64 character lowercase hex string
Response Codes
Code Description
Security Recommendations
The following recommendations are not required for automated backups to work, but they
improve security. Implementing these recommendations is especially important when offering
a public service.
If the server software itself does not support rate limiting, this can be implemented by using a
Proxy like Nginx or HAProxy.
Data Retention
Backups should be automatically deleted after a certain amount of time, as specified in the
“retentionDays” configuration key.