Author | enter school

Review | Tai one

Datagram Transport Layer Security (DTLS) This protocol is customized and improved for UDP when packets may be lost or reordered. The use of DTLS in WebRTC consists of two parts: negotiating and managing SRTP keys and providing encryption channels for DataChannel.

This paper analyzes the process of SRTP key negotiation using DTLS in WebRTC based on actual data packets. The problems encountered in using DTLS in actual projects are summarized.

DTLS Protocol Overview

Before analyzing the application of DTLS in WebRTC, the basic principle of DTLS protocol is introduced. DTLS protocol consists of two layers: Record protocol and Handshake protocol

  1. Record protocol: use symmetric key to encrypt the transmitted data, and use HMAC to verify the integrity of the data, to achieve the safe transmission of data.
  2. Handshake protocol: Use asymmetric encryption algorithm to complete the negotiation of symmetric key for Record protocol.

HandShake

The TLS handshake protocol flow is as follows. For details, see RFC5246

The DTLS handshake protocol flow is as follows. For details, see RFC6347

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

  • HelloVerifyRequest in DTLS is a message added to prevent DoS attacks.
  • TLS does not send CertificateRequest, which is not required. It is reverse authentication, that is, the server validates the client.
  • SequenceNumber and Epoch are added to RecordLayer of DTLS, cookies are added to ClientHello, and Fragments are added to Handshake (to prevent MTU exceeding UDP). Are to adapt to UDP packet loss and easy to be attacked to do improvements. Refer to RFC 6347
  • The last 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 to the plaintext to resolve what the Alert packet Encrypted by the client is.

The RecordLayer protocol is the protocol associated with DTLS transmission. RecordLayer is Handshake or ChangeCipherSpec or ApplicationData over UDP. The RecordLayer protocol definition refers to RFC4347. There are actually three RecordLayer packages:

  • DTLSPlaintextDTLS Indicates the RecordLayer of the plaintext.
  • DTLSCompressed, compressed data, generally not.
  • DTLSCiphertextEncrypted data, after ChangeCipherSpec.

There is no specific field for what kind of message it is, but you can tell by context and content. For example, if a ChangeCipherSpec is available through type, it must be a Plaintext. Except for Finished handshakes, they are generally Plaintext.

SRTP key negotiation

Role of negotiation

In THE DTLS protocol, the two sides of communication are divided into Client and Server. The identity negotiated by DTLS in WebRTC is described in SDP. The description is as follows. Refer to parameter DTLS in SDP-Anatomy

a=setup:active
Copy the code

Setup property in RFC4145,

Setup :active: initiates negotiation as a client

Setup :passive, as sever, waiting for negotiation to start

Setup :actpass, as a client, initiates negotiation. As the server, waiting to initiate a negotiation.

Algorithm negotiation – Hello message

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

  • Version: Indicates the highest version that the Client can support or use, such as DTLS1.2. The Server receives this message and responds based on which version it supports or wants to use, such as DTLS1.0. The negotiated version is DTLS1.0.
  • CipherSuites: The Client provides CipherSuites supported by the Client. After receiving the CipherSuites, the Server selects one that it supports, for example, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (0xC014). The encryption suite determines the certificate type, key generation algorithm, digest algorithm, and so on.
  • Random: Random number of both parties involved in generating MasterSecret. MasterSecret is used to generate the master key and export the SRTP key. For details, see [Exporting SRTP Keys]
  • Extensions: The Client indicates the extended protocol to be used, and the Server responds with the supported one. For example, the Client sets the SessionTicket TLS extension, but the Server does not respond. Therefore, the extension is not used.

Cipher Suite

Encrypting the socket in the Hello message uses the name registered in IANA. The IANA name consists of descriptions of Protocol, Key Exchange Algorithm, Authentication Algorithm, Encryption Algorithm, and Hash Algorithm. For example, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 has the following meanings:

  • 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)

Encrypted sockets are available at ciphersuite.info. The IANA name can also be found in OpenSSL. Note: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 in OpenSSL is named ecdhe-rSA-aes128-GMC-sha256. For details about Authentication, KeyExchange, Encryption, and Message Authentication Code (MAC) Message digest, see RSA key negotiation.

Extension

The extension protocol for DTLS is specified in the Extensions information for ClientHello and ServerHello. All TLS Extensions refer to TLS Extensions. Here are some of the extensions WebRTC uses:

  • use_srtp: DTLS After the handshake is complete, data is transmitted using SRTP and DTLS generates the SRTP key.RFC5764. The extended information in ClientHello is definedRFC5764 4.1.2. SRTP Protection Profiles 和 srtp_mki.

  • supported_groups, formerly known as Elliptic_curves, describes the supported ECC encryption algorithms, seeRFC8422 5.1.1.Supported Elliptic Curves ExtensionSecp256r1 is commonly used.

  • signature_algorithms, DTLS1.2 extension that specifies the Hash and Signature algorithms to use, seeRFC5246 7.4.1.4.1. Signature Algorithms. DTLS1.0, RSA uses MD5SHA1 digest algorithm, DSA uses SHA1 digest algorithm.

  • extended_master_secret, expand MasterSecret generation mode, refer toRFC7627. In KeyExchange, constants are added to generate MasterSecret. TLS defines an extension. If you use this extension, DTLS behaves a little differently than TLS.
  • renegotiation_infoReference,RFC5746

