dtlssrtptransport.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. if (!message)
  64. return false;
  65. if (!mInitDone) {
  66. PLOG_WARNING << "SRTP media sent before keys are derived";
  67. return false;
  68. }
  69. int size = message->size();
  70. PLOG_VERBOSE << "Send size=" << size;
  71. // The RTP header has a minimum size of 12 bytes
  72. // An RTCP packet can have a minimum size of 8 bytes
  73. if (size < 8)
  74. throw std::runtime_error("RTP/RTCP packet too short");
  75. // srtp_protect() and srtp_protect_rtcp() assume that they can write SRTP_MAX_TRAILER_LEN (for
  76. // the authentication tag) into the location in memory immediately following the RTP packet.
  77. message->resize(size + SRTP_MAX_TRAILER_LEN);
  78. uint8_t value2 = to_integer<uint8_t>(*(message->begin() + 1)) & 0x7F;
  79. PLOG_VERBOSE << "Demultiplexing SRTCP and SRTP with RTP payload type, value="
  80. << unsigned(value2);
  81. // RFC 5761 Multiplexing RTP and RTCP 4. Distinguishable RTP and RTCP Packets
  82. // https://tools.ietf.org/html/rfc5761#section-4
  83. // It is RECOMMENDED to follow the guidelines in the RTP/AVP profile for the choice of RTP
  84. // payload type values, with the additional restriction that payload type values in the
  85. // range 64-95 MUST NOT be used. Specifically, dynamic RTP payload types SHOULD be chosen in
  86. // the range 96-127 where possible. Values below 64 MAY be used if that is insufficient
  87. // [...]
  88. if (value2 >= 64 && value2 <= 95) { // Range 64-95 (inclusive) MUST be RTCP
  89. if (srtp_err_status_t err = srtp_protect_rtcp(mSrtpOut, message->data(), &size)) {
  90. if (err == srtp_err_status_replay_fail)
  91. throw std::runtime_error("SRTCP packet is a replay");
  92. else
  93. throw std::runtime_error("SRTCP protect error, status=" +
  94. to_string(static_cast<int>(err)));
  95. }
  96. PLOG_VERBOSE << "Protected SRTCP packet, size=" << size;
  97. } else {
  98. if (srtp_err_status_t err = srtp_protect(mSrtpOut, message->data(), &size)) {
  99. if (err == srtp_err_status_replay_fail)
  100. throw std::runtime_error("SRTP packet is a replay");
  101. else
  102. throw std::runtime_error("SRTP protect error, status=" +
  103. to_string(static_cast<int>(err)));
  104. }
  105. PLOG_VERBOSE << "Protected SRTP packet, size=" << size;
  106. }
  107. message->resize(size);
  108. return outgoing(message);
  109. // return DtlsTransport::send(message);
  110. }
  111. void DtlsSrtpTransport::incoming(message_ptr message) {
  112. if (!mInitDone) {
  113. // Bypas
  114. DtlsTransport::incoming(message);
  115. return;
  116. }
  117. int size = message->size();
  118. if (size == 0)
  119. return;
  120. // RFC 5764 5.1.2. Reception
  121. // https://tools.ietf.org/html/rfc5764#section-5.1.2
  122. // The process for demultiplexing a packet is as follows. The receiver looks at the first byte
  123. // of the packet. [...] If the value is in between 128 and 191 (inclusive), then the packet is
  124. // RTP (or RTCP [...]). If the value is between 20 and 63 (inclusive), the packet is DTLS.
  125. uint8_t value1 = to_integer<uint8_t>(*message->begin());
  126. PLOG_VERBOSE << "Demultiplexing DTLS and SRTP/SRTCP with first byte, value="
  127. << unsigned(value1);
  128. if (value1 >= 20 && value1 <= 63) {
  129. PLOG_VERBOSE << "Incoming DTLS packet, size=" << size;
  130. DtlsTransport::incoming(message);
  131. } else if (value1 >= 128 && value1 <= 191) {
  132. // The RTP header has a minimum size of 12 bytes
  133. // An RTCP packet can have a minimum size of 8 bytes
  134. if (size < 8) {
  135. PLOG_WARNING << "Incoming SRTP/SRTCP packet too short, size=" << size;
  136. return;
  137. }
  138. uint8_t value2 = to_integer<uint8_t>(*(message->begin() + 1)) & 0x7F;
  139. PLOG_VERBOSE << "Demultiplexing SRTCP and SRTP with RTP payload type, value="
  140. << unsigned(value2);
  141. // See RFC 5761 reference above
  142. if (value2 >= 64 && value2 <= 95) { // Range 64-95 (inclusive) MUST be RTCP
  143. PLOG_VERBOSE << "Incoming SRTCP packet, size=" << size;
  144. if (srtp_err_status_t err = srtp_unprotect_rtcp(mSrtpIn, message->data(), &size)) {
  145. if (err == srtp_err_status_replay_fail)
  146. PLOG_WARNING << "Incoming SRTCP packet is a replay";
  147. else if (err == srtp_err_status_auth_fail)
  148. PLOG_WARNING << "Incoming SRTCP packet failed authentication check";
  149. else
  150. PLOG_WARNING << "SRTCP unprotect error, status=" << err;
  151. return;
  152. }
  153. PLOG_VERBOSE << "Unprotected SRTCP packet, size=" << size;
  154. message->type = Message::Type::Control;
  155. message->stream = to_integer<uint8_t>(*(message->begin() + 1)); // Payload Type
  156. } else {
  157. PLOG_VERBOSE << "Incoming SRTP packet, size=" << size;
  158. if (srtp_err_status_t err = srtp_unprotect(mSrtpIn, message->data(), &size)) {
  159. if (err == srtp_err_status_replay_fail)
  160. PLOG_WARNING << "Incoming SRTP packet is a replay";
  161. else if (err == srtp_err_status_auth_fail)
  162. PLOG_WARNING << "Incoming SRTP packet failed authentication check";
  163. else
  164. PLOG_WARNING << "SRTP unprotect error, status=" << err;
  165. return;
  166. }
  167. PLOG_VERBOSE << "Unprotected SRTP packet, size=" << size;
  168. message->type = Message::Type::Binary;
  169. message->stream = value2; // Payload Type
  170. }
  171. message->resize(size);
  172. mSrtpRecvCallback(message);
  173. } else {
  174. PLOG_WARNING << "Unknown packet type, value=" << unsigned(value1) << ", size=" << size;
  175. }
  176. }
  177. void DtlsSrtpTransport::postHandshake() {
  178. if (mInitDone)
  179. return;
  180. const size_t materialLen = SRTP_AES_ICM_128_KEY_LEN_WSALT * 2;
  181. unsigned char material[materialLen];
  182. const unsigned char *clientKey, *clientSalt, *serverKey, *serverSalt;
  183. #if USE_GNUTLS
  184. PLOG_INFO << "Deriving SRTP keying material (GnuTLS)";
  185. gnutls_datum_t clientKeyDatum, clientSaltDatum, serverKeyDatum, serverSaltDatum;
  186. gnutls::check(gnutls_srtp_get_keys(mSession, material, materialLen, &clientKeyDatum,
  187. &clientSaltDatum, &serverKeyDatum, &serverSaltDatum),
  188. "Failed to derive SRTP keys");
  189. if (clientKeyDatum.size != SRTP_AES_128_KEY_LEN)
  190. throw std::logic_error("Unexpected SRTP master key length: " +
  191. to_string(clientKeyDatum.size));
  192. if (clientSaltDatum.size != SRTP_SALT_LEN)
  193. throw std::logic_error("Unexpected SRTP salt length: " + to_string(clientSaltDatum.size));
  194. if (serverKeyDatum.size != SRTP_AES_128_KEY_LEN)
  195. throw std::logic_error("Unexpected SRTP master key length: " +
  196. to_string(serverKeyDatum.size));
  197. if (serverSaltDatum.size != SRTP_SALT_LEN)
  198. throw std::logic_error("Unexpected SRTP salt size: " + to_string(serverSaltDatum.size));
  199. clientKey = reinterpret_cast<const unsigned char *>(clientKeyDatum.data);
  200. clientSalt = reinterpret_cast<const unsigned char *>(clientSaltDatum.data);
  201. serverKey = reinterpret_cast<const unsigned char *>(serverKeyDatum.data);
  202. serverSalt = reinterpret_cast<const unsigned char *>(serverSaltDatum.data);
  203. #else
  204. PLOG_INFO << "Deriving SRTP keying material (OpenSSL)";
  205. // The extractor provides the client write master key, the server write master key, the client
  206. // write master salt and the server write master salt in that order.
  207. const string label = "EXTRACTOR-dtls_srtp";
  208. // returns 1 on success, 0 or -1 on failure (OpenSSL API is a complete mess...)
  209. if (SSL_export_keying_material(mSsl, material, materialLen, label.c_str(), label.size(),
  210. nullptr, 0, 0) <= 0)
  211. throw std::runtime_error("Failed to derive SRTP keys: " +
  212. openssl::error_string(ERR_get_error()));
  213. // Order is client key, server key, client salt, and server salt
  214. clientKey = material;
  215. serverKey = clientKey + SRTP_AES_128_KEY_LEN;
  216. clientSalt = serverKey + SRTP_AES_128_KEY_LEN;
  217. serverSalt = clientSalt + SRTP_SALT_LEN;
  218. #endif
  219. unsigned char clientSessionKey[SRTP_AES_ICM_128_KEY_LEN_WSALT];
  220. std::memcpy(clientSessionKey, clientKey, SRTP_AES_128_KEY_LEN);
  221. std::memcpy(clientSessionKey + SRTP_AES_128_KEY_LEN, clientSalt, SRTP_SALT_LEN);
  222. unsigned char serverSessionKey[SRTP_AES_ICM_128_KEY_LEN_WSALT];
  223. std::memcpy(serverSessionKey, serverKey, SRTP_AES_128_KEY_LEN);
  224. std::memcpy(serverSessionKey + SRTP_AES_128_KEY_LEN, serverSalt, SRTP_SALT_LEN);
  225. srtp_policy_t inbound = {};
  226. srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&inbound.rtp);
  227. srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&inbound.rtcp);
  228. inbound.ssrc.type = ssrc_any_inbound;
  229. inbound.ssrc.value = 0;
  230. inbound.key = mIsClient ? serverSessionKey : clientSessionKey;
  231. inbound.next = nullptr;
  232. if (srtp_err_status_t err = srtp_add_stream(mSrtpIn, &inbound))
  233. throw std::runtime_error("SRTP add inbound stream failed, status=" +
  234. to_string(static_cast<int>(err)));
  235. srtp_policy_t outbound = {};
  236. srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&outbound.rtp);
  237. srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&outbound.rtcp);
  238. outbound.ssrc.type = ssrc_any_outbound;
  239. outbound.ssrc.value = 0;
  240. outbound.key = mIsClient ? clientSessionKey : serverSessionKey;
  241. outbound.next = nullptr;
  242. if (srtp_err_status_t err = srtp_add_stream(mSrtpOut, &outbound))
  243. throw std::runtime_error("SRTP add outbound stream failed, status=" +
  244. to_string(static_cast<int>(err)));
  245. mInitDone = true;
  246. }
  247. } // namespace rtc
  248. #endif