Securing WebRTC Signaling: How Twinme Encrypts SDPs for Safe Device Connections

By Stephane Carrez

WebRTC has revolutionized real-time communication, enabling everything from video calls to IoT device synchronization. At Twinlife, we use WebRTC to power seamless, low-latency connections between the devices running our applications. But here’s the catch: WebRTC’s signaling phase—where the session descriptions (SDP offers and answers) are exchanged—is often overlooked as a security risk.

Imagine two devices negotiating a connection. The signaling server acts as a matchmaker, relaying session descriptions that contain critical metadata: the DTLS certificate fingerprint, the ICE credentials, the supported codecs and the ICE candidates with their IP addresses. Signaling usually runs over TLS, but the server terminates that TLS connection and sees everything that goes through it. WebRTC encrypts the media streams with DTLS-SRTP, yet the security of DTLS-SRTP rests on one thing: the certificate fingerprint carried in the session description. A server that can read and rewrite the session descriptions can replace the fingerprint and sit in the middle of the media encryption. It can also read the ICE credentials and the private network addresses of the devices.

At Twinlife, we’ve spent a decade hardening our WebRTC implementation. One of our key design choices? Encrypting SDPs before they ever reach the signaling server. Here’s how we do it—and why it matters.

TL;DR Twinlife encrypts WebRTC SDPs end-to-end using per-relation secrets, ensuring signaling servers—even if compromised—cannot read or tamper with connection metadata. Secrets are exchanged via public-key cryptography and rotated regularly, with no modifications to WebRTC itself.

Images/webrtc-signaling-encryption.jpg

The Basics: WebRTC and Signaling

What is WebRTC?

WebRTC (Web Real-Time Communication) is a set of protocols and APIs that enables peer-to-peer (P2P) communication directly between browsers or devices. In twinme and Skred, every audio call, video call and message exchange between two contacts goes through a WebRTC P2P connection: messages and files use a WebRTC data channel, calls use audio and video tracks.

The Role of Signaling

WebRTC requires a signaling mechanism to establish connections. This is where the SDP comes in:

  • SDP (Session Description Protocol) is a text-based format that describes the media streams, codecs, and network information needed to establish a connection. The offer and the answer exchanged by the two peers are session descriptions written in this format.
  • Signaling Server relays the session descriptions and ICE candidates between peers. It is distinct from the STUN and TURN servers, which only help the peers to discover their addresses and to relay the media when a direct path is not possible. Crucially, this server forwards the SDPs—but it shouldn’t be able to read them.

Why Unencrypted SDPs Are a Problem

An unencrypted SDP might look like this:

v=0
o=- 1234567890 2 IN IP4 192.168.1.1
s=-
c=IN IP4 192.168.1.1
a=ice-ufrag:abc123
a=ice-pwd:def456
a=fingerprint:sha-256 7A:8B:9C:...
a=candidate:1 1 udp 2122260223 192.168.1.1 51234 typ host
a=candidate:2 1 udp 1686052607 203.0.113.42 51234 typ srflx raddr 192.168.1.1 rport 51234

What’s exposed?

  • Fingerprint: identifies the DTLS certificate of the device. The DTLS handshake only verifies that the peer's certificate matches this fingerprint. An attacker able to replace it with its own can terminate DTLS on both sides and read or alter the media and the data channel.
  • ICE credentials (abc123, def456): let an attacker answer the connectivity checks of a peer and disrupt or redirect the connection attempt. Combined with the fingerprint substitution, they give a complete man-in-the-middle.
  • IP addresses: the signaling server already knows the public address of each device from the TLS connection, but the session description also reveals the private LAN addresses (192.168.1.1) and the full list of network paths of the device, which helps to fingerprint it over time.

Potential attacks:

  1. Tampering: Modifying SDPs to substitute the DTLS fingerprint or redirect traffic.
  2. Eavesdropping: An attacker intercepts SDPs to map network topologies or identify devices.
  3. Session Hijacking: Using stolen ICE credentials and a substituted fingerprint to insert a malicious peer into a session.