In addition to these extended protocols, SRTP key export is related to:

RFC5705: Keying Material Exporters for Transport Layer Security (TLS), DTLS how to export keys from MasterSecret, such as SRTP keys. RFC5764: DTLS Extension to Establish Keys for the SRTP, DTLS Extension usE_SRTP, including ClientHello Extension definition, Profile definition, Key calculation.

Authentication – Certificate

Digital certificates are issued by recognized and trusted certification authorities and are not easily forged. Digital certificates can be used for the receiver to verify the identity, the recipient receives a of the certificate, will examine the signature authority digital signature, in general, the receiver will be pre-installed in advance the signature of the many common agency certificate (containing the public key), using the public key can be validated for signature in advance.

The Server negotiates the key exchange method through the Hello message and sends the Server certificate to the Client for the Client to verify the Server identity. The certificate sent by the Server must be applicable to the encrypted socket used by the negotiated KeyExchange and the Hash/Signature algorithm pair described in the Hello Message extension.

In WebRTC, two communicating parties will typically not be able to obtain an authentication certificate signed by a well-known root certificate authority (CA), and self-signed certificates are usually the only option. RFC4572 defines a mechanism to add the security hash of the self-signed certificate to the SDP, called “certificate fingerprint”. If the fingerprint of the provided certificate matches that of the SDP, the self-signed certificate can be trusted to ensure secure SDP transmission. In actual application scenarios, SDP exchanges over secure signaling channels (HTTPS), and the security integrity of SDP can be achieved. In this way, the fingerprint of the certificate can be used to verify the identity of the communication parties during DTLS negotiation. The certificate fingerprint is described as follows in SDP. For details, see 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
Copy the code

KeyExchange – KeyExchange

ServerKeyExchange Sends the public key used by the Server to the Client. There are two cases:

  1. RSAAlgorithm: If the server uses the RSA algorithm, you do not need to send this message because the public key used by the RSA algorithm is described in the Certificate.
  2. DHThe algorithm calculates the shared key based on the peer’s public key and its own private key. The Client and Server only know their own private key and each other’s public key. Their private keys are different, and with special mathematical properties, they can calculate the same shared key. For details about how to calculate the shared key using the DH algorithm, seeDH algorithm.

ClientKeyExchange Sends the public key used by the Client to the Server.

  1. RSAAlgorithm: If the RSA algorithm is used for key negotiation, the RSA public key on the server is used to send the premaster secret encryption to the server.
  2. DHAlgorithm: If the DH algorithm used in key negotiation is not described in the certificate, send the public key of the DH algorithm used by the client to the Server for computing the shared key.

In KeyExchange, the Client and Server obtain the RSA Key or calculate the shared Key using the DH algorithm. For details, see the procedure of exporting SRTP Key

Certificate verification – CertificateVerify

Use the Hash/Signature algorithm described in ClientRequest to sign a Server for the received and sent HandShake messages. The Server verifies the signature.

Encryption authentication – Finished

When the Server and Client complete the exchange of symmetric keys, the peer end is notified through ChangeCipherSpec to enter the encryption phase, and the epoch is added by 1.

Then the Client uses the exchanged key to encrypt Client Finished and sends a FINISHED message to the server. The Server encrypts Server Finished and sends it to the client using exchanged keys. Once the FINISHED message is authenticated, communication is normal.

Example Export the SRTP key

The procedure of DTLS is described above. The following describes the procedure of exporting SRTP keys based on the actual data provided in the preceding example.

The negotiated encryption algorithm

Encryption suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xC02F) The algorithm for elliptic curves is secP256R1, and the point compression algorithm for elliptic curves is uncompressed. ECC elliptic curve encryption algorithm – ECDH,ECDHE,ECDSA, from the document we can know, determine the elliptic curve encryption algorithm has the following parameters:

  • The prime number P is used to determine the range of a finite field
  • A and B parameters in elliptic curve equations
  • The basis point G for generating subgroups
  • Order N of a subgroup
  • The cofactor h of the subgroup

Defined as a sextuple (P,a,b,G,n,h)

In secg-sec2 2.4.2 Recommended Parameters secp256R1, you can check the following Parameters:

Secp256r1 uses the following parameters: prime p used: P = FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF = 2224 (232-1) + 2192 + 296-1 elliptic curve E: ^ 3 ^ 2 = x + y ax + b parameters are defined as follows:  a=FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC B = 5 G ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b bp of compressed format:  G=046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB 6406837 bf51f5 limited domain of order n: n = FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551 cofactor h: h = 01Copy the code

