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