Author|Jinxue

Review|Taiyi

DTLS (Datagram Transport Layer Security) is a customized and improved TLS protocol for UDP based on the reality that data packets may be lost or reordered in the UDP scenario. The use of DTLS in WebRTC includes two parts: negotiation and management of [SRTP]() keys and providing encrypted channels for [DataChannel]().

This article analyzes the process of WebRTC using DTLS for SRTP key negotiation in combination with actual data packets. And summarize the problems encountered in using DTLS in actual projects.

Introduction to DTLS protocol

Before analyzing the application of DTLS in WebRTC, first introduce the basic principles of the DTLS protocol. The DTLS protocol consists of two layers: Record protocol and Handshake protocol

  1. Record protocol: Use a symmetric key to encrypt the transmitted data, and use HMAC to check the integrity of the data, which realizes the safe transmission of data.
  2. Handshake protocol: Use an asymmetric encryption algorithm to complete the negotiation of the symmetric key used by the Record protocol.

HandShake

The TLS handshake protocol process is as follows, refer to RFC5246

The DTLS handshake protocol process is as follows, refer to RFC6347


The handshake process of TLS and DTLS is basically the same, the differences and special instructions are as follows:

  • HelloVerifyRequest in DTLS is a message added to prevent DoS attacks.
  • TLS did not send CertificateRequest , this is not necessary, it is reverse authentication, that is, the server authenticates the client.
  • DTLS's RecordLayer added SequenceNumber and Epoch, and ClientHello added Cookie, and Handshake added Fragment information (to prevent exceeding UDP MTU), all to adapt to UDP packet loss and easy to be attacked. Reference RFC 6347
  • The final Alert of DTLS is to decrypt the Encrypted Alert message of the client and directly respond to the client. In fact, the server should respond to the encrypted message. Here, our server responds in plaintext to parse the alert packet encrypted by the client.

The RecordLayer protocol is a protocol related to DTLS transmission. Above UDP is RecordLayer, and above RecordLayer is Handshake or ChangeCipherSpec or ApplicationData. RecordLayer protocol definition refers to RFC4347 , there are actually three RecordLayer packages:

  • DTLSPlaintext , the RecordLayer of DTLS plaintext.
  • DTLSCompressed , compressed data, generally not used.
  • DTLSCiphertext , encrypted data, this is the case after ChangeCipherSpec.

There is no clear field indicating what kind of message it is, but it can be judged based on the context and content. For example, ChangeCipherSpec is a passable type, and it must be a Plaintext. Except for Finished other handshake, it is usually Plaintext.

SRTP key agreement

Role negotiation

In the DTLS protocol, there are Client and Server between the two communicating parties. The identity of DTLS negotiation in WebRTC is described SDP The description is as follows, refer to the DTLS parameter in SDP-Anatomy

a=setup:active

setup attributes are in RFC4145 ,

setup:active, as a client, initiate negotiation

setup:passive, as a sever, waiting to initiate negotiation

setup: actpass, as a client, initiates negotiation actively. As a server, waiting to initiate negotiation.

Algorithm negotiation-Hello message

ClienHello and ServerHello negotiate DTLS Version, CipherSuites, Random, and Extensions.

  • Version : Client gives the highest version that it can support or to use, such as DTLS1.2. After the server receives this information, it responds according to the version it can support or to use, such as DTLS1.0. In the end, the negotiated version, which is DTLS1.0, shall prevail.
  • CipherSuites : Client gives CipherSuites that it can support. After receiving it, Server chooses a response that it can support, such as TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (0xc014). The cipher suite determines the type of certificate, key generation algorithm, digest algorithm, etc.
  • Random : The random number of both parties involved in the generation of MasterSecret. MasterSecret will be used to generate the master key and export the SRTP key. See [Export SRTP key] for details
  • Extensions : The client gives the extended protocol it wants to use, and the server can respond to what it supports. For example, although the Client has set the SessionTicket TLS extension, the Server does not respond, so this extension will not be used in the end.

Cipher Suite

In the Hello message, the encrypted socket uses the registered name in IANA The IANA name is composed of descriptions of Protocol, Key Exchange Algorithm, Authentication Algorithm, Encryption Algorithm, and Hash Algorithm. For example, the meaning of TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 is as follows:

  • Protocol: Transport Layer Security (TLS)
  • Key Exchange: Elliptic Curve Diffie-Hellman Ephemeral (ECDHE)
  • Authentication: Rivest Shamir Adleman algorithm (RSA)
  • Encryption: Advanced Encryption Standard with 128bit key in Galois/Counter mode (AES 128 GCM)
  • Hash: Secure Hash Algorithm 256 (SHA256)