Exchange the public key of the elliptic curve algorithm through KeyExchange

ECDH Server Parameter

Pubkey:04b0ce3c5f2c4a9fbe7c2257c1328438f3378f74e9f528b6e27a00b44eee4c19e5e6b2cb6cab09f796bcf8c05102b2a4bcdc753d91cc4f431 f558c845a1ba6f1ceCopy the code

Remember to Spk

ECDH Client Paramter

PubKey: 0454e8fbef1503109d619c39be0ccaf89efa3c3962300476465cbc66b15152cd8a900c45d506420f0123e65d8fbb70cb60b497893f81c5c2a0ef2f4b c2da996d9eCopy the code

Remember to Cpk

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

Assume that the elliptic curve private key used by the Server is Ds, and the elliptic curve private key used by the Client is Dc. Calculate the shared key according to the ECC elliptic curve encryption algorithm – ECDH,ECDHE, and ECDSA

S = Ds * Cpk = Dc * Spk

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

Calculate the master secret

Computing the Master Secret procedure is as follows

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

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

Export the SRTP encryption parameter byte sequence using master_secrete

Use RFC5705 4. Exporter Definition to calculate the byte sequence using the master_secret, client_random, and server_random parameters:

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

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

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

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 as follows:

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
Copy the code

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

Example Export the SRTP key

The SRTP encryption parameter byte sequence is calculated and the meaning of Derivation is described in DTLS-SRTP 4.2. Key:

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
Copy the code

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

DTLS timeout retransmission

DTLS is based on UDP. Packet loss is inevitable and retransmission is required. If the fault is not handled properly, the two parties cannot establish a conversation and the call fails. RFC6347 4.2.4 provides timeout and retransmission mechanisms. When handling retransmission, note the following:

  1. In the DTLS protocol, to solve the packet loss and retransmission problems, addedmessage_seq.Be sure to update those when sending DTLS retransmission messagesmessage_seq, so the peer will identify the packet as a retransmitted packet and respond to the correct message. Otherwise, the packets are silently discarded without any response.
  2. After receiving the FINISHED message from the Client, the server sends a FINISHED message to the client, changes the server status to complete, and starts to send SRTP data. Packet loss occurs in the FINISHED message sent to the client. After receiving SRTP data, the client discards it. At the same time, the FINISHED message is sent to the server again. The server must respond correctly. Otherwise, the DTLS negotiation is complete and the call fails.
  3. With OpenSSL prior to 1.1.1, the DTLS timeout retransmission time cannot be set, and the timeout retransmission mechanism is not available, so people start to use BoringSSL. Openssl 1.1.1 already supports setting DTLS timeout retransmission to achieve the same effect as BoringSSL. Reference DTLS_set_timer_cb

DTLS function of OpenSSL

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

  1. X509_digestFingerprint, which is used in SDP negotiationfingerprintProperties.
  2. SSL_CTX_set_cipher_list: specifies the cipher suite used to affect the cipher list in Hello messages by setting the algorithm description.
  3. SSL_CTX_set1_sigalgs_listExample Set the signature algorithm. You can set the description of the signature algorithm to affect the hello messagesignature_algorithmsExtension.signature_algorithmsThe DTLSHello messageKeyExchange.CerficateVerifyThe message.signature_algorithmsIf the Settings are incorrect, internal errors occur, which makes it difficult to locate problems.
  4. SSL_CTX_set_verify Specifies whether to verify the peer certificate. Since self-certification is used in most data cases in the RTC, verification of certificates and verified identities is required.
  5. SSL_CTX_set_tlsext_use_srtpSet up thesrtpExtension. Profile in SRTP extension affects key negotiation and extraction during SRTP encryption.
  6. SSL_set_optionsuseSSL_OP_NO_QUERY_MTUAnd [SSL_set_mtu] set the fragment size. By default, OpenSSL uses a small fragment. Use the preceding two interfaces to set fragments suitable for the network situation.
  7. DTLS_set_timer_cb: sets the Callback for timeout retransmission. Callback sets a more reasonable timeout retransmission time.

The open source project SRS already supports the basic protocol of WebRTC. Students who are interested in THE DTLS protocol can quickly build the local environment based on SRS and further deepen their understanding of DTLS through debugging.

conclusion

This paper explains the application of DTLS in WebRTC through the negotiation of SRTP key in WebRTC. DTLS protocol design of the various encryption algorithm knowledge, coupled with the TLS message in a variety of application scenarios, it is inevitable that there is some understanding and recognition of the place, still need to further explore.

reference

  1. The 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 algorithms – ECDH, ECDHE and ECDSA

“Video cloud technology” your most noteworthy audio and video technology public account, weekly push from Ali Cloud front-line practice technology articles, here with the audio and video field first-class engineers exchange exchange. You can join ali Cloud video cloud technology exchange group to discuss audio and video technology with the author and get more latest information in the industry.