The Solution: Encrypting SDPs End-to-End

For twinme and Skred, we encrypt SDPs at the application layer before they leave the sender’s device. This ensures that only the intended recipient can decrypt and read the SDP—not even the signaling server can access the plaintext.

The important point is where the keys come from. We do not negotiate keys through the signaling server when a call starts—doing so would defeat the purpose, since an attacker with access to the server could intercept them. Instead, the two devices share secrets that were exchanged earlier through channels the server cannot read:

  • when the contact relation is created, inside an invitation encrypted for the peer's public key,
  • later, inside the WebRTC data channel of an already secured P2P connection, when the secrets are renewed.

Here’s the high-level flow:

  1. Secret Exchange: Before any P2P session, devices must exchange secrets. Each device generates a random 256-bit secret and sends it to the peer at contact creation (via a secure invocation encrypted with the peer's public key) or later through an already-secured P2P data channel.
  2. SDP Encryption: When a P2P session starts, the sender encrypts the SDP with its own secret (AES-256-GCM).
  3. Signaling: The encrypted SDP is sent to the signaling server, which forwards it opaque (unreadable).
  4. Decryption: The recipient uses its copy of the sender's secret to decrypt the SDP and proceed with the WebRTC handshake.

Step-by-Step Implementation

1. Identity Keys: the Twincodes

In twinme and Skred, a twincode is a unique identifier for a device, tied to cryptographic key pairs. A contact is a relation between two twincodes, one on each side. When a twincode is created, the device generates two private keys for it and keeps them in its encrypted database:

  • an X25519 key used for encryption (key agreement),
  • an Ed25519 key used for signatures.

The public keys are published as attributes of the twincode, and the attributes are signed with the Ed25519 key. Any device can fetch them from the server, verify the signature and know that the encryption key and the signing key belong together. The server distributes these public keys but never accesses the private keys.

2. Secret Exchange at Contact Creation

When Alice accepts Bob's invitation, her device sends a secure invocation (an end-to-end encrypted message) to Bob's twincode. The invocation carries a fresh secret generated by Alice's device. Bob's device answers the same way with its own secret. At the end of the exchange, each relation has two secrets (one per direction): Alice encrypts with her secret, and Bob decrypts with his copy of it. Each secret is only ever used for encryption by the device that generated it.

The invocation itself is protected with the twincode keys:

  • a random 32-byte salt is generated for each message,
  • an X25519 agreement between the sender's private key and the receiver's public key produces a shared secret; an HMAC-SHA256 keyed with that shared secret, computed over the salt, the sender's public key and the receiver's public key, gives the one-time AES-256-GCM key, so the key is bound to the salt and to both identities,
  • the payload carrying the sender's signing key, the secret index and the secret is encrypted with that key,
  • the version, nonce sequence, salt, and sender identity remain in cleartext but are covered by the AES-GCM authentication tag, so any tampering is detected.

The secret is generated and selected in CryptoServiceImpl.encrypt(), here is the part that builds the encrypted payload:

// 1. Authenticated (but not encrypted) header
encoder.writeInt(version);
encoder.writeLong(nonceSequence);
encoder.writeBytes(salt, 0, salt.length);
encoder.writeOptionalUUID(senderTwincode.getId());
encoder.writeEnum(2);   // Encryption version: X25519 + AES-256-GCM
encoder.writeOptionalString(keyInfo.getPublicEncryptionKey());
final byte[] auth = outputStream.toByteArray();

// 2. Encrypted payload: signing key, secret index, secret, and attributes
outputStream.reset();
encoder.writeOptionalString(senderInfo.getPublicSigningKey());
encoder.writeInt(senderInfo.getKeyIndex());
encoder.writeOptionalBytes(senderInfo.getSecretKey());
encoder.writeAttributes(attributes);
final byte[] toCrypt = outputStream.toByteArray();

// 3. Encrypt with AES-256-GCM
cipher = CryptoBox.create(CryptoBox.Kind.AES_GCM);
int status = cipher.bind(true, cipherPrivateKey, targetPublicKey, salt);
...
byte[] result = new byte[auth.length + toCrypt.length + 64];
int len = cipher.encryptAEAD(nonceSequence, toCrypt, toCrypt.length, auth, result);

CryptoBox is our native binding to the cryptographic primitives already embedded in the WebRTC library (BoringSSL).

  • bind() performs the X25519 key agreement and the HMAC-based derivation to produce a one-time AES key
  • encryptAEAD() performs AES-256-GCM with a 12-byte nonce built from the authenticated header and the nonce sequence

Here is the C++ side of these nonce generation:

// Nonce (12 bytes): first 8 bytes of the authenticated header || 32-bit nonce sequence
void CryptoBox::makeNonce(unsigned char *nonce, size_t nonceLength, uint32_t nonceSequence,
                          const unsigned char* auth)
{
  CBB cbs;
  CBB_init_fixed(&cbs, nonce, nonceLength);
  CBB_add_bytes(&cbs, auth, nonceLength - 4);
  CBB_add_u32(&cbs, nonceSequence);
}

And the AES key generation and AEAD encryption, with the error handling removed (see C++ method CryptoBox::encryptAEAD ):

// Build key with HMAC(sharedKey, { salt || pubKeyA || pubKeyB })
// (pubKeyA is the sender's key, pubKeyB the receiver's key)
HMAC_Init_ex(&ctx, sharedKey, sharedKeyLength, EVP_sha256(), NULL);
HMAC_Update(&ctx, salt, saltLength);
HMAC_Update(&ctx, pubKeyA, pubKeyALength);
HMAC_Update(&ctx, pubKeyB, pubKeyBLength);
HMAC_Final(&ctx, key, &keyLength);          // 32 bytes: the AES-256 key

aead_ = EVP_AEAD_CTX_new(EVP_aead_aes_256_gcm(), key, keyLength, EVP_AEAD_DEFAULT_TAG_LENGTH);

// Seal: the auth header is copied in clear, the payload is encrypted and the tag is appended
memcpy(buffer, auth, authLength);
EVP_AEAD_CTX_seal(aead_, &buffer[authLength], &outLength, maxLength - authLength,
                  nonce, sizeof(nonce), data, len, auth, authLength);

The nonce uniqueness comes from the sequence number: the 8 header bytes only make the nonce specific to the message. For a secure invocation, every message has its own salt and therefore its own key, so the sequence cannot repeat under a key.

3. Secret Exchange and Renewal Through the Data Channel

A secret is not kept forever. When a P2P session starts with a secret that is older than 30 days, the session is flagged as needing a renewal. Once the data channel is open, which means that both devices have already decrypted each other's SDP and that the DTLS channel is established, the device generates its next secret and sends it in a SignatureInfoIQ through the data channel:

final SdpEncryptionStatus sdpEncryptionStatus
  = mPeerConnectionService.getSdpEncryptionStatus(peerConnectionId);
if (sdpEncryptionStatus != SdpEncryptionStatus.ENCRYPTED) {
    SignatureInfoIQ iq = mTwinlifeImpl.getCryptoService()
        .getSignatureInfoIQ(twincodeOutbound, peerTwincodeOutbound,
            sdpEncryptionStatus == SdpEncryptionStatus.ENCRYPTED_NEED_RENEW);
    if (iq == null) {
        return false;
    }
    connection.sendPacket(StatType.IQ_SET_SIGNATURE_INFO, iq);
    return true;
}

The condition covers two cases. When the status is ENCRYPTED_NEED_RENEW, the IQ carries a renewed secret. When the status is NONE, the session was established with clear SDPs because the relation has no secrets yet: this happens for contacts created before SDP encryption was deployed. The same IQ then sends the public keys and the first secret, and the next P2P session with that contact is encrypted.

The new secret never travels through the signaling server: it is protected by DTLS between the two devices.

Each direction has its own secret, and each secret has two slots in the database (secret1 and secret2), so a relation holds up to four secret values. The new secret goes to the free slot and is only marked usable once the peer has acknowledged it. This way, a P2P session that starts during the renewal can still be decrypted with the previous secret. The slot index used for an SDP travels in clear with the encrypted SDP so that the receiver picks the right secret.

If a device lost its secrets, for example after a restore on a new phone, the peers run the same exchange through secure invocations, encrypted with the twincode keys as described above. A restore only brings back the twincode key pairs, never the relation secrets, so a restored device always starts with fresh secrets and fresh nonce counters.

4. Preparing a P2P Session

When a P2P session is created, the device loads its secret and the peer's secrets for the relation in CryptoServiceProvider.prepareSession(). For an outgoing session, we only use a secret that we know the peer has acknowledged:

// Get the secret that we are sure the peer has.
if ((flags & CryptoService.USE_SECRET1) != 0) {
    keyIndex = 1;
    secret = secret1;
} else if ((flags & CryptoService.USE_SECRET2) != 0) {
    keyIndex = 2;
    secret = secret2;
} else if (flags != 0 && strict) {
    // The peer does not know our secret and we are in strict mode (P2P-OUT).
    return null;
} else {
    secret = secret1;
    keyIndex = 1;
}

The same method reserves a block of 100 nonce sequences in the database for the session. Because the reservation is persisted before use, a nonce is never reused with the same secret, even if the application is killed in the middle of a call. The nonce is incremented each time a new SDP packet is encrypted and if we have sent more than 100 SDP packets in the same WebRTC session, a new reservation of 100 nonce sequences is made again. Since a secret is only used for encryption by the device that generated it, the nonce counter has a single writer and two devices can never collide on the same nonce.

5. SDP Encryption

The SDP is first compressed with zlib when it is large enough for the compression to pay off, then encrypted with AES-256-GCM. The P2P session id and nonce sequence remain in cleartext but are authenticated by the AES-GCM tag, preventing any modification. This is the encrypt() method of SessionSecretKeyPair, without its logs (see full Java encrypt() and the Objective-C encryptWithSdp: ):

@Override
@NonNull
public Pair<ErrorCode, Sdp> encrypt(@NonNull Sdp sdp) {

    final long nonceSequence = allocateNonce();
    if (nonceSequence == 0) {
        return new Pair<>(ErrorCode.NO_PRIVATE_KEY, null);
    }
    
    CryptoBox cipher = null;
    try {
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final BinaryEncoder encoder = new BinaryCompactEncoder(outputStream);
        
        // 1. Authenticated header (not encrypted, but protected by AES-GCM tag)
        //    - P2P session id: binds SDP to a specific session
        //    - nonce sequence: ensures uniqueness
        encoder.writeUUID(getSessionId());
        encoder.writeLong(nonceSequence);
        
        final byte[] auth = outputStream.toByteArray();
        
        // 2. Encrypt the SDP with AES-256-GCM
        cipher = CryptoBox.create(CryptoBox.Kind.AES_GCM);
        int status = cipher.bind(mSecret);
        if (status != 1) {
            return new Pair<>(ErrorCode.INVALID_PRIVATE_KEY, null);
        }
        byte[] result = new byte[auth.length + sdp.getLength() + 64];
        int len = cipher.encryptAEAD(nonceSequence, sdp.getData(), sdp.getLength(), auth, result);
        if (len <= 0) {
            return new Pair<>(ErrorCode.ENCRYPT_ERROR, null);
        }
        return new Pair<>(ErrorCode.SUCCESS, new Sdp(result, len, sdp.isCompressed(), getKeyIndex()));
        
    } catch (Exception exception) {
        return new Pair<>(ErrorCode.LIBRARY_ERROR, null);
        
    } finally {
        if (cipher != null) {
            cipher.dispose();
        }
    }
}
  • Algorithm: AES-256-GCM provides both confidentiality and integrity.
  • Nonce: 12 bytes made of the first 8 bytes of the authenticated header (the start of the P2P session id) followed by the 32-bit nonce sequence. The sequence is unique for a given secret, and the secret lives at most 30 days, so the 32-bit range is never exhausted.
  • Authenticated data: The P2P session id binds the encrypted SDP to one session.

6. Signaling

The encrypted SDP is sent to the signaling server in a binary SessionInitiateIQ (or SessionAcceptIQ and TransportInfoIQ for the answer and the ICE candidates). The server sees the routing information it needs and an opaque sdp blob:

SessionInitiateIQ
  from, to    routing identifiers
  sessionId   P2P session id
  offer       audio/video/data flags, compression flag, and secret index in bits 8-15
  priority, expirationDeadline, ...
  sdp         +----------------------------+-----------------------------+
              | Authenticated Header       | Encrypted Payload           |
              |----------------------------|-----------------------------|
              | sessionId | nonceSequence  | AES-256-GCM(compressed SDP) |
              | (clear, protected by tag)  | + authentication tag        |
              +----------------------------+-----------------------------+

Key Point: The signaling server cannot decrypt or modify the SDP. It simply forwards it to the recipient. The ICE candidates sent later in TransportInfoIQ are encrypted the same way.

7. SDP Decryption

The recipient checks that the SDP belongs to its P2P session, selects the sender's secret from the index, and decrypts. Any modification of the clear header or of the ciphertext makes the authentication tag fail (see full Java decrypt() and the Objective-C decryptWithSdp: ):

@NonNull
public Pair<ErrorCode, Sdp> decrypt(@NonNull Sdp sdp) {

    if (!sdp.isEncrypted()) {
        return new Pair<>(ErrorCode.NO_PUBLIC_KEY, sdp);
    }
    
    CryptoBox cipher = null;
    try {
        final byte[] encrypted = sdp.getData();
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(encrypted);
        final BinaryDecoder decoder = new BinaryCompactDecoder(inputStream);
        
        // 1. Extract and verify authenticated header
        //    - P2P sessionId: must match our session
        //    - nonce sequence: used for decryption
        final UUID peerSessionId = decoder.readUUID();
        if (!peerSessionId.equals(getSessionId())) {
            return new Pair<>(ErrorCode.BAD_SIGNATURE, null);
        }
        final long nonceSequence = decoder.readLong();
        
        // 2. Decrypt with AES-256-GCM
        final int authLength = encrypted.length - inputStream.available();
        cipher = CryptoBox.create(CryptoBox.Kind.AES_GCM);
        final byte[] key = getSecret(sdp.getKeyIndex());
        if (key == null) {
            return new Pair<>(ErrorCode.NO_SECRET_KEY, null);
        }
        
        int status = cipher.bind(key);
        if (status != 1) {
            return new Pair<>(ErrorCode.DECRYPT_ERROR, null);
        }
        
        final byte[] data = new byte[encrypted.length];
        int len = cipher.decryptAEAD(nonceSequence, encrypted, authLength, data);
        if (len <= 0 || len > data.length) {
            return new Pair<>(ErrorCode.DECRYPT_ERROR, null);
        }
        
        return new Pair<>(ErrorCode.SUCCESS, new Sdp(data, len, sdp.isCompressed(), 0));
        
    } catch (SerializerException serializerException) {
        return new Pair<>(ErrorCode.BAD_ENCRYPTION_FORMAT, null);
        
    } catch (Exception exception) {
        return new Pair<>(ErrorCode.LIBRARY_ERROR, null);
        
    } finally {
        if (cipher != null) {
            cipher.dispose();
        }
    }
}

8. Authentication Without Signing Each SDP

We do not sign each SDP. Only the two devices of the relation know the secrets, so a valid AES-GCM tag already proves that the SDP comes from the peer and was not modified. Signatures are used where they matter: the twincode public keys are signed when they are published, and the invocations that carry the secrets identify the sender's signing key.

The remaining question is whether the public key we received at contact creation really belongs to our contact. Users can answer this by certifying the contact, either by scanning each other's QR code or during a video call. Once certified, the contact is marked as trusted in the application. Certification is not required for SDP encryption—it simply prevents a MITM attack during the initial invitation exchange.

Why This Works for Twinme and Skred

  1. Confidentiality

    Only the intended peer can decrypt the SDP. Even if the signaling server is compromised, the SDP remains secure.

  1. Integrity

    AES-GCM authentication ensures the SDP hasn’t been tampered with in transit, and the authenticated session id prevents reusing an SDP in another session.

  1. Limited Exposure

    Secrets are renewed every 30 days through the data channel, out of reach of the signaling server. A leaked secret only exposes the SDPs encrypted with it, and never the media or the messages, which are protected by DTLS keys negotiated for each session.

  1. Performance
    • Latency: A key agreement happens only when a secret is exchanged. Each SDP costs one AES-GCM operation on a few kilobytes, which is negligible next to the network round trips.

    • Storage: The secrets and nonce sequences are kept in the SQLCipher database of the application.

  1. Compatibility
    • No WebRTC Modifications: Works with standard WebRTC implementations. The encryption/decryption happens before the SDP is passed to the WebRTC stack.

    • No Silent Downgrade: When the two twincodes of a relation support encryption, a P2P session cannot start with a clear SDP: a missing secret is reported as an error and an unencrypted SDP is rejected.

Security Considerations

Key Management

  • Per-relation secrets: One secret per direction and per relation.
  • Two slots: Renewal never breaks a session that is being established.
  • Local storage: Private keys and secrets never leave the device except the secret sent to the peer.
  • Secret rotation: Secrets expire after 30 days to limit exposure if a device is compromised, balancing security and operational overhead.
  • Restore: A backup restore brings back the twincode key pairs only. Relation secrets and their nonce counters are re-created, so a restored database never reuses a nonce with an old secret. The secure invocations themselves use a fresh random salt per message, so their one-time keys never repeat either.
  • Forward secrecy limitation: Past SDPs can be decrypted if a secret is compromised, and a compromised long-term X25519 key exposes the past secure invocations and the secrets they carried. Future versions may use ephemeral keys for stronger forward secrecy.

Threat Mitigation

ThreatMitigation
Fingerprint substitutionThe SDP is authenticated with a secret the server does not have.
Replay in another sessionThe P2P session id is authenticated with the SDP.
Nonce reuseNonce sequences are reserved in the database before use; each secret has a single encrypting device.
Signaling Server CompromiseEnd-to-end encryption ensures the server cannot read SDPs.
Key substitution (MITM)Secrets travel encrypted for the peer's key; users can certify the relation.
Downgrade to clear SDPA clear SDP is rejected for an encrypted relation.
Device theftSecrets are stored in a SQLCipher-encrypted database; app-level protections apply.
Server-side logsNo SDP plaintext is logged. The applications only count clear and encrypted SDPs and report decryption failures without any key material.

Conclusion: Security Without Compromise

By encrypting SDPs end-to-end with secrets that never transit in clear through our servers, we ensure that:

  • Signaling data is confidential—even from our own servers.
  • Connections are tamper-proof—an altered SDP is rejected.
  • Performance remains optimal—with minimal overhead.

This approach currently protects more than 400K audio/video calls per day and more than 1M WebRTC data-channel connections per day.

If you're implementing WebRTC, consider these key takeaways:

  • Encrypt SDPs before they reach the signaling server
  • Use per-relation secrets exchanged via trusted channels
  • Rotate keys periodically to limit exposure
  • Never trust the server with plaintext signaling data

Whether you're building a messaging application, an audio/video call system, or a conference platform, securing WebRTC signaling is a critical step—and now, you know how we do it.

Add a comment

(How to get a Mini-code ?)