The encrypted socket can be found ciphersuite.info While finding the IANA name, you can also find the name in OpenSSL. The name of TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 in OpenSSL is ECDHE-RSA-AES128-GCM-SHA256
Note: For authentication, KeyExchange, Encryption, MAC (Message Authentication Code) message digests, etc., please refer to RSA key agreement .

Extension

The extension protocol of DTLS is specified in the Extensions information of ClientHello and ServerHello. For all TLS extensions, refer to 1609b519c8253f TLS Extensions . Here are a few extensions used by WebRTC:

  • signature_algorithms , an extension of DTLS1.2, specifies the Hash and Signature algorithms used, refer to RFC5246 7.4.1.4.1. Signature Algorithms . DTLS1.0, RSA uses the md5sha1 digest algorithm, and DSA uses the sha1 digest algorithm.

  • extended_master_secret , to extend the generation method of MasterSecret, refer to RFC7627 . In KeyExchange, some constants will be added to generate MasterSecret. TLS defines an extension method. If this extension is used, the method of DTLS and TLS will be somewhat different.
  • renegotiation_info , reference

In addition to these extended protocols, there are also related to SRTP key derivation:

RFC5705: Keying Material Exporters for Transport Layer Security (TLS), how DTLS exports Key from MasterSecret, such as SRTP Key.
RFC5764: DTLS Extension to Establish Keys for the SRTP, a detailed specification of the use_srtp extension of DTLS, including ClientHello extension definition, Profile definition, and Key calculation.

Authentication-Certificate


Digital certificates are issued by some recognized and credible certificate authorities and are not easy to forge. The digital certificate can be used for the receiver to verify the identity of the peer. When the receiver receives a certificate from the peer, it will check the digital signature of the signing authority. Generally speaking, the receiver will pre-install many commonly used signatures. The certificate of the organization (containing the public key), the signature can be verified using the pre-public key.

After the server negotiates the key exchange method through the Hello message, it sends the server certificate to the client for the client to verify the identity of the server. The certificate sent by the server must be suitable for the encrypted socket used by the negotiated KeyExchange and the Hash/Signature algorithm pair described in the Hello message extension.

In WebRTC, the communicating parties will usually not be able to obtain an identity verification certificate signed by a well-known root certification authority (CA), and a self-signed certificate is usually the only option. RFC4572 defines a mechanism by SDP , called "certificate fingerprint". Under the premise of ensuring SDP secure transmission, if the fingerprint of the provided certificate matches SDP You can trust the self-signed certificate. In actual application scenarios, SDP is exchanged in a secure signaling channel (https), and the security and integrity of SDP can be achieved. In this way, in the DTLS negotiation process, the fingerprint of the certificate can be used to complete the identity verification of the communicating parties. The description of certificate fingerprint in SDP is as follows, refer to DTLS parameter in SDP-Anatomy

a=fingerprint:sha-256 49:66:12:17:0D:1C:91:AE:57:4C:C6:36:DD:D5:97:D2:7D:62:C9:9A:7F:B9:A3:F4:70:03:E7:43:91:73:23:5E

Key Exchange-KeyExchange

ServerKeyExchange is used to send the public key used by the server to the client. Divided into two situations:

  1. RSA algorithm: If the server uses the RSA algorithm, this message may not be sent, because the public key used by the RSA algorithm has been described in the Certificate.
  2. DH algorithm calculates the shared key based on the other party’s public key and own private key. Because both Client and Server only know their own private key and the other's public key; and their private keys are different. According to special mathematical characteristics, they can calculate the same shared key. For how the DH algorithm calculates the shared key, refer to DH algorithm .

ClientKeyExchange is used to send the public key used by the client to the server.

  1. RSA algorithm: If the RSA algorithm used for key negotiation, send the server side RSA public key, encrypt the premaster secret and send it to the server side.
  2. DH algorithm: If the DH algorithm used for key negotiation is not described in the certificate, send the DH algorithm public key used by the client to the server to calculate the shared key.

The result of KeyExchange is that the Client and Server obtain the RSA Key, or calculate the shared key through the DH algorithm. For details, please refer to the process of [Export SRTP Key]

Certificate Verify-CertificateVerify

Use the Hash/Signature algorithm described in ClientRequest to sign the received and sent HandShake message and send it to a Server. The server side verifies the signature.

Encryption verification-Finished

When the server and the client complete the exchange of the symmetric key, ChangeCipherSpec notify the opposite end to enter the encryption phase through 0609b519c82d1f, and the epoch is incremented by 1.

Then the client uses the exchanged key to encrypt "client finished" and uses the Finished message to send it to the server. Server uses the exchanged key to encrypt "server finished" and send it to the client. Once the finished message is verified, normal communication can be started.

Export SRTP key

The DTLS process is described above. The following describes the SRTP key derivation steps in detail by combining the actual data given in the above example.

Encryption algorithm after negotiation

Encryption suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xc02f)
The elliptic curve algorithm is: secp256r1, and the point compression algorithm of the elliptic curve is uncompressed.
The basic knowledge of the elliptic curve algorithm is introduced in the ECC elliptic curve encryption algorithm-ECDH, ECDHE, ECDSA . From the document, we can know that the elliptic curve encryption algorithm has the following parameters:

  • Prime number p, used to determine the range of a finite field
  • The a, b parameters in the elliptic curve equation
  • Base point G used to generate subgroups
  • Subgroup order n
  • The auxiliary factor of the subgroup h

Defined as six-tuple (p, a, b, G, n, h)

The corresponding parameters of SECG-SEC2 2.4.2 Recommended Parameters secp256r1 1609b519c82eb5 as follows:

secp256r1使用的参数如下:
使用的素数p:
p=FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF
=2224(232−1)+2192+296−1
椭圆曲线E:y^2=x^3+ax+b的参数定义如下:
a=FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC
b=5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B
基点G的非压缩格式:
G=046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5
有限域的阶n:
n=FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
辅助因子h:
h=01

Exchange elliptic curve algorithm public key through KeyExchange

ECDH Server Parameter

Pubkey:04b0ce3c5f2c4a9fbe7c2257c1328438f3378f74e9f528b6e27a00b44eee4c19e5e6b2cb6cab09f796bcf8c05102b2a4bcdc753d91cc4f431f558c845a1ba6f1ce

Recorded as Spk

ECDH Client Paramter

PubKey: 0454e8fbef1503109d619c39be0ccaf89efa3c3962300476465cbc66b15152cd8a900c45d506420f0123e65d8fbb70cb60b497893f81c5c2a0ef2f4bc2da996d9e

Recorded as Cpk

Calculate the shared secret S (pre-master-secret) according to the ECDHE algorithm

Assuming that the elliptic curve private key used by the server is Ds and the Dc used by the client, the calculation of the shared key is as follows, refer to ECC elliptic curve encryption algorithm-ECDH, ECDHE, ECDSA

S = Ds Cpk = Dc Spk

This shared key S is what we see in the RFC document pre-master-secret

Calculate the master secret

The calculation master secret is as follows, please refer to Computing the Master Secret

    master_secret = PRF(pre_master_secret, "master secret", ClientHello.random + ServerHello.random)[0..47];

The calculated master_secret is 48 Bytes, of which ClientHello.random and ServerHello.random are given in the Hello message. PRF is a pseudorandom function, which is given in the negotiated encryption suite.

Use master_secrete to export SRTP encryption parameter byte sequence

Use RFC5705 4. Exporter Definition give the calculation method, use the parameters master_secret , client_random , server_random calculate the byte sequence:

key_block = PRF(master_secret, "EXTRACTOR-dtls_srtp", client_random + server_random)[length]

The required byte sequence length is described DTLS-SRTP 4.2. Key Derivation

2 * (SRTPSecurityParams.master_key_len + SRTPSecurityParams.master_salt_len) bytes of data

The values of master_key_len and master_salt_len are defined in the profile described by user_srtp The profile used in our example is SRTP_AES128_CM_HMAC_SHA1_80 , and the corresponding profile configuration is:

SRTP_AES128_CM_HMAC_SHA1_80
        cipher: AES_128_CM
        cipher_key_length: 128
        cipher_salt_length: 112
        maximum_lifetime: 2^31
        auth_function: HMAC-SHA1
        auth_key_length: 160
        auth_tag_length: 80

That is, we need the (128/8+112/8)*2 = 60 bytes byte sequence.

Export SRTP key

Calculate the SRTP encryption parameter byte sequence, in DTLS-SRTP 4.2. Key Derivation describes the meaning of the byte sequence:

client_write_SRTP_master_key[SRTPSecurityParams.master_key_len]; // 128 bits
server_write_SRTP_master_key[SRTPSecurityParams.master_key_len]; // 128 bits
client_write_SRTP_master_salt[SRTPSecurityParams.master_salt_len]; // 112 bits
server_write_SRTP_master_salt[SRTPSecurityParams.master_salt_len]; // 112 bits

