dtlssrtptransport.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. /**
  2. * Copyright (c) 2020 Paul-Louis Ageneau
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include "dtlssrtptransport.hpp"
  19. #include "tls.hpp"
  20. #if RTC_ENABLE_MEDIA
  21. #include <cstring>
  22. #include <exception>
  23. using std::shared_ptr;
  24. using std::to_integer;
  25. using std::to_string;
  26. namespace rtc {
  27. void DtlsSrtpTransport::Init() { srtp_init(); }
  28. void DtlsSrtpTransport::Cleanup() { srtp_shutdown(); }
  29. DtlsSrtpTransport::DtlsSrtpTransport(std::shared_ptr<IceTransport> lower,
  30. shared_ptr<Certificate> certificate,
  31. verifier_callback verifierCallback,
  32. message_callback srtpRecvCallback,
  33. state_callback stateChangeCallback)
  34. : DtlsTransport(lower, certificate, std::move(verifierCallback),
  35. std::move(stateChangeCallback)),
  36. mSrtpRecvCallback(std::move(srtpRecvCallback)) { // distinct from Transport recv callback
  37. PLOG_DEBUG << "Initializing DTLS-SRTP transport";
  38. #if USE_GNUTLS
  39. PLOG_DEBUG << "Setting SRTP profile (GnuTLS)";
  40. gnutls::check(gnutls_srtp_set_profile(mSession, GNUTLS_SRTP_AES128_CM_HMAC_SHA1_80),
  41. "Failed to set SRTP profile");
  42. #else
  43. PLOG_DEBUG << "Setting SRTP profile (OpenSSL)";
  44. // returns 0 on success, 1 on error
  45. if (SSL_set_tlsext_use_srtp(mSsl, "SRTP_AES128_CM_SHA1_80"))
  46. throw std::runtime_error("Failed to set SRTP profile: " +
  47. openssl::error_string(ERR_get_error()));
  48. #endif
  49. if (srtp_err_status_t err = srtp_create(&mSrtpIn, nullptr)) {
  50. throw std::runtime_error("SRTP create failed, status=" + to_string(static_cast<int>(err)));
  51. }
  52. if (srtp_err_status_t err = srtp_create(&mSrtpOut, nullptr)) {
  53. srtp_dealloc(mSrtpIn);
  54. throw std::runtime_error("SRTP create failed, status=" + to_string(static_cast<int>(err)));
  55. }
  56. }
  57. DtlsSrtpTransport::~DtlsSrtpTransport() {
  58. stop(); // stop before deallocating
  59. srtp_dealloc(mSrtpIn);
  60. srtp_dealloc(mSrtpOut);
  61. }
  62. bool DtlsSrtpTransport::sendMedia(message_ptr message) {
  63. std::lock_guard lock(sendMutex);
  64. if (!message)
  65. return false;
  66. if (!mInitDone) {
  67. PLOG_WARNING << "SRTP media sent before keys are derived";
  68. return false;
  69. }
  70. int size = int(message->size());
  71. PLOG_VERBOSE << "Send size=" << size;
  72. // The RTP header has a minimum size of 12 bytes
  73. // An RTCP packet can have a minimum size of 8 bytes
  74. if (size < 8)
  75. throw std::runtime_error("RTP/RTCP packet too short");
  76. // srtp_protect() and srtp_protect_rtcp() assume that they can write SRTP_MAX_TRAILER_LEN (for
  77. // the authentication tag) into the location in memory immediately following the RTP packet.
  78. message->resize(size + SRTP_MAX_TRAILER_LEN);
  79. uint8_t value2 = to_integer<uint8_t>(*(message->begin() + 1)) & 0x7F;
  80. PLOG_VERBOSE << "Demultiplexing SRTCP and SRTP with RTP payload type, value="
  81. << unsigned(value2);
  82. // RFC 5761 Multiplexing RTP and RTCP 4. Distinguishable RTP and RTCP Packets
  83. // https://tools.ietf.org/html/rfc5761#section-4
  84. // It is RECOMMENDED to follow the guidelines in the RTP/AVP profile for the choice of RTP
  85. // payload type values, with the additional restriction that payload type values in the
  86. // range 64-95 MUST NOT be used. Specifically, dynamic RTP payload types SHOULD be chosen in
  87. // the range 96-127 where possible. Values below 64 MAY be used if that is insufficient
  88. // [...]
  89. if (value2 >= 64 && value2 <= 95) { // Range 64-95 (inclusive) MUST be RTCP
  90. if (srtp_err_status_t err = srtp_protect_rtcp(mSrtpOut, message->data(), &size)) {
  91. if (err == srtp_err_status_replay_fail)
  92. throw std::runtime_error("Outgoing SRTCP packet is a replay");
  93. else
  94. throw std::runtime_error("SRTCP protect error, status=" +
  95. to_string(static_cast<int>(err)));
  96. }
  97. PLOG_VERBOSE << "Protected SRTCP packet, size=" << size;
  98. } else {
  99. if (srtp_err_status_t err = srtp_protect(mSrtpOut, message->data(), &size)) {
  100. if (err == srtp_err_status_replay_fail)
  101. throw std::runtime_error("Outgoing SRTP packet is a replay");
  102. else
  103. throw std::runtime_error("SRTP protect error, status=" +
  104. to_string(static_cast<int>(err)));
  105. }
  106. PLOG_VERBOSE << "Protected SRTP packet, size=" << size;
  107. }
  108. message->resize(size);
  109. if (message->dscp == 0) { // Track might override the value
  110. // Set recommended medium-priority DSCP value
  111. // See https://tools.ietf.org/html/draft-ietf-tsvwg-rtcweb-qos-18
  112. message->dscp = 36; // AF42: Assured Forwarding class 4, medium drop probability
  113. }
  114. return Transport::outgoing(message); // bypass DTLS DSCP marking
  115. }
  116. void DtlsSrtpTransport::incoming(message_ptr message) {
  117. if (!mInitDone) {
  118. // Bypas
  119. DtlsTransport::incoming(message);
  120. return;
  121. }
  122. int size = int(message->size());
  123. if (size == 0)
  124. return;
  125. // RFC 5764 5.1.2. Reception
  126. // https://tools.ietf.org/html/rfc5764#section-5.1.2
  127. // The process for demultiplexing a packet is as follows. The receiver looks at the first byte
  128. // of the packet. [...] If the value is in between 128 and 191 (inclusive), then the packet is
  129. // RTP (or RTCP [...]). If the value is between 20 and 63 (inclusive), the packet is DTLS.
  130. uint8_t value1 = to_integer<uint8_t>(*message->begin());
  131. PLOG_VERBOSE << "Demultiplexing DTLS and SRTP/SRTCP with first byte, value="
  132. << unsigned(value1);
  133. if (value1 >= 20 && value1 <= 63) {
  134. PLOG_VERBOSE << "Incoming DTLS packet, size=" << size;
  135. DtlsTransport::incoming(message);
  136. } else if (value1 >= 128 && value1 <= 191) {
  137. // The RTP header has a minimum size of 12 bytes
  138. // An RTCP packet can have a minimum size of 8 bytes
  139. if (size < 8) {
  140. PLOG_WARNING << "Incoming SRTP/SRTCP packet too short, size=" << size;
  141. return;
  142. }
  143. uint8_t value2 = to_integer<uint8_t>(*(message->begin() + 1)) & 0x7F;
  144. PLOG_VERBOSE << "Demultiplexing SRTCP and SRTP with RTP payload type, value="
  145. << unsigned(value2);
  146. // See RFC 5761 reference above
  147. if (value2 >= 64 && value2 <= 95) { // Range 64-95 (inclusive) MUST be RTCP
  148. PLOG_VERBOSE << "Incoming SRTCP packet, size=" << size;
  149. if (srtp_err_status_t err = srtp_unprotect_rtcp(mSrtpIn, message->data(), &size)) {
  150. if (err == srtp_err_status_replay_fail)
  151. PLOG_WARNING << "Incoming SRTCP packet is a replay";
  152. else if (err == srtp_err_status_auth_fail)
  153. PLOG_WARNING << "Incoming SRTCP packet failed authentication check";
  154. else
  155. PLOG_WARNING << "SRTCP unprotect error, status=" << err;
  156. return;
  157. }
  158. PLOG_VERBOSE << "Unprotected SRTCP packet, size=" << size;
  159. message->type = Message::Type::Control;
  160. message->stream = reinterpret_cast<RTCP_SR *>(message->data())->senderSSRC();
  161. } else {
  162. PLOG_VERBOSE << "Incoming SRTP packet, size=" << size;
  163. if (srtp_err_status_t err = srtp_unprotect(mSrtpIn, message->data(), &size)) {
  164. if (err == srtp_err_status_replay_fail)
  165. PLOG_WARNING << "Incoming SRTP packet is a replay";
  166. else if (err == srtp_err_status_auth_fail)
  167. PLOG_WARNING << "Incoming SRTP packet failed authentication check";
  168. else
  169. PLOG_WARNING << "SRTP unprotect error, status=" << err;
  170. return;
  171. }
  172. PLOG_VERBOSE << "Unprotected SRTP packet, size=" << size;
  173. message->type = Message::Type::Binary;
  174. message->stream = reinterpret_cast<RTP *>(message->data())->ssrc();
  175. }
  176. message->resize(size);
  177. mSrtpRecvCallback(message);
  178. } else {
  179. PLOG_WARNING << "Unknown packet type, value=" << unsigned(value1) << ", size=" << size;
  180. }
  181. }
  182. void DtlsSrtpTransport::postHandshake() {
  183. if (mInitDone)
  184. return;
  185. static_assert(SRTP_AES_ICM_128_KEY_LEN_WSALT == SRTP_AES_128_KEY_LEN + SRTP_SALT_LEN);
  186. const size_t materialLen = SRTP_AES_ICM_128_KEY_LEN_WSALT * 2;
  187. unsigned char material[materialLen];
  188. const unsigned char *clientKey, *clientSalt, *serverKey, *serverSalt;
  189. #if USE_GNUTLS
  190. PLOG_INFO << "Deriving SRTP keying material (GnuTLS)";
  191. gnutls_datum_t clientKeyDatum, clientSaltDatum, serverKeyDatum, serverSaltDatum;
  192. gnutls::check(gnutls_srtp_get_keys(mSession, material, materialLen, &clientKeyDatum,
  193. &clientSaltDatum, &serverKeyDatum, &serverSaltDatum),
  194. "Failed to derive SRTP keys");
  195. if (clientKeyDatum.size != SRTP_AES_128_KEY_LEN)
  196. throw std::logic_error("Unexpected SRTP master key length: " +
  197. to_string(clientKeyDatum.size));
  198. if (clientSaltDatum.size != SRTP_SALT_LEN)
  199. throw std::logic_error("Unexpected SRTP salt length: " + to_string(clientSaltDatum.size));
  200. if (serverKeyDatum.size != SRTP_AES_128_KEY_LEN)
  201. throw std::logic_error("Unexpected SRTP master key length: " +
  202. to_string(serverKeyDatum.size));
  203. if (serverSaltDatum.size != SRTP_SALT_LEN)
  204. throw std::logic_error("Unexpected SRTP salt size: " + to_string(serverSaltDatum.size));
  205. clientKey = reinterpret_cast<const unsigned char *>(clientKeyDatum.data);
  206. clientSalt = reinterpret_cast<const unsigned char *>(clientSaltDatum.data);
  207. serverKey = reinterpret_cast<const unsigned char *>(serverKeyDatum.data);
  208. serverSalt = reinterpret_cast<const unsigned char *>(serverSaltDatum.data);
  209. #else
  210. PLOG_INFO << "Deriving SRTP keying material (OpenSSL)";
  211. // The extractor provides the client write master key, the server write master key, the client
  212. // write master salt and the server write master salt in that order.
  213. const string label = "EXTRACTOR-dtls_srtp";
  214. // returns 1 on success, 0 or -1 on failure (OpenSSL API is a complete mess...)
  215. if (SSL_export_keying_material(mSsl, material, materialLen, label.c_str(), label.size(),
  216. nullptr, 0, 0) <= 0)
  217. throw std::runtime_error("Failed to derive SRTP keys: " +
  218. openssl::error_string(ERR_get_error()));
  219. // Order is client key, server key, client salt, and server salt
  220. clientKey = material;
  221. serverKey = clientKey + SRTP_AES_128_KEY_LEN;
  222. clientSalt = serverKey + SRTP_AES_128_KEY_LEN;
  223. serverSalt = clientSalt + SRTP_SALT_LEN;
  224. #endif
  225. std::memcpy(mClientSessionKey, clientKey, SRTP_AES_128_KEY_LEN);
  226. std::memcpy(mClientSessionKey + SRTP_AES_128_KEY_LEN, clientSalt, SRTP_SALT_LEN);
  227. std::memcpy(mServerSessionKey, serverKey, SRTP_AES_128_KEY_LEN);
  228. std::memcpy(mServerSessionKey + SRTP_AES_128_KEY_LEN, serverSalt, SRTP_SALT_LEN);
  229. srtp_policy_t inbound = {};
  230. srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&inbound.rtp);
  231. srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&inbound.rtcp);
  232. inbound.ssrc.type = ssrc_any_inbound;
  233. inbound.key = mIsClient ? mServerSessionKey : mClientSessionKey;
  234. inbound.window_size = 1024;
  235. inbound.allow_repeat_tx = true;
  236. inbound.next = nullptr;
  237. if (srtp_err_status_t err = srtp_add_stream(mSrtpIn, &inbound))
  238. throw std::runtime_error("SRTP add inbound stream failed, status=" +
  239. to_string(static_cast<int>(err)));
  240. srtp_policy_t outbound = {};
  241. srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&outbound.rtp);
  242. srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&outbound.rtcp);
  243. outbound.ssrc.type = ssrc_any_outbound;
  244. outbound.key = mIsClient ? mClientSessionKey : mServerSessionKey;
  245. outbound.window_size = 1024;
  246. outbound.allow_repeat_tx = true;
  247. outbound.next = nullptr;
  248. if (srtp_err_status_t err = srtp_add_stream(mSrtpOut, &outbound))
  249. throw std::runtime_error("SRTP add outbound stream failed, status=" +
  250. to_string(static_cast<int>(err)));
  251. mInitDone = true;
  252. }
  253. } // namespace rtc
  254. #endif