| 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 |
| 11 | #include "pc/srtp_session.h" |
| 12 |
| 13 | #include <iomanip> |
| 14 |
| 15 | #include "absl/base/attributes.h" |
| 16 | #include "media/base/rtp_utils.h" |
| 17 | #include "pc/external_hmac.h" |
| 18 | #include "rtc_base/logging.h" |
| 19 | #include "rtc_base/ssl_stream_adapter.h" |
| 20 | #include "rtc_base/string_encode.h" |
| 21 | #include "rtc_base/time_utils.h" |
| 22 | #include "system_wrappers/include/field_trial.h" |
| 23 | #include "system_wrappers/include/metrics.h" |
| 24 | #include "third_party/libsrtp/include/srtp.h" |
| 25 | #include "third_party/libsrtp/include/srtp_priv.h" |
| 26 |
| 27 | namespace cricket { |
| 28 |
| 29 | // One more than the maximum libsrtp error code. Required by |
| 30 | // RTC_HISTOGRAM_ENUMERATION. Keep this in sync with srtp_error_status_t defined |
| 31 | // in srtp.h. |
| 32 | constexpr int kSrtpErrorCodeBoundary = 28; |
| 33 |
| 34 | SrtpSession::SrtpSession() { |
| 35 | dump_plain_rtp_ = webrtc::field_trial::IsEnabled("WebRTC-Debugging-RtpDump"); |
| 36 | } |
| 37 |
| 38 | SrtpSession::~SrtpSession() { |
| 39 | if (session_) { |
| 40 | srtp_set_user_data(session_, nullptr); |
| 41 | srtp_dealloc(session_); |
| 42 | } |
| 43 | if (inited_) { |
| 44 | DecrementLibsrtpUsageCountAndMaybeDeinit(); |
| 45 | } |
| 46 | } |
| 47 |
| 48 | bool SrtpSession::SetSend(int cs, |
| 49 | const uint8_t* key, |
| 50 | size_t len, |
| 51 | const std::vector<int>& extension_ids) { |
| 52 | return SetKey(ssrc_any_outbound, cs, key, len, extension_ids); |
| 53 | } |
| 54 |
| 55 | bool SrtpSession::UpdateSend(int cs, |
| 56 | const uint8_t* key, |
| 57 | size_t len, |
| 58 | const std::vector<int>& extension_ids) { |
| 59 | return UpdateKey(ssrc_any_outbound, cs, key, len, extension_ids); |
| 60 | } |
| 61 |
| 62 | bool SrtpSession::SetRecv(int cs, |
| 63 | const uint8_t* key, |
| 64 | size_t len, |
| 65 | const std::vector<int>& extension_ids) { |
| 66 | return SetKey(ssrc_any_inbound, cs, key, len, extension_ids); |
| 67 | } |
| 68 |
| 69 | bool SrtpSession::UpdateRecv(int cs, |
| 70 | const uint8_t* key, |
| 71 | size_t len, |
| 72 | const std::vector<int>& extension_ids) { |
| 73 | return UpdateKey(ssrc_any_inbound, cs, key, len, extension_ids); |
| 74 | } |
| 75 |
| 76 | bool SrtpSession::ProtectRtp(void* p, int in_len, int max_len, int* out_len) { |
| 77 | RTC_DCHECK(thread_checker_.IsCurrent()); |
| 78 | if (!session_) { |
| 79 | RTC_LOG(LS_WARNING) << "Failed to protect SRTP packet: no SRTP Session"; |
| 80 | return false; |
| 81 | } |
| 82 |
| 83 | // Note: the need_len differs from the libsrtp recommendatіon to ensure |
| 84 | // SRTP_MAX_TRAILER_LEN bytes of free space after the data. WebRTC |
| 85 | // never includes a MKI, therefore the amount of bytes added by the |
| 86 | // srtp_protect call is known in advance and depends on the cipher suite. |
| 87 | int need_len = in_len + rtp_auth_tag_len_; // NOLINT |
| 88 | if (max_len < need_len) { |
| 89 | RTC_LOG(LS_WARNING) << "Failed to protect SRTP packet: The buffer length " |
| 90 | << max_len << " is less than the needed " << need_len; |
| 91 | return false; |
| 92 | } |
| 93 | if (dump_plain_rtp_) { |
| 94 | DumpPacket(p, in_len, /*outbound=*/true); |
| 95 | } |
| 96 |
| 97 | *out_len = in_len; |
| 98 | int err = srtp_protect(session_, p, out_len); |
| 99 | int seq_num; |
| 100 | GetRtpSeqNum(p, in_len, &seq_num); |
| 101 | if (err != srtp_err_status_ok) { |
| 102 | RTC_LOG(LS_WARNING) << "Failed to protect SRTP packet, seqnum=" << seq_num |
| 103 | << ", err=" << err |
| 104 | << ", last seqnum=" << last_send_seq_num_; |
| 105 | return false; |
| 106 | } |
| 107 | last_send_seq_num_ = seq_num; |
| 108 | return true; |
| 109 | } |
| 110 |
| 111 | bool SrtpSession::ProtectRtp(void* p, |
| 112 | int in_len, |
| 113 | int max_len, |
| 114 | int* out_len, |
| 115 | int64_t* index) { |
| 116 | if (!ProtectRtp(p, in_len, max_len, out_len)) { |
| 117 | return false; |
| 118 | } |
| 119 | return (index) ? GetSendStreamPacketIndex(p, in_len, index) : true; |
| 120 | } |
| 121 |
| 122 | bool SrtpSession::ProtectRtcp(void* p, int in_len, int max_len, int* out_len) { |
| 123 | RTC_DCHECK(thread_checker_.IsCurrent()); |
| 124 | if (!session_) { |
| 125 | RTC_LOG(LS_WARNING) << "Failed to protect SRTCP packet: no SRTP Session"; |
| 126 | return false; |
| 127 | } |
| 128 |
| 129 | // Note: the need_len differs from the libsrtp recommendatіon to ensure |
| 130 | // SRTP_MAX_TRAILER_LEN bytes of free space after the data. WebRTC |
| 131 | // never includes a MKI, therefore the amount of bytes added by the |
| 132 | // srtp_protect_rtp call is known in advance and depends on the cipher suite. |
| 133 | int need_len = in_len + sizeof(uint32_t) + rtcp_auth_tag_len_; // NOLINT |
| 134 | if (max_len < need_len) { |
| 135 | RTC_LOG(LS_WARNING) << "Failed to protect SRTCP packet: The buffer length " |
| 136 | << max_len << " is less than the needed " << need_len; |
| 137 | return false; |
| 138 | } |
| 139 | if (dump_plain_rtp_) { |
| 140 | DumpPacket(p, in_len, /*outbound=*/true); |
| 141 | } |
| 142 |
| 143 | *out_len = in_len; |
| 144 | int err = srtp_protect_rtcp(session_, p, out_len); |
| 145 | if (err != srtp_err_status_ok) { |
| 146 | RTC_LOG(LS_WARNING) << "Failed to protect SRTCP packet, err=" << err; |
| 147 | return false; |
| 148 | } |
| 149 | return true; |
| 150 | } |
| 151 |
| 152 | bool SrtpSession::UnprotectRtp(void* p, int in_len, int* out_len) { |
| 153 | RTC_DCHECK(thread_checker_.IsCurrent()); |
| 154 | if (!session_) { |
| 155 | RTC_LOG(LS_WARNING) << "Failed to unprotect SRTP packet: no SRTP Session"; |
| 156 | return false; |
| 157 | } |
| 158 |
| 159 | *out_len = in_len; |
| 160 | int err = srtp_unprotect(session_, p, out_len); |
| 161 | if (err != srtp_err_status_ok) { |
| 162 | // Limit the error logging to avoid excessive logs when there are lots of |
| 163 | // bad packets. |
| 164 | const int kFailureLogThrottleCount = 100; |
| 165 | if (decryption_failure_count_ % kFailureLogThrottleCount == 0) { |
| 166 | RTC_LOG(LS_WARNING) << "Failed to unprotect SRTP packet, err=" << err |
| 167 | << ", previous failure count: " |
| 168 | << decryption_failure_count_; |
| 169 | } |
| 170 | ++decryption_failure_count_; |
| 171 | RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SrtpUnprotectError", |
| 172 | static_cast<int>(err), kSrtpErrorCodeBoundary); |
| 173 | return false; |
| 174 | } |
| 175 | if (dump_plain_rtp_) { |
| 176 | DumpPacket(p, *out_len, /*outbound=*/false); |
| 177 | } |
| 178 | return true; |
| 179 | } |
| 180 |
| 181 | bool SrtpSession::UnprotectRtcp(void* p, int in_len, int* out_len) { |
| 182 | RTC_DCHECK(thread_checker_.IsCurrent()); |
| 183 | if (!session_) { |
| 184 | RTC_LOG(LS_WARNING) << "Failed to unprotect SRTCP packet: no SRTP Session"; |
| 185 | return false; |
| 186 | } |
| 187 |
| 188 | *out_len = in_len; |
| 189 | int err = srtp_unprotect_rtcp(session_, p, out_len); |
| 190 | if (err != srtp_err_status_ok) { |
| 191 | RTC_LOG(LS_WARNING) << "Failed to unprotect SRTCP packet, err=" << err; |
| 192 | RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SrtcpUnprotectError", |
| 193 | static_cast<int>(err), kSrtpErrorCodeBoundary); |
| 194 | return false; |
| 195 | } |
| 196 | if (dump_plain_rtp_) { |
| 197 | DumpPacket(p, *out_len, /*outbound=*/false); |
| 198 | } |
| 199 | return true; |
| 200 | } |
| 201 |
| 202 | bool SrtpSession::GetRtpAuthParams(uint8_t** key, int* key_len, int* tag_len) { |
| 203 | RTC_DCHECK(thread_checker_.IsCurrent()); |
| 204 | RTC_DCHECK(IsExternalAuthActive()); |
| 205 | if (!IsExternalAuthActive()) { |
| 206 | return false; |
| 207 | } |
| 208 |
| 209 | ExternalHmacContext* external_hmac = nullptr; |
| 210 | // stream_template will be the reference context for other streams. |
| 211 | // Let's use it for getting the keys. |
| 212 | srtp_stream_ctx_t* srtp_context = session_->stream_template; |
| 213 | if (srtp_context && srtp_context->session_keys && |
| 214 | srtp_context->session_keys->rtp_auth) { |
| 215 | external_hmac = reinterpret_cast<ExternalHmacContext*>( |
| 216 | srtp_context->session_keys->rtp_auth->state); |
| 217 | } |
| 218 |
| 219 | if (!external_hmac) { |
| 220 | RTC_LOG(LS_ERROR) << "Failed to get auth keys from libsrtp!."; |
| 221 | return false; |
| 222 | } |
| 223 |
| 224 | *key = external_hmac->key; |
| 225 | *key_len = external_hmac->key_length; |
| 226 | *tag_len = rtp_auth_tag_len_; |
| 227 | return true; |
| 228 | } |
| 229 |
| 230 | int SrtpSession::GetSrtpOverhead() const { |
| 231 | return rtp_auth_tag_len_; |
| 232 | } |
| 233 |
| 234 | void SrtpSession::EnableExternalAuth() { |
| 235 | RTC_DCHECK(!session_); |
| 236 | external_auth_enabled_ = true; |
| 237 | } |
| 238 |
| 239 | bool SrtpSession::IsExternalAuthEnabled() const { |
| 240 | return external_auth_enabled_; |
| 241 | } |
| 242 |
| 243 | bool SrtpSession::IsExternalAuthActive() const { |
| 244 | return external_auth_active_; |
| 245 | } |
| 246 |
| 247 | bool SrtpSession::GetSendStreamPacketIndex(void* p, |
| 248 | int in_len, |
| 249 | int64_t* index) { |
| 250 | RTC_DCHECK(thread_checker_.IsCurrent()); |
| 251 | srtp_hdr_t* hdr = reinterpret_cast<srtp_hdr_t*>(p); |
| 252 | srtp_stream_ctx_t* stream = srtp_get_stream(session_, hdr->ssrc); |
| 253 | if (!stream) { |
| 254 | return false; |
| 255 | } |
| 256 |
| 257 | // Shift packet index, put into network byte order |
| 258 | *index = static_cast<int64_t>(rtc::NetworkToHost64( |
| 259 | srtp_rdbx_get_packet_index(&stream->rtp_rdbx) << 16)); |
| 260 | return true; |
| 261 | } |
| 262 |
| 263 | bool SrtpSession::DoSetKey(int type, |
| 264 | int cs, |
| 265 | const uint8_t* key, |
| 266 | size_t len, |
| 267 | const std::vector<int>& extension_ids) { |
| 268 | RTC_DCHECK(thread_checker_.IsCurrent()); |
| 269 |
| 270 | srtp_policy_t policy; |
| 271 | memset(&policy, 0, sizeof(policy)); |
| 272 | if (!(srtp_crypto_policy_set_from_profile_for_rtp( |
| 273 | &policy.rtp, (srtp_profile_t)cs) == srtp_err_status_ok && |
| 274 | srtp_crypto_policy_set_from_profile_for_rtcp( |
| 275 | &policy.rtcp, (srtp_profile_t)cs) == srtp_err_status_ok)) { |
| 276 | RTC_LOG(LS_ERROR) << "Failed to " << (session_ ? "update" : "create") |
| 277 | << " SRTP session: unsupported cipher_suite " << cs; |
| 278 | return false; |
| 279 | } |
| 280 |
| 281 | if (!key || len != static_cast<size_t>(policy.rtp.cipher_key_len)) { |
| 282 | RTC_LOG(LS_ERROR) << "Failed to " << (session_ ? "update" : "create") |
| 283 | << " SRTP session: invalid key"; |
| 284 | return false; |
| 285 | } |
| 286 |
| 287 | policy.ssrc.type = static_cast<srtp_ssrc_type_t>(type); |
| 288 | policy.ssrc.value = 0; |
| 289 | policy.key = const_cast<uint8_t*>(key); |
| 290 | // TODO(astor) parse window size from WSH session-param |
| 291 | policy.window_size = 1024; |
| 292 | policy.allow_repeat_tx = 1; |
| 293 | // If external authentication option is enabled, supply custom auth module |
| 294 | // id EXTERNAL_HMAC_SHA1 in the policy structure. |
| 295 | // We want to set this option only for rtp packets. |
| 296 | // By default policy structure is initialized to HMAC_SHA1. |
| 297 | // Enable external HMAC authentication only for outgoing streams and only |
| 298 | // for cipher suites that support it (i.e. only non-GCM cipher suites). |
| 299 | if (type == ssrc_any_outbound && IsExternalAuthEnabled() && |
| 300 | !rtc::IsGcmCryptoSuite(cs)) { |
| 301 | policy.rtp.auth_type = EXTERNAL_HMAC_SHA1; |
| 302 | } |
| 303 | if (!extension_ids.empty()) { |
| 304 | policy.enc_xtn_hdr = const_cast<int*>(&extension_ids[0]); |
| 305 | policy.enc_xtn_hdr_count = static_cast<int>(extension_ids.size()); |
| 306 | } |
| 307 | policy.next = nullptr; |
| 308 |
| 309 | if (!session_) { |
| 310 | int err = srtp_create(&session_, &policy); |
| 311 | if (err != srtp_err_status_ok) { |
| 312 | session_ = nullptr; |
| 313 | RTC_LOG(LS_ERROR) << "Failed to create SRTP session, err=" << err; |
| 314 | return false; |
| 315 | } |
| 316 | srtp_set_user_data(session_, this); |
| 317 | } else { |
| 318 | int err = srtp_update(session_, &policy); |
| 319 | if (err != srtp_err_status_ok) { |
| 320 | RTC_LOG(LS_ERROR) << "Failed to update SRTP session, err=" << err; |
| 321 | return false; |
| 322 | } |
| 323 | } |
| 324 |
| 325 | rtp_auth_tag_len_ = policy.rtp.auth_tag_len; |
| 326 | rtcp_auth_tag_len_ = policy.rtcp.auth_tag_len; |
| 327 | external_auth_active_ = (policy.rtp.auth_type == EXTERNAL_HMAC_SHA1); |
| 328 | return true; |
| 329 | } |
| 330 |
| 331 | bool SrtpSession::SetKey(int type, |
| 332 | int cs, |
| 333 | const uint8_t* key, |
| 334 | size_t len, |
| 335 | const std::vector<int>& extension_ids) { |
| 336 | RTC_DCHECK(thread_checker_.IsCurrent()); |
| 337 | if (session_) { |
| 338 | RTC_LOG(LS_ERROR) << "Failed to create SRTP session: " |
| 339 | "SRTP session already created"; |
| 340 | return false; |
| 341 | } |
| 342 |
| 343 | // This is the first time we need to actually interact with libsrtp, so |
| 344 | // initialize it if needed. |
| 345 | if (IncrementLibsrtpUsageCountAndMaybeInit()) { |
| 346 | inited_ = true; |
| 347 | } else { |
| 348 | return false; |
| 349 | } |
| 350 |
| 351 | return DoSetKey(type, cs, key, len, extension_ids); |
| 352 | } |
| 353 |
| 354 | bool SrtpSession::UpdateKey(int type, |
| 355 | int cs, |
| 356 | const uint8_t* key, |
| 357 | size_t len, |
| 358 | const std::vector<int>& extension_ids) { |
| 359 | RTC_DCHECK(thread_checker_.IsCurrent()); |
| 360 | if (!session_) { |
| 361 | RTC_LOG(LS_ERROR) << "Failed to update non-existing SRTP session"; |
| 362 | return false; |
| 363 | } |
| 364 |
| 365 | return DoSetKey(type, cs, key, len, extension_ids); |
| 366 | } |
| 367 |
| 368 | ABSL_CONST_INIT int g_libsrtp_usage_count = 0; |
| 369 | ABSL_CONST_INIT webrtc::GlobalMutex g_libsrtp_lock(absl::kConstInit); |
| 370 |
| 371 | void ProhibitLibsrtpInitialization() { |
| 372 | webrtc::GlobalMutexLock ls(&g_libsrtp_lock); |
| 373 | ++g_libsrtp_usage_count; |
| 374 | } |
| 375 |
| 376 | // static |
| 377 | bool SrtpSession::IncrementLibsrtpUsageCountAndMaybeInit() { |
| 378 | webrtc::GlobalMutexLock ls(&g_libsrtp_lock); |
| 379 |
| 380 | RTC_DCHECK_GE(g_libsrtp_usage_count, 0); |
| 381 | if (g_libsrtp_usage_count == 0) { |
| 382 | int err; |
| 383 | err = srtp_init(); |
| 384 | if (err != srtp_err_status_ok) { |
| 385 | RTC_LOG(LS_ERROR) << "Failed to init SRTP, err=" << err; |
| 386 | return false; |
| 387 | } |
| 388 |
| 389 | err = srtp_install_event_handler(&SrtpSession::HandleEventThunk); |
| 390 | if (err != srtp_err_status_ok) { |
| 391 | RTC_LOG(LS_ERROR) << "Failed to install SRTP event handler, err=" << err; |
| 392 | return false; |
| 393 | } |
| 394 |
| 395 | err = external_crypto_init(); |
| 396 | if (err != srtp_err_status_ok) { |
| 397 | RTC_LOG(LS_ERROR) << "Failed to initialize fake auth, err=" << err; |
| 398 | return false; |
| 399 | } |
| 400 | } |
| 401 | ++g_libsrtp_usage_count; |
| 402 | return true; |
| 403 | } |
| 404 |
| 405 | // static |
| 406 | void SrtpSession::DecrementLibsrtpUsageCountAndMaybeDeinit() { |
| 407 | webrtc::GlobalMutexLock ls(&g_libsrtp_lock); |
| 408 |
| 409 | RTC_DCHECK_GE(g_libsrtp_usage_count, 1); |
| 410 | if (--g_libsrtp_usage_count == 0) { |
| 411 | int err = srtp_shutdown(); |
| 412 | if (err) { |
| 413 | RTC_LOG(LS_ERROR) << "srtp_shutdown failed. err=" << err; |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 |
| 418 | void SrtpSession::HandleEvent(const srtp_event_data_t* ev) { |
| 419 | RTC_DCHECK(thread_checker_.IsCurrent()); |
| 420 | switch (ev->event) { |
| 421 | case event_ssrc_collision: |
| 422 | RTC_LOG(LS_INFO) << "SRTP event: SSRC collision"; |
| 423 | break; |
| 424 | case event_key_soft_limit: |
| 425 | RTC_LOG(LS_INFO) << "SRTP event: reached soft key usage limit"; |
| 426 | break; |
| 427 | case event_key_hard_limit: |
| 428 | RTC_LOG(LS_INFO) << "SRTP event: reached hard key usage limit"; |
| 429 | break; |
| 430 | case event_packet_index_limit: |
| 431 | RTC_LOG(LS_INFO) |
| 432 | << "SRTP event: reached hard packet limit (2^48 packets)"; |
| 433 | break; |
| 434 | default: |
| 435 | RTC_LOG(LS_INFO) << "SRTP event: unknown " << ev->event; |
| 436 | break; |
| 437 | } |
| 438 | } |
| 439 |
| 440 | void SrtpSession::HandleEventThunk(srtp_event_data_t* ev) { |
| 441 | // Callback will be executed from same thread that calls the "srtp_protect" |
| 442 | // and "srtp_unprotect" functions. |
| 443 | SrtpSession* session = |
| 444 | static_cast<SrtpSession*>(srtp_get_user_data(ev->session)); |
| 445 | if (session) { |
| 446 | session->HandleEvent(ev); |
| 447 | } |
| 448 | } |
| 449 |
| 450 | // Logs the unencrypted packet in text2pcap format. This can then be |
| 451 | // extracted by searching for RTP_DUMP |
| 452 | // grep RTP_DUMP chrome_debug.log > in.txt |
| 453 | // and converted to pcap using |
| 454 | // text2pcap -D -u 1000,2000 -t %H:%M:%S. in.txt out.pcap |
| 455 | // The resulting file can be replayed using the WebRTC video_replay tool and |
| 456 | // be inspected in Wireshark using the RTP, VP8 and H264 dissectors. |
| 457 | void SrtpSession::DumpPacket(const void* buf, int len, bool outbound) { |
| 458 | int64_t time_of_day = rtc::TimeUTCMillis() % (24 * 3600 * 1000); |
| 459 | int64_t hours = time_of_day / (3600 * 1000); |
| 460 | int64_t minutes = (time_of_day / (60 * 1000)) % 60; |
| 461 | int64_t seconds = (time_of_day / 1000) % 60; |
| 462 | int64_t millis = time_of_day % 1000; |
| 463 | RTC_LOG(LS_VERBOSE) << "\n" << (outbound ? "O" : "I") << " " |
| 464 | << std::setfill('0') << std::setw(2) << hours << ":" |
| 465 | << std::setfill('0') << std::setw(2) << minutes << ":" |
| 466 | << std::setfill('0') << std::setw(2) << seconds << "." |
| 467 | << std::setfill('0') << std::setw(3) << millis << " " |
| 468 | << "000000 " << rtc::hex_encode_with_delimiter((const char *)buf, len, ' ') |
| 469 | << " # RTP_DUMP"; |
| 470 | } |
| 471 |
| 472 | } // namespace cricket |
| 473 |