So far we have got the SRTP encryption parameters used by Client and Server: master_key and master_salt.

DTLS timeout retransmission

DTLS is based on UDP, and packet loss will inevitably occur, requiring retransmission. If it is not handled properly, it will cause the entire communication parties to fail to establish a session and the call will fail. RFC6347 4.2.4 gives the timeout and retransmission mechanism.
When dealing with retransmissions, the following points need to be noted:

  1. In the DTLS protocol, in order to solve the problem of packet loss and retransmission, message_seq is added. When sending a DTLS retransmission message, you must update message_seq , so that the peer will recognize the packet as a retransmission packet and respond Correct message. Otherwise, these packets will be silently discarded and no response will be made.
  2. When the server receives the FINISHED message from the client and sends the FINISHED message to the client, it updates the server status to the completion of the negotiation and starts sending SRTP data. At this time, the FINISHED message sent to the client shows packet loss. The client discards the SRTP data after receiving it. At the same time, send a FINISHED message to the server again, and the server must respond correctly. Otherwise, it will cause the illusion that the DTLS negotiation is completed and the call will fail.
  3. Using openssl versions before 1.1.1, the DTLS timeout retransmission time cannot be set, and the timeout retransmission mechanism is unavailable, and everyone starts to use boringssl. The beginning version of openssl 1.1.1 already supports setting DTLS timeout retransmission, achieving the same effect as boringssl. Reference DTLS_set_timer_cb

DTLS function of OpenSSL

DTLS is a huge protocol system, which includes various encryption, signature, certificate, compression and other algorithms. Most projects are based on the DTLS function implemented by OpenSSL or BoringSSL. The DTLS function of OpenSSL is used in the actual project, and the interfaces related to the negotiation are summarized as follows.

  1. X509_digest , calculate the certificate fingerprint, used in the fingerprint attribute in SDP negotiation.
  2. SSL_CTX_set_cipher_list , set the cipher suite used, and set the algorithm description to affect the cipher list in the Hello message.
  3. SSL_CTX_set1_sigalgs_list Set the signature algorithm. By setting the description of the signature algorithm, the signature_algorithms extension in the hello message is affected. signature_algorithms Hello message, KeyExchange , CerficateVerify message for DTLS. signature_algorithms set incorrectly, an internal error will occur, which makes it difficult to locate the problem.
  4. SSL_CTX_set_verify Set whether to verify the peer certificate. Since the self-signed certificate is used in most data situations in RTC, the verification of the certificate and the verified identity are required.
  5. SSL_CTX_set_tlsext_use_srtp Set srtp extension. The profile in the srtp extension affects the negotiation and extraction of the key used in srtp encryption.
  6. SSL_set_options use SSL_OP_NO_QUERY_MTU and [SSL_set_mtu] to set the size of the fragment. By default, OpenSSL uses a smaller fragment. Through the above two interfaces, set up a fragment suitable for the network situation.
  7. DTLS_set_timer_cb , set the callback for timeout retransmission, and the callback sets a more reasonable timeout retransmission time.

In the open source project SRS , the basic protocol of WebRTC has been supported. Students who are interested in the DTLS protocol can quickly build a native environment based on SRS, and further deepen their understanding of DTLS through debugging.

to sum up

This article illustrates the application of DTLS in WebRTC through the negotiation process of SRTP keys in WebRTC. There is a lot of knowledge about each encryption algorithm designed by the DTLS protocol, coupled with the expansion of TLS messages in various application scenarios, it is inevitable that there are areas that are not understood and recognized, and further exploration is needed.

references

  1. TLS 1.2
  2. DTLS 1.2
  3. TLS Session Hash Extension
  4. TCP-Based Media Transport in the Session Description Protocol
  5. TLS Extension
  6. SRTP Extension for DTLS
  7. OpenSSL Man
  8. ECC Elliptic Curve Encryption Algorithm-Introduction
  9. ECC Elliptic Curve Encryption Algorithm-Finite Field and Discrete Logarithm
  10. ECC Elliptic Curve Encryption Algorithm-ECDH, ECDHE and ECDSA
"Video Cloud Technology" Your most noteworthy audio and video technology public account, pushes practical technical articles from the front line of Alibaba Cloud every week, and exchanges and exchanges with first-class engineers in the audio and video field. The official account backstage reply [Technology] You can join the Alibaba Cloud Video Cloud Technology Exchange Group, discuss audio and video technologies with the author, and get more industry latest information.

CloudImagine
222 声望1.5k 粉丝