You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

443 lines
14 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2017 The WebRTC project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include "pc/srtp_session.h"
  11. #include "absl/base/attributes.h"
  12. #include "media/base/rtp_utils.h"
  13. #include "pc/external_hmac.h"
  14. #include "rtc_base/critical_section.h"
  15. #include "rtc_base/logging.h"
  16. #include "rtc_base/ssl_stream_adapter.h"
  17. #include "system_wrappers/include/metrics.h"
  18. #include "third_party/libsrtp/include/srtp.h"
  19. #include "third_party/libsrtp/include/srtp_priv.h"
  20. namespace cricket {
  21. // One more than the maximum libsrtp error code. Required by
  22. // RTC_HISTOGRAM_ENUMERATION. Keep this in sync with srtp_error_status_t defined
  23. // in srtp.h.
  24. constexpr int kSrtpErrorCodeBoundary = 28;
  25. SrtpSession::SrtpSession() {}
  26. SrtpSession::~SrtpSession() {
  27. if (session_) {
  28. srtp_set_user_data(session_, nullptr);
  29. srtp_dealloc(session_);
  30. }
  31. if (inited_) {
  32. DecrementLibsrtpUsageCountAndMaybeDeinit();
  33. }
  34. }
  35. bool SrtpSession::SetSend(int cs,
  36. const uint8_t* key,
  37. size_t len,
  38. const std::vector<int>& extension_ids) {
  39. return SetKey(ssrc_any_outbound, cs, key, len, extension_ids);
  40. }
  41. bool SrtpSession::UpdateSend(int cs,
  42. const uint8_t* key,
  43. size_t len,
  44. const std::vector<int>& extension_ids) {
  45. return UpdateKey(ssrc_any_outbound, cs, key, len, extension_ids);
  46. }
  47. bool SrtpSession::SetRecv(int cs,
  48. const uint8_t* key,
  49. size_t len,
  50. const std::vector<int>& extension_ids) {
  51. return SetKey(ssrc_any_inbound, cs, key, len, extension_ids);
  52. }
  53. bool SrtpSession::UpdateRecv(int cs,
  54. const uint8_t* key,
  55. size_t len,
  56. const std::vector<int>& extension_ids) {
  57. return UpdateKey(ssrc_any_inbound, cs, key, len, extension_ids);
  58. }
  59. bool SrtpSession::ProtectRtp(void* p, int in_len, int max_len, int* out_len) {
  60. RTC_DCHECK(thread_checker_.IsCurrent());
  61. if (!session_) {
  62. RTC_LOG(LS_WARNING) << "Failed to protect SRTP packet: no SRTP Session";
  63. return false;
  64. }
  65. int need_len = in_len + rtp_auth_tag_len_; // NOLINT
  66. if (max_len < need_len) {
  67. RTC_LOG(LS_WARNING) << "Failed to protect SRTP packet: The buffer length "
  68. << max_len << " is less than the needed " << need_len;
  69. return false;
  70. }
  71. *out_len = in_len;
  72. int err = srtp_protect(session_, p, out_len);
  73. int seq_num;
  74. GetRtpSeqNum(p, in_len, &seq_num);
  75. if (err != srtp_err_status_ok) {
  76. RTC_LOG(LS_WARNING) << "Failed to protect SRTP packet, seqnum=" << seq_num
  77. << ", err=" << err
  78. << ", last seqnum=" << last_send_seq_num_;
  79. return false;
  80. }
  81. last_send_seq_num_ = seq_num;
  82. return true;
  83. }
  84. bool SrtpSession::ProtectRtp(void* p,
  85. int in_len,
  86. int max_len,
  87. int* out_len,
  88. int64_t* index) {
  89. if (!ProtectRtp(p, in_len, max_len, out_len)) {
  90. return false;
  91. }
  92. return (index) ? GetSendStreamPacketIndex(p, in_len, index) : true;
  93. }
  94. bool SrtpSession::ProtectRtcp(void* p, int in_len, int max_len, int* out_len) {
  95. RTC_DCHECK(thread_checker_.IsCurrent());
  96. if (!session_) {
  97. RTC_LOG(LS_WARNING) << "Failed to protect SRTCP packet: no SRTP Session";
  98. return false;
  99. }
  100. int need_len = in_len + sizeof(uint32_t) + rtcp_auth_tag_len_; // NOLINT
  101. if (max_len < need_len) {
  102. RTC_LOG(LS_WARNING) << "Failed to protect SRTCP packet: The buffer length "
  103. << max_len << " is less than the needed " << need_len;
  104. return false;
  105. }
  106. *out_len = in_len;
  107. int err = srtp_protect_rtcp(session_, p, out_len);
  108. if (err != srtp_err_status_ok) {
  109. RTC_LOG(LS_WARNING) << "Failed to protect SRTCP packet, err=" << err;
  110. return false;
  111. }
  112. return true;
  113. }
  114. bool SrtpSession::UnprotectRtp(void* p, int in_len, int* out_len) {
  115. RTC_DCHECK(thread_checker_.IsCurrent());
  116. if (!session_) {
  117. RTC_LOG(LS_WARNING) << "Failed to unprotect SRTP packet: no SRTP Session";
  118. return false;
  119. }
  120. *out_len = in_len;
  121. int err = srtp_unprotect(session_, p, out_len);
  122. if (err != srtp_err_status_ok) {
  123. // Limit the error logging to avoid excessive logs when there are lots of
  124. // bad packets.
  125. const int kFailureLogThrottleCount = 100;
  126. if (decryption_failure_count_ % kFailureLogThrottleCount == 0) {
  127. RTC_LOG(LS_WARNING) << "Failed to unprotect SRTP packet, err=" << err
  128. << ", previous failure count: "
  129. << decryption_failure_count_;
  130. }
  131. ++decryption_failure_count_;
  132. RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SrtpUnprotectError",
  133. static_cast<int>(err), kSrtpErrorCodeBoundary);
  134. return false;
  135. }
  136. return true;
  137. }
  138. bool SrtpSession::UnprotectRtcp(void* p, int in_len, int* out_len) {
  139. RTC_DCHECK(thread_checker_.IsCurrent());
  140. if (!session_) {
  141. RTC_LOG(LS_WARNING) << "Failed to unprotect SRTCP packet: no SRTP Session";
  142. return false;
  143. }
  144. *out_len = in_len;
  145. int err = srtp_unprotect_rtcp(session_, p, out_len);
  146. if (err != srtp_err_status_ok) {
  147. RTC_LOG(LS_WARNING) << "Failed to unprotect SRTCP packet, err=" << err;
  148. RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SrtcpUnprotectError",
  149. static_cast<int>(err), kSrtpErrorCodeBoundary);
  150. return false;
  151. }
  152. return true;
  153. }
  154. bool SrtpSession::GetRtpAuthParams(uint8_t** key, int* key_len, int* tag_len) {
  155. RTC_DCHECK(thread_checker_.IsCurrent());
  156. RTC_DCHECK(IsExternalAuthActive());
  157. if (!IsExternalAuthActive()) {
  158. return false;
  159. }
  160. ExternalHmacContext* external_hmac = nullptr;
  161. // stream_template will be the reference context for other streams.
  162. // Let's use it for getting the keys.
  163. srtp_stream_ctx_t* srtp_context = session_->stream_template;
  164. if (srtp_context && srtp_context->session_keys &&
  165. srtp_context->session_keys->rtp_auth) {
  166. external_hmac = reinterpret_cast<ExternalHmacContext*>(
  167. srtp_context->session_keys->rtp_auth->state);
  168. }
  169. if (!external_hmac) {
  170. RTC_LOG(LS_ERROR) << "Failed to get auth keys from libsrtp!.";
  171. return false;
  172. }
  173. *key = external_hmac->key;
  174. *key_len = external_hmac->key_length;
  175. *tag_len = rtp_auth_tag_len_;
  176. return true;
  177. }
  178. int SrtpSession::GetSrtpOverhead() const {
  179. return rtp_auth_tag_len_;
  180. }
  181. void SrtpSession::EnableExternalAuth() {
  182. RTC_DCHECK(!session_);
  183. external_auth_enabled_ = true;
  184. }
  185. bool SrtpSession::IsExternalAuthEnabled() const {
  186. return external_auth_enabled_;
  187. }
  188. bool SrtpSession::IsExternalAuthActive() const {
  189. return external_auth_active_;
  190. }
  191. bool SrtpSession::GetSendStreamPacketIndex(void* p,
  192. int in_len,
  193. int64_t* index) {
  194. RTC_DCHECK(thread_checker_.IsCurrent());
  195. srtp_hdr_t* hdr = reinterpret_cast<srtp_hdr_t*>(p);
  196. srtp_stream_ctx_t* stream = srtp_get_stream(session_, hdr->ssrc);
  197. if (!stream) {
  198. return false;
  199. }
  200. // Shift packet index, put into network byte order
  201. *index = static_cast<int64_t>(rtc::NetworkToHost64(
  202. srtp_rdbx_get_packet_index(&stream->rtp_rdbx) << 16));
  203. return true;
  204. }
  205. bool SrtpSession::DoSetKey(int type,
  206. int cs,
  207. const uint8_t* key,
  208. size_t len,
  209. const std::vector<int>& extension_ids) {
  210. RTC_DCHECK(thread_checker_.IsCurrent());
  211. srtp_policy_t policy;
  212. memset(&policy, 0, sizeof(policy));
  213. if (cs == rtc::SRTP_AES128_CM_SHA1_80) {
  214. srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtp);
  215. srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp);
  216. } else if (cs == rtc::SRTP_AES128_CM_SHA1_32) {
  217. // RTP HMAC is shortened to 32 bits, but RTCP remains 80 bits.
  218. srtp_crypto_policy_set_aes_cm_128_hmac_sha1_32(&policy.rtp);
  219. srtp_crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp);
  220. } else if (cs == rtc::SRTP_AEAD_AES_128_GCM) {
  221. srtp_crypto_policy_set_aes_gcm_128_16_auth(&policy.rtp);
  222. srtp_crypto_policy_set_aes_gcm_128_16_auth(&policy.rtcp);
  223. } else if (cs == rtc::SRTP_AEAD_AES_256_GCM) {
  224. srtp_crypto_policy_set_aes_gcm_256_16_auth(&policy.rtp);
  225. srtp_crypto_policy_set_aes_gcm_256_16_auth(&policy.rtcp);
  226. } else {
  227. RTC_LOG(LS_WARNING) << "Failed to " << (session_ ? "update" : "create")
  228. << " SRTP session: unsupported cipher_suite " << cs;
  229. return false;
  230. }
  231. int expected_key_len;
  232. int expected_salt_len;
  233. if (!rtc::GetSrtpKeyAndSaltLengths(cs, &expected_key_len,
  234. &expected_salt_len)) {
  235. // This should never happen.
  236. RTC_NOTREACHED();
  237. RTC_LOG(LS_WARNING)
  238. << "Failed to " << (session_ ? "update" : "create")
  239. << " SRTP session: unsupported cipher_suite without length information"
  240. << cs;
  241. return false;
  242. }
  243. if (!key ||
  244. len != static_cast<size_t>(expected_key_len + expected_salt_len)) {
  245. RTC_LOG(LS_WARNING) << "Failed to " << (session_ ? "update" : "create")
  246. << " SRTP session: invalid key";
  247. return false;
  248. }
  249. policy.ssrc.type = static_cast<srtp_ssrc_type_t>(type);
  250. policy.ssrc.value = 0;
  251. policy.key = const_cast<uint8_t*>(key);
  252. // TODO(astor) parse window size from WSH session-param
  253. policy.window_size = 1024;
  254. policy.allow_repeat_tx = 1;
  255. // If external authentication option is enabled, supply custom auth module
  256. // id EXTERNAL_HMAC_SHA1 in the policy structure.
  257. // We want to set this option only for rtp packets.
  258. // By default policy structure is initialized to HMAC_SHA1.
  259. // Enable external HMAC authentication only for outgoing streams and only
  260. // for cipher suites that support it (i.e. only non-GCM cipher suites).
  261. if (type == ssrc_any_outbound && IsExternalAuthEnabled() &&
  262. !rtc::IsGcmCryptoSuite(cs)) {
  263. policy.rtp.auth_type = EXTERNAL_HMAC_SHA1;
  264. }
  265. if (!extension_ids.empty()) {
  266. policy.enc_xtn_hdr = const_cast<int*>(&extension_ids[0]);
  267. policy.enc_xtn_hdr_count = static_cast<int>(extension_ids.size());
  268. }
  269. policy.next = nullptr;
  270. if (!session_) {
  271. int err = srtp_create(&session_, &policy);
  272. if (err != srtp_err_status_ok) {
  273. session_ = nullptr;
  274. RTC_LOG(LS_ERROR) << "Failed to create SRTP session, err=" << err;
  275. return false;
  276. }
  277. srtp_set_user_data(session_, this);
  278. } else {
  279. int err = srtp_update(session_, &policy);
  280. if (err != srtp_err_status_ok) {
  281. RTC_LOG(LS_ERROR) << "Failed to update SRTP session, err=" << err;
  282. return false;
  283. }
  284. }
  285. rtp_auth_tag_len_ = policy.rtp.auth_tag_len;
  286. rtcp_auth_tag_len_ = policy.rtcp.auth_tag_len;
  287. external_auth_active_ = (policy.rtp.auth_type == EXTERNAL_HMAC_SHA1);
  288. return true;
  289. }
  290. bool SrtpSession::SetKey(int type,
  291. int cs,
  292. const uint8_t* key,
  293. size_t len,
  294. const std::vector<int>& extension_ids) {
  295. RTC_DCHECK(thread_checker_.IsCurrent());
  296. if (session_) {
  297. RTC_LOG(LS_ERROR) << "Failed to create SRTP session: "
  298. "SRTP session already created";
  299. return false;
  300. }
  301. // This is the first time we need to actually interact with libsrtp, so
  302. // initialize it if needed.
  303. if (IncrementLibsrtpUsageCountAndMaybeInit()) {
  304. inited_ = true;
  305. } else {
  306. return false;
  307. }
  308. return DoSetKey(type, cs, key, len, extension_ids);
  309. }
  310. bool SrtpSession::UpdateKey(int type,
  311. int cs,
  312. const uint8_t* key,
  313. size_t len,
  314. const std::vector<int>& extension_ids) {
  315. RTC_DCHECK(thread_checker_.IsCurrent());
  316. if (!session_) {
  317. RTC_LOG(LS_ERROR) << "Failed to update non-existing SRTP session";
  318. return false;
  319. }
  320. return DoSetKey(type, cs, key, len, extension_ids);
  321. }
  322. ABSL_CONST_INIT int g_libsrtp_usage_count = 0;
  323. ABSL_CONST_INIT rtc::GlobalLock g_libsrtp_lock;
  324. // static
  325. bool SrtpSession::IncrementLibsrtpUsageCountAndMaybeInit() {
  326. rtc::GlobalLockScope ls(&g_libsrtp_lock);
  327. RTC_DCHECK_GE(g_libsrtp_usage_count, 0);
  328. if (g_libsrtp_usage_count == 0) {
  329. int err;
  330. err = srtp_init();
  331. if (err != srtp_err_status_ok) {
  332. RTC_LOG(LS_ERROR) << "Failed to init SRTP, err=" << err;
  333. return false;
  334. }
  335. err = srtp_install_event_handler(&SrtpSession::HandleEventThunk);
  336. if (err != srtp_err_status_ok) {
  337. RTC_LOG(LS_ERROR) << "Failed to install SRTP event handler, err=" << err;
  338. return false;
  339. }
  340. err = external_crypto_init();
  341. if (err != srtp_err_status_ok) {
  342. RTC_LOG(LS_ERROR) << "Failed to initialize fake auth, err=" << err;
  343. return false;
  344. }
  345. }
  346. ++g_libsrtp_usage_count;
  347. return true;
  348. }
  349. // static
  350. void SrtpSession::DecrementLibsrtpUsageCountAndMaybeDeinit() {
  351. rtc::GlobalLockScope ls(&g_libsrtp_lock);
  352. RTC_DCHECK_GE(g_libsrtp_usage_count, 1);
  353. if (--g_libsrtp_usage_count == 0) {
  354. int err = srtp_shutdown();
  355. if (err) {
  356. RTC_LOG(LS_ERROR) << "srtp_shutdown failed. err=" << err;
  357. }
  358. }
  359. }
  360. void SrtpSession::HandleEvent(const srtp_event_data_t* ev) {
  361. RTC_DCHECK(thread_checker_.IsCurrent());
  362. switch (ev->event) {
  363. case event_ssrc_collision:
  364. RTC_LOG(LS_INFO) << "SRTP event: SSRC collision";
  365. break;
  366. case event_key_soft_limit:
  367. RTC_LOG(LS_INFO) << "SRTP event: reached soft key usage limit";
  368. break;
  369. case event_key_hard_limit:
  370. RTC_LOG(LS_INFO) << "SRTP event: reached hard key usage limit";
  371. break;
  372. case event_packet_index_limit:
  373. RTC_LOG(LS_INFO)
  374. << "SRTP event: reached hard packet limit (2^48 packets)";
  375. break;
  376. default:
  377. RTC_LOG(LS_INFO) << "SRTP event: unknown " << ev->event;
  378. break;
  379. }
  380. }
  381. void SrtpSession::HandleEventThunk(srtp_event_data_t* ev) {
  382. // Callback will be executed from same thread that calls the "srtp_protect"
  383. // and "srtp_unprotect" functions.
  384. SrtpSession* session =
  385. static_cast<SrtpSession*>(srtp_get_user_data(ev->session));
  386. if (session) {
  387. session->HandleEvent(ev);
  388. }
  389. }
  390. } // namespace cricket