| 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 "p2p/base/turn_server.h" |
| 12 |
| 13 | #include <algorithm> |
| 14 | #include <memory> |
| 15 | #include <tuple> // for std::tie |
| 16 | #include <utility> |
| 17 |
| 18 | #include "absl/algorithm/container.h" |
| 19 | #include "absl/memory/memory.h" |
| 20 | #include "absl/strings/string_view.h" |
| 21 | #include "api/array_view.h" |
| 22 | #include "api/packet_socket_factory.h" |
| 23 | #include "api/task_queue/task_queue_base.h" |
| 24 | #include "api/transport/stun.h" |
| 25 | #include "p2p/base/async_stun_tcp_socket.h" |
| 26 | #include "rtc_base/byte_buffer.h" |
| 27 | #include "rtc_base/checks.h" |
| 28 | #include "rtc_base/helpers.h" |
| 29 | #include "rtc_base/logging.h" |
| 30 | #include "rtc_base/message_digest.h" |
| 31 | #include "rtc_base/socket_adapters.h" |
| 32 | #include "rtc_base/strings/string_builder.h" |
| 33 |
| 34 | namespace cricket { |
| 35 | namespace { |
| 36 | using ::webrtc::TimeDelta; |
| 37 |
| 38 | // TODO(juberti): Move this all to a future turnmessage.h |
| 39 | // static const int IPPROTO_UDP = 17; |
| 40 | constexpr TimeDelta kNonceTimeout = TimeDelta::Minutes(60); |
| 41 | constexpr TimeDelta kDefaultAllocationTimeout = TimeDelta::Minutes(10); |
| 42 | constexpr TimeDelta kPermissionTimeout = TimeDelta::Minutes(5); |
| 43 | constexpr TimeDelta kChannelTimeout = TimeDelta::Minutes(10); |
| 44 |
| 45 | constexpr int kMinChannelNumber = 0x4000; |
| 46 | constexpr int kMaxChannelNumber = 0x7FFF; |
| 47 |
| 48 | constexpr size_t kNonceKeySize = 16; |
| 49 | constexpr size_t kNonceSize = 48; |
| 50 |
| 51 | constexpr size_t TURN_CHANNEL_HEADER_SIZE = 4U; |
| 52 |
| 53 | // TODO(mallinath) - Move these to a common place. |
| 54 | bool IsTurnChannelData(uint16_t msg_type) { |
| 55 | // The first two bits of a channel data message are 0b01. |
| 56 | return ((msg_type & 0xC000) == 0x4000); |
| 57 | } |
| 58 |
| 59 | } // namespace |
| 60 |
| 61 | int GetStunSuccessResponseTypeOrZero(const StunMessage& req) { |
| 62 | const int resp_type = GetStunSuccessResponseType(req.type()); |
| 63 | return resp_type == -1 ? 0 : resp_type; |
| 64 | } |
| 65 |
| 66 | int GetStunErrorResponseTypeOrZero(const StunMessage& req) { |
| 67 | const int resp_type = GetStunErrorResponseType(req.type()); |
| 68 | return resp_type == -1 ? 0 : resp_type; |
| 69 | } |
| 70 |
| 71 | static void InitErrorResponse(int code, |
| 72 | absl::string_view reason, |
| 73 | StunMessage* resp) { |
| 74 | resp->AddAttribute(std::make_unique<cricket::StunErrorCodeAttribute>( |
| 75 | STUN_ATTR_ERROR_CODE, code, std::string(reason))); |
| 76 | } |
| 77 |
| 78 | TurnServer::TurnServer(webrtc::TaskQueueBase* thread) |
| 79 | : thread_(thread), |
| 80 | nonce_key_(rtc::CreateRandomString(kNonceKeySize)), |
| 81 | auth_hook_(NULL), |
| 82 | redirect_hook_(NULL), |
| 83 | enable_otu_nonce_(false) {} |
| 84 |
| 85 | TurnServer::~TurnServer() { |
| 86 | RTC_DCHECK_RUN_ON(thread_); |
| 87 | for (InternalSocketMap::iterator it = server_sockets_.begin(); |
| 88 | it != server_sockets_.end(); ++it) { |
| 89 | rtc::AsyncPacketSocket* socket = it->first; |
| 90 | delete socket; |
| 91 | } |
| 92 |
| 93 | for (ServerSocketMap::iterator it = server_listen_sockets_.begin(); |
| 94 | it != server_listen_sockets_.end(); ++it) { |
| 95 | rtc::Socket* socket = it->first; |
| 96 | delete socket; |
| 97 | } |
| 98 | } |
| 99 |
| 100 | void TurnServer::AddInternalSocket(rtc::AsyncPacketSocket* socket, |
| 101 | ProtocolType proto) { |
| 102 | RTC_DCHECK_RUN_ON(thread_); |
| 103 | RTC_DCHECK(server_sockets_.end() == server_sockets_.find(socket)); |
| 104 | server_sockets_[socket] = proto; |
| 105 | socket->RegisterReceivedPacketCallback( |
| 106 | [&](rtc::AsyncPacketSocket* socket, const rtc::ReceivedPacket& packet) { |
| 107 | RTC_DCHECK_RUN_ON(thread_); |
| 108 | OnInternalPacket(socket, packet); |
| 109 | }); |
| 110 | } |
| 111 |
| 112 | void TurnServer::AddInternalServerSocket( |
| 113 | rtc::Socket* socket, |
| 114 | ProtocolType proto, |
| 115 | std::unique_ptr<rtc::SSLAdapterFactory> ssl_adapter_factory) { |
| 116 | RTC_DCHECK_RUN_ON(thread_); |
| 117 |
| 118 | RTC_DCHECK(server_listen_sockets_.end() == |
| 119 | server_listen_sockets_.find(socket)); |
| 120 | server_listen_sockets_[socket] = {proto, std::move(ssl_adapter_factory)}; |
| 121 | socket->SignalReadEvent.connect(this, &TurnServer::OnNewInternalConnection); |
| 122 | } |
| 123 |
| 124 | void TurnServer::SetExternalSocketFactory( |
| 125 | rtc::PacketSocketFactory* factory, |
| 126 | const rtc::SocketAddress& external_addr) { |
| 127 | RTC_DCHECK_RUN_ON(thread_); |
| 128 | external_socket_factory_.reset(factory); |
| 129 | external_addr_ = external_addr; |
| 130 | } |
| 131 |
| 132 | void TurnServer::OnNewInternalConnection(rtc::Socket* socket) { |
| 133 | RTC_DCHECK_RUN_ON(thread_); |
| 134 | RTC_DCHECK(server_listen_sockets_.find(socket) != |
| 135 | server_listen_sockets_.end()); |
| 136 | AcceptConnection(socket); |
| 137 | } |
| 138 |
| 139 | void TurnServer::AcceptConnection(rtc::Socket* server_socket) { |
| 140 | // Check if someone is trying to connect to us. |
| 141 | rtc::SocketAddress accept_addr; |
| 142 | rtc::Socket* accepted_socket = server_socket->Accept(&accept_addr); |
| 143 | if (accepted_socket != NULL) { |
| 144 | const ServerSocketInfo& info = server_listen_sockets_[server_socket]; |
| 145 | if (info.ssl_adapter_factory) { |
| 146 | rtc::SSLAdapter* ssl_adapter = |
| 147 | info.ssl_adapter_factory->CreateAdapter(accepted_socket); |
| 148 | ssl_adapter->StartSSL(""); |
| 149 | accepted_socket = ssl_adapter; |
| 150 | } |
| 151 | cricket::AsyncStunTCPSocket* tcp_socket = |
| 152 | new cricket::AsyncStunTCPSocket(accepted_socket); |
| 153 |
| 154 | tcp_socket->SubscribeCloseEvent(this, |
| 155 | [this](rtc::AsyncPacketSocket* s, int err) { |
| 156 | OnInternalSocketClose(s, err); |
| 157 | }); |
| 158 | // Finally add the socket so it can start communicating with the client. |
| 159 | AddInternalSocket(tcp_socket, info.proto); |
| 160 | } |
| 161 | } |
| 162 |
| 163 | void TurnServer::OnInternalSocketClose(rtc::AsyncPacketSocket* socket, |
| 164 | int err) { |
| 165 | RTC_DCHECK_RUN_ON(thread_); |
| 166 | DestroyInternalSocket(socket); |
| 167 | } |
| 168 |
| 169 | void TurnServer::OnInternalPacket(rtc::AsyncPacketSocket* socket, |
| 170 | const rtc::ReceivedPacket& packet) { |
| 171 | RTC_DCHECK_RUN_ON(thread_); |
| 172 | // Fail if the packet is too small to even contain a channel header. |
| 173 | if (packet.payload().size() < TURN_CHANNEL_HEADER_SIZE) { |
| 174 | return; |
| 175 | } |
| 176 | InternalSocketMap::iterator iter = server_sockets_.find(socket); |
| 177 | RTC_DCHECK(iter != server_sockets_.end()); |
| 178 | TurnServerConnection conn(packet.source_address(), iter->second, socket); |
| 179 | uint16_t msg_type = rtc::GetBE16(packet.payload().data()); |
| 180 | if (!IsTurnChannelData(msg_type)) { |
| 181 | // This is a STUN message. |
| 182 | HandleStunMessage(&conn, packet.payload()); |
| 183 | } else { |
| 184 | // This is a channel message; let the allocation handle it. |
| 185 | TurnServerAllocation* allocation = FindAllocation(&conn); |
| 186 | if (allocation) { |
| 187 | allocation->HandleChannelData(packet.payload()); |
| 188 | } |
| 189 | if (stun_message_observer_ != nullptr) { |
| 190 | stun_message_observer_->ReceivedChannelData(packet.payload()); |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 |
| 195 | void TurnServer::HandleStunMessage(TurnServerConnection* conn, |
| 196 | rtc::ArrayView<const uint8_t> payload) { |
| 197 | TurnMessage msg; |
| 198 | rtc::ByteBufferReader buf(payload); |
| 199 | if (!msg.Read(&buf) || (buf.Length() > 0)) { |
| 200 | RTC_LOG(LS_WARNING) << "Received invalid STUN message"; |
| 201 | return; |
| 202 | } |
| 203 |
| 204 | if (stun_message_observer_ != nullptr) { |
| 205 | stun_message_observer_->ReceivedMessage(&msg); |
| 206 | } |
| 207 |
| 208 | // If it's a STUN binding request, handle that specially. |
| 209 | if (msg.type() == STUN_BINDING_REQUEST) { |
| 210 | HandleBindingRequest(conn, &msg); |
| 211 | return; |
| 212 | } |
| 213 |
| 214 | if (redirect_hook_ != NULL && msg.type() == STUN_ALLOCATE_REQUEST) { |
| 215 | rtc::SocketAddress address; |
| 216 | if (redirect_hook_->ShouldRedirect(conn->src(), &address)) { |
| 217 | SendErrorResponseWithAlternateServer(conn, &msg, address); |
| 218 | return; |
| 219 | } |
| 220 | } |
| 221 |
| 222 | // Look up the key that we'll use to validate the M-I. If we have an |
| 223 | // existing allocation, the key will already be cached. |
| 224 | TurnServerAllocation* allocation = FindAllocation(conn); |
| 225 | std::string key; |
| 226 | if (!allocation) { |
| 227 | GetKey(&msg, &key); |
| 228 | } else { |
| 229 | key = allocation->key(); |
| 230 | } |
| 231 |
| 232 | // Ensure the message is authorized; only needed for requests. |
| 233 | if (IsStunRequestType(msg.type())) { |
| 234 | if (!CheckAuthorization(conn, &msg, key)) { |
| 235 | return; |
| 236 | } |
| 237 | } |
| 238 |
| 239 | if (!allocation && msg.type() == STUN_ALLOCATE_REQUEST) { |
| 240 | HandleAllocateRequest(conn, &msg, key); |
| 241 | } else if (allocation && |
| 242 | (msg.type() != STUN_ALLOCATE_REQUEST || |
| 243 | msg.transaction_id() == allocation->transaction_id())) { |
| 244 | // This is a non-allocate request, or a retransmit of an allocate. |
| 245 | // Check that the username matches the previous username used. |
| 246 | if (IsStunRequestType(msg.type()) && |
| 247 | msg.GetByteString(STUN_ATTR_USERNAME)->string_view() != |
| 248 | allocation->username()) { |
| 249 | SendErrorResponse(conn, &msg, STUN_ERROR_WRONG_CREDENTIALS, |
| 250 | STUN_ERROR_REASON_WRONG_CREDENTIALS); |
| 251 | return; |
| 252 | } |
| 253 | allocation->HandleTurnMessage(&msg); |
| 254 | } else { |
| 255 | // Allocation mismatch. |
| 256 | SendErrorResponse(conn, &msg, STUN_ERROR_ALLOCATION_MISMATCH, |
| 257 | STUN_ERROR_REASON_ALLOCATION_MISMATCH); |
| 258 | } |
| 259 | } |
| 260 |
| 261 | bool TurnServer::GetKey(const StunMessage* msg, std::string* key) { |
| 262 | const StunByteStringAttribute* username_attr = |
| 263 | msg->GetByteString(STUN_ATTR_USERNAME); |
| 264 | if (!username_attr) { |
| 265 | return false; |
| 266 | } |
| 267 |
| 268 | return (auth_hook_ != NULL && |
| 269 | auth_hook_->GetKey(std::string(username_attr->string_view()), realm_, |
| 270 | key)); |
| 271 | } |
| 272 |
| 273 | bool TurnServer::CheckAuthorization(TurnServerConnection* conn, |
| 274 | StunMessage* msg, |
| 275 | absl::string_view key) { |
| 276 | // RFC 5389, 10.2.2. |
| 277 | RTC_DCHECK(IsStunRequestType(msg->type())); |
| 278 | const StunByteStringAttribute* mi_attr = |
| 279 | msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY); |
| 280 | const StunByteStringAttribute* username_attr = |
| 281 | msg->GetByteString(STUN_ATTR_USERNAME); |
| 282 | const StunByteStringAttribute* realm_attr = |
| 283 | msg->GetByteString(STUN_ATTR_REALM); |
| 284 | const StunByteStringAttribute* nonce_attr = |
| 285 | msg->GetByteString(STUN_ATTR_NONCE); |
| 286 |
| 287 | // Fail if no MESSAGE_INTEGRITY. |
| 288 | if (!mi_attr) { |
| 289 | SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_UNAUTHORIZED, |
| 290 | STUN_ERROR_REASON_UNAUTHORIZED); |
| 291 | return false; |
| 292 | } |
| 293 |
| 294 | // Fail if there is MESSAGE_INTEGRITY but no username, nonce, or realm. |
| 295 | if (!username_attr || !realm_attr || !nonce_attr) { |
| 296 | SendErrorResponse(conn, msg, STUN_ERROR_BAD_REQUEST, |
| 297 | STUN_ERROR_REASON_BAD_REQUEST); |
| 298 | return false; |
| 299 | } |
| 300 |
| 301 | // Fail if bad nonce. |
| 302 | if (!ValidateNonce(nonce_attr->string_view())) { |
| 303 | SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_STALE_NONCE, |
| 304 | STUN_ERROR_REASON_STALE_NONCE); |
| 305 | return false; |
| 306 | } |
| 307 |
| 308 | // Fail if bad MESSAGE_INTEGRITY. |
| 309 | if (key.empty() || msg->ValidateMessageIntegrity(std::string(key)) != |
| 310 | StunMessage::IntegrityStatus::kIntegrityOk) { |
| 311 | SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_UNAUTHORIZED, |
| 312 | STUN_ERROR_REASON_UNAUTHORIZED); |
| 313 | return false; |
| 314 | } |
| 315 |
| 316 | // Fail if one-time-use nonce feature is enabled. |
| 317 | TurnServerAllocation* allocation = FindAllocation(conn); |
| 318 | if (enable_otu_nonce_ && allocation && |
| 319 | allocation->last_nonce() == nonce_attr->string_view()) { |
| 320 | SendErrorResponseWithRealmAndNonce(conn, msg, STUN_ERROR_STALE_NONCE, |
| 321 | STUN_ERROR_REASON_STALE_NONCE); |
| 322 | return false; |
| 323 | } |
| 324 |
| 325 | if (allocation) { |
| 326 | allocation->set_last_nonce(nonce_attr->string_view()); |
| 327 | } |
| 328 | // Success. |
| 329 | return true; |
| 330 | } |
| 331 |
| 332 | void TurnServer::HandleBindingRequest(TurnServerConnection* conn, |
| 333 | const StunMessage* req) { |
| 334 | StunMessage response(GetStunSuccessResponseTypeOrZero(*req), |
| 335 | req->transaction_id()); |
| 336 | // Tell the user the address that we received their request from. |
| 337 | auto mapped_addr_attr = std::make_unique<StunXorAddressAttribute>( |
| 338 | STUN_ATTR_XOR_MAPPED_ADDRESS, conn->src()); |
| 339 | response.AddAttribute(std::move(mapped_addr_attr)); |
| 340 |
| 341 | SendStun(conn, &response); |
| 342 | } |
| 343 |
| 344 | void TurnServer::HandleAllocateRequest(TurnServerConnection* conn, |
| 345 | const TurnMessage* msg, |
| 346 | absl::string_view key) { |
| 347 | // Check the parameters in the request. |
| 348 | const StunUInt32Attribute* transport_attr = |
| 349 | msg->GetUInt32(STUN_ATTR_REQUESTED_TRANSPORT); |
| 350 | if (!transport_attr) { |
| 351 | SendErrorResponse(conn, msg, STUN_ERROR_BAD_REQUEST, |
| 352 | STUN_ERROR_REASON_BAD_REQUEST); |
| 353 | return; |
| 354 | } |
| 355 |
| 356 | // Only UDP is supported right now. |
| 357 | int proto = transport_attr->value() >> 24; |
| 358 | if (proto != IPPROTO_UDP) { |
| 359 | SendErrorResponse(conn, msg, STUN_ERROR_UNSUPPORTED_PROTOCOL, |
| 360 | STUN_ERROR_REASON_UNSUPPORTED_PROTOCOL); |
| 361 | return; |
| 362 | } |
| 363 |
| 364 | // Create the allocation and let it send the success response. |
| 365 | // If the actual socket allocation fails, send an internal error. |
| 366 | TurnServerAllocation* alloc = CreateAllocation(conn, proto, key); |
| 367 | if (alloc) { |
| 368 | alloc->HandleTurnMessage(msg); |
| 369 | } else { |
| 370 | SendErrorResponse(conn, msg, STUN_ERROR_SERVER_ERROR, |
| 371 | "Failed to allocate socket"); |
| 372 | } |
| 373 | } |
| 374 |
| 375 | std::string TurnServer::GenerateNonce(int64_t now) const { |
| 376 | // Generate a nonce of the form hex(now + HMAC-MD5(nonce_key_, now)) |
| 377 | std::string input(reinterpret_cast<const char*>(&now), sizeof(now)); |
| 378 | std::string nonce = rtc::hex_encode(input); |
| 379 | nonce += rtc::ComputeHmac(rtc::DIGEST_MD5, nonce_key_, input); |
| 380 | RTC_DCHECK(nonce.size() == kNonceSize); |
| 381 |
| 382 | return nonce; |
| 383 | } |
| 384 |
| 385 | bool TurnServer::ValidateNonce(absl::string_view nonce) const { |
| 386 | // Check the size. |
| 387 | if (nonce.size() != kNonceSize) { |
| 388 | return false; |
| 389 | } |
| 390 |
| 391 | // Decode the timestamp. |
| 392 | int64_t then; |
| 393 | char* p = reinterpret_cast<char*>(&then); |
| 394 | size_t len = rtc::hex_decode(rtc::ArrayView<char>(p, sizeof(then)), |
| 395 | nonce.substr(0, sizeof(then) * 2)); |
| 396 | if (len != sizeof(then)) { |
| 397 | return false; |
| 398 | } |
| 399 |
| 400 | // Verify the HMAC. |
| 401 | if (nonce.substr(sizeof(then) * 2) != |
| 402 | rtc::ComputeHmac(rtc::DIGEST_MD5, nonce_key_, |
| 403 | std::string(p, sizeof(then)))) { |
| 404 | return false; |
| 405 | } |
| 406 |
| 407 | // Validate the timestamp. |
| 408 | return TimeDelta::Millis(rtc::TimeMillis() - then) < kNonceTimeout; |
| 409 | } |
| 410 |
| 411 | TurnServerAllocation* TurnServer::FindAllocation(TurnServerConnection* conn) { |
| 412 | AllocationMap::const_iterator it = allocations_.find(*conn); |
| 413 | return (it != allocations_.end()) ? it->second.get() : nullptr; |
| 414 | } |
| 415 |
| 416 | TurnServerAllocation* TurnServer::CreateAllocation(TurnServerConnection* conn, |
| 417 | int proto, |
| 418 | absl::string_view key) { |
| 419 | rtc::AsyncPacketSocket* external_socket = |
| 420 | (external_socket_factory_) |
| 421 | ? external_socket_factory_->CreateUdpSocket(external_addr_, 0, 0) |
| 422 | : NULL; |
| 423 | if (!external_socket) { |
| 424 | return NULL; |
| 425 | } |
| 426 |
| 427 | // The Allocation takes ownership of the socket. |
| 428 | TurnServerAllocation* allocation = |
| 429 | new TurnServerAllocation(this, thread_, *conn, external_socket, key); |
| 430 | allocations_[*conn].reset(allocation); |
| 431 | return allocation; |
| 432 | } |
| 433 |
| 434 | void TurnServer::SendErrorResponse(TurnServerConnection* conn, |
| 435 | const StunMessage* req, |
| 436 | int code, |
| 437 | absl::string_view reason) { |
| 438 | RTC_DCHECK_RUN_ON(thread_); |
| 439 | TurnMessage resp(GetStunErrorResponseTypeOrZero(*req), req->transaction_id()); |
| 440 | InitErrorResponse(code, reason, &resp); |
| 441 |
| 442 | RTC_LOG(LS_INFO) << "Sending error response, type=" << resp.type() |
| 443 | << ", code=" << code << ", reason=" << reason; |
| 444 | SendStun(conn, &resp); |
| 445 | } |
| 446 |
| 447 | void TurnServer::SendErrorResponseWithRealmAndNonce(TurnServerConnection* conn, |
| 448 | const StunMessage* msg, |
| 449 | int code, |
| 450 | absl::string_view reason) { |
| 451 | TurnMessage resp(GetStunErrorResponseTypeOrZero(*msg), msg->transaction_id()); |
| 452 | InitErrorResponse(code, reason, &resp); |
| 453 |
| 454 | int64_t timestamp = rtc::TimeMillis(); |
| 455 | if (ts_for_next_nonce_) { |
| 456 | timestamp = ts_for_next_nonce_; |
| 457 | ts_for_next_nonce_ = 0; |
| 458 | } |
| 459 | resp.AddAttribute(std::make_unique<StunByteStringAttribute>( |
| 460 | STUN_ATTR_NONCE, GenerateNonce(timestamp))); |
| 461 | resp.AddAttribute( |
| 462 | std::make_unique<StunByteStringAttribute>(STUN_ATTR_REALM, realm_)); |
| 463 | SendStun(conn, &resp); |
| 464 | } |
| 465 |
| 466 | void TurnServer::SendErrorResponseWithAlternateServer( |
| 467 | TurnServerConnection* conn, |
| 468 | const StunMessage* msg, |
| 469 | const rtc::SocketAddress& addr) { |
| 470 | TurnMessage resp(GetStunErrorResponseTypeOrZero(*msg), msg->transaction_id()); |
| 471 | InitErrorResponse(STUN_ERROR_TRY_ALTERNATE, |
| 472 | STUN_ERROR_REASON_TRY_ALTERNATE_SERVER, &resp); |
| 473 | resp.AddAttribute( |
| 474 | std::make_unique<StunAddressAttribute>(STUN_ATTR_ALTERNATE_SERVER, addr)); |
| 475 | SendStun(conn, &resp); |
| 476 | } |
| 477 |
| 478 | void TurnServer::SendStun(TurnServerConnection* conn, StunMessage* msg) { |
| 479 | RTC_DCHECK_RUN_ON(thread_); |
| 480 | rtc::ByteBufferWriter buf; |
| 481 | // Add a SOFTWARE attribute if one is set. |
| 482 | if (!software_.empty()) { |
| 483 | msg->AddAttribute(std::make_unique<StunByteStringAttribute>( |
| 484 | STUN_ATTR_SOFTWARE, software_)); |
| 485 | } |
| 486 | msg->Write(&buf); |
| 487 | Send(conn, buf); |
| 488 | } |
| 489 |
| 490 | void TurnServer::Send(TurnServerConnection* conn, |
| 491 | const rtc::ByteBufferWriter& buf) { |
| 492 | RTC_DCHECK_RUN_ON(thread_); |
| 493 | rtc::PacketOptions options; |
| 494 | conn->socket()->SendTo(buf.Data(), buf.Length(), conn->src(), options); |
| 495 | } |
| 496 |
| 497 | void TurnServer::DestroyAllocation(TurnServerAllocation* allocation) { |
| 498 | // Removing the internal socket if the connection is not udp. |
| 499 | rtc::AsyncPacketSocket* socket = allocation->conn()->socket(); |
| 500 | InternalSocketMap::iterator iter = server_sockets_.find(socket); |
| 501 | // Skip if the socket serving this allocation is UDP, as this will be shared |
| 502 | // by all allocations. |
| 503 | // Note: We may not find a socket if it's a TCP socket that was closed, and |
| 504 | // the allocation is only now timing out. |
| 505 | if (iter != server_sockets_.end() && iter->second != cricket::PROTO_UDP) { |
| 506 | DestroyInternalSocket(socket); |
| 507 | } |
| 508 |
| 509 | allocations_.erase(*(allocation->conn())); |
| 510 | } |
| 511 |
| 512 | void TurnServer::DestroyInternalSocket(rtc::AsyncPacketSocket* socket) { |
| 513 | InternalSocketMap::iterator iter = server_sockets_.find(socket); |
| 514 | if (iter != server_sockets_.end()) { |
| 515 | rtc::AsyncPacketSocket* socket = iter->first; |
| 516 | socket->UnsubscribeCloseEvent(this); |
| 517 | socket->DeregisterReceivedPacketCallback(); |
| 518 | server_sockets_.erase(iter); |
| 519 | std::unique_ptr<rtc::AsyncPacketSocket> socket_to_delete = |
| 520 | absl::WrapUnique(socket); |
| 521 | // We must destroy the socket async to avoid invalidating the sigslot |
| 522 | // callback list iterator inside a sigslot callback. (In other words, |
| 523 | // deleting an object from within a callback from that object). |
| 524 | thread_->PostTask([socket_to_delete = std::move(socket_to_delete)] {}); |
| 525 | } |
| 526 | } |
| 527 |
| 528 | TurnServerConnection::TurnServerConnection(const rtc::SocketAddress& src, |
| 529 | ProtocolType proto, |
| 530 | rtc::AsyncPacketSocket* socket) |
| 531 | : src_(src), |
| 532 | dst_(socket->GetRemoteAddress()), |
| 533 | proto_(proto), |
| 534 | socket_(socket) {} |
| 535 |
| 536 | bool TurnServerConnection::operator==(const TurnServerConnection& c) const { |
| 537 | return src_ == c.src_ && dst_ == c.dst_ && proto_ == c.proto_; |
| 538 | } |
| 539 |
| 540 | bool TurnServerConnection::operator<(const TurnServerConnection& c) const { |
| 541 | return std::tie(src_, dst_, proto_) < std::tie(c.src_, c.dst_, c.proto_); |
| 542 | } |
| 543 |
| 544 | std::string TurnServerConnection::ToString() const { |
| 545 | const char* const kProtos[] = {"unknown", "udp", "tcp", "ssltcp"}; |
| 546 | rtc::StringBuilder ost; |
| 547 | ost << src_.ToSensitiveString() << "-" << dst_.ToSensitiveString() << ":" |
| 548 | << kProtos[proto_]; |
| 549 | return ost.Release(); |
| 550 | } |
| 551 |
| 552 | TurnServerAllocation::TurnServerAllocation(TurnServer* server, |
| 553 | webrtc::TaskQueueBase* thread, |
| 554 | const TurnServerConnection& conn, |
| 555 | rtc::AsyncPacketSocket* socket, |
| 556 | absl::string_view key) |
| 557 | : server_(server), |
| 558 | thread_(thread), |
| 559 | conn_(conn), |
| 560 | external_socket_(socket), |
| 561 | key_(key) { |
| 562 | external_socket_->RegisterReceivedPacketCallback( |
| 563 | [&](rtc::AsyncPacketSocket* socket, const rtc::ReceivedPacket& packet) { |
| 564 | RTC_DCHECK_RUN_ON(thread_); |
| 565 | OnExternalPacket(socket, packet); |
| 566 | }); |
| 567 | } |
| 568 |
| 569 | TurnServerAllocation::~TurnServerAllocation() { |
| 570 | channels_.clear(); |
| 571 | perms_.clear(); |
| 572 | RTC_LOG(LS_INFO) << ToString() << ": Allocation destroyed"; |
| 573 | } |
| 574 |
| 575 | std::string TurnServerAllocation::ToString() const { |
| 576 | rtc::StringBuilder ost; |
| 577 | ost << "Alloc[" << conn_.ToString() << "]"; |
| 578 | return ost.Release(); |
| 579 | } |
| 580 |
| 581 | void TurnServerAllocation::HandleTurnMessage(const TurnMessage* msg) { |
| 582 | RTC_DCHECK(msg != NULL); |
| 583 | switch (msg->type()) { |
| 584 | case STUN_ALLOCATE_REQUEST: |
| 585 | HandleAllocateRequest(msg); |
| 586 | break; |
| 587 | case TURN_REFRESH_REQUEST: |
| 588 | HandleRefreshRequest(msg); |
| 589 | break; |
| 590 | case TURN_SEND_INDICATION: |
| 591 | HandleSendIndication(msg); |
| 592 | break; |
| 593 | case TURN_CREATE_PERMISSION_REQUEST: |
| 594 | HandleCreatePermissionRequest(msg); |
| 595 | break; |
| 596 | case TURN_CHANNEL_BIND_REQUEST: |
| 597 | HandleChannelBindRequest(msg); |
| 598 | break; |
| 599 | default: |
| 600 | // Not sure what to do with this, just eat it. |
| 601 | RTC_LOG(LS_WARNING) << ToString() |
| 602 | << ": Invalid TURN message type received: " |
| 603 | << msg->type(); |
| 604 | } |
| 605 | } |
| 606 |
| 607 | void TurnServerAllocation::HandleAllocateRequest(const TurnMessage* msg) { |
| 608 | // Copy the important info from the allocate request. |
| 609 | transaction_id_ = msg->transaction_id(); |
| 610 | const StunByteStringAttribute* username_attr = |
| 611 | msg->GetByteString(STUN_ATTR_USERNAME); |
| 612 | RTC_DCHECK(username_attr != NULL); |
| 613 | username_ = std::string(username_attr->string_view()); |
| 614 |
| 615 | // Figure out the lifetime and start the allocation timer. |
| 616 | TimeDelta lifetime = ComputeLifetime(*msg); |
| 617 | PostDeleteSelf(lifetime); |
| 618 |
| 619 | RTC_LOG(LS_INFO) << ToString() << ": Created allocation with lifetime=" |
| 620 | << lifetime.seconds(); |
| 621 |
| 622 | // We've already validated all the important bits; just send a response here. |
| 623 | TurnMessage response(GetStunSuccessResponseTypeOrZero(*msg), |
| 624 | msg->transaction_id()); |
| 625 |
| 626 | auto mapped_addr_attr = std::make_unique<StunXorAddressAttribute>( |
| 627 | STUN_ATTR_XOR_MAPPED_ADDRESS, conn_.src()); |
| 628 | auto relayed_addr_attr = std::make_unique<StunXorAddressAttribute>( |
| 629 | STUN_ATTR_XOR_RELAYED_ADDRESS, external_socket_->GetLocalAddress()); |
| 630 | auto lifetime_attr = std::make_unique<StunUInt32Attribute>( |
| 631 | STUN_ATTR_LIFETIME, lifetime.seconds()); |
| 632 | response.AddAttribute(std::move(mapped_addr_attr)); |
| 633 | response.AddAttribute(std::move(relayed_addr_attr)); |
| 634 | response.AddAttribute(std::move(lifetime_attr)); |
| 635 |
| 636 | SendResponse(&response); |
| 637 | } |
| 638 |
| 639 | void TurnServerAllocation::HandleRefreshRequest(const TurnMessage* msg) { |
| 640 | // Figure out the new lifetime. |
| 641 | TimeDelta lifetime = ComputeLifetime(*msg); |
| 642 |
| 643 | // Reset the expiration timer. |
| 644 | safety_.reset(); |
| 645 | PostDeleteSelf(lifetime); |
| 646 |
| 647 | RTC_LOG(LS_INFO) << ToString() |
| 648 | << ": Refreshed allocation, lifetime=" << lifetime.seconds(); |
| 649 |
| 650 | // Send a success response with a LIFETIME attribute. |
| 651 | TurnMessage response(GetStunSuccessResponseTypeOrZero(*msg), |
| 652 | msg->transaction_id()); |
| 653 |
| 654 | auto lifetime_attr = std::make_unique<StunUInt32Attribute>( |
| 655 | STUN_ATTR_LIFETIME, lifetime.seconds()); |
| 656 | response.AddAttribute(std::move(lifetime_attr)); |
| 657 |
| 658 | SendResponse(&response); |
| 659 | } |
| 660 |
| 661 | void TurnServerAllocation::HandleSendIndication(const TurnMessage* msg) { |
| 662 | // Check mandatory attributes. |
| 663 | const StunByteStringAttribute* data_attr = msg->GetByteString(STUN_ATTR_DATA); |
| 664 | const StunAddressAttribute* peer_attr = |
| 665 | msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS); |
| 666 | if (!data_attr || !peer_attr) { |
| 667 | RTC_LOG(LS_WARNING) << ToString() << ": Received invalid send indication"; |
| 668 | return; |
| 669 | } |
| 670 |
| 671 | // If a permission exists, send the data on to the peer. |
| 672 | if (HasPermission(peer_attr->GetAddress().ipaddr())) { |
| 673 | SendExternal(reinterpret_cast<char*>(data_attr->array_view().data()), |
| 674 | data_attr->length(), peer_attr->GetAddress()); |
| 675 | } else { |
| 676 | RTC_LOG(LS_WARNING) << ToString() |
| 677 | << ": Received send indication without permission" |
| 678 | " peer=" |
| 679 | << peer_attr->GetAddress().ToSensitiveString(); |
| 680 | } |
| 681 | } |
| 682 |
| 683 | void TurnServerAllocation::HandleCreatePermissionRequest( |
| 684 | const TurnMessage* msg) { |
| 685 | // Check mandatory attributes. |
| 686 | const StunAddressAttribute* peer_attr = |
| 687 | msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS); |
| 688 | if (!peer_attr) { |
| 689 | SendBadRequestResponse(msg); |
| 690 | return; |
| 691 | } |
| 692 |
| 693 | if (server_->reject_private_addresses_ && |
| 694 | rtc::IPIsPrivate(peer_attr->GetAddress().ipaddr())) { |
| 695 | SendErrorResponse(msg, STUN_ERROR_FORBIDDEN, STUN_ERROR_REASON_FORBIDDEN); |
| 696 | return; |
| 697 | } |
| 698 |
| 699 | // Add this permission. |
| 700 | AddPermission(peer_attr->GetAddress().ipaddr()); |
| 701 |
| 702 | RTC_LOG(LS_INFO) << ToString() << ": Created permission, peer=" |
| 703 | << peer_attr->GetAddress().ToSensitiveString(); |
| 704 |
| 705 | // Send a success response. |
| 706 | TurnMessage response(GetStunSuccessResponseTypeOrZero(*msg), |
| 707 | msg->transaction_id()); |
| 708 | SendResponse(&response); |
| 709 | } |
| 710 |
| 711 | void TurnServerAllocation::HandleChannelBindRequest(const TurnMessage* msg) { |
| 712 | // Check mandatory attributes. |
| 713 | const StunUInt32Attribute* channel_attr = |
| 714 | msg->GetUInt32(STUN_ATTR_CHANNEL_NUMBER); |
| 715 | const StunAddressAttribute* peer_attr = |
| 716 | msg->GetAddress(STUN_ATTR_XOR_PEER_ADDRESS); |
| 717 | if (!channel_attr || !peer_attr) { |
| 718 | SendBadRequestResponse(msg); |
| 719 | return; |
| 720 | } |
| 721 |
| 722 | // Check that channel id is valid. |
| 723 | int channel_id = channel_attr->value() >> 16; |
| 724 | if (channel_id < kMinChannelNumber || channel_id > kMaxChannelNumber) { |
| 725 | SendBadRequestResponse(msg); |
| 726 | return; |
| 727 | } |
| 728 |
| 729 | // Check that this channel id isn't bound to another transport address, and |
| 730 | // that this transport address isn't bound to another channel id. |
| 731 | auto channel1 = FindChannel(channel_id); |
| 732 | auto channel2 = FindChannel(peer_attr->GetAddress()); |
| 733 | if (channel1 != channel2) { |
| 734 | SendBadRequestResponse(msg); |
| 735 | return; |
| 736 | } |
| 737 |
| 738 | // Add or refresh this channel. |
| 739 | if (channel1 == channels_.end()) { |
| 740 | channel1 = channels_.insert( |
| 741 | channels_.end(), {.id = channel_id, .peer = peer_attr->GetAddress()}); |
| 742 | } else { |
| 743 | channel1->pending_delete.reset(); |
| 744 | } |
| 745 | thread_->PostDelayedTask( |
| 746 | SafeTask(channel1->pending_delete.flag(), |
| 747 | [this, channel1] { channels_.erase(channel1); }), |
| 748 | kChannelTimeout); |
| 749 |
| 750 | // Channel binds also refresh permissions. |
| 751 | AddPermission(peer_attr->GetAddress().ipaddr()); |
| 752 |
| 753 | RTC_LOG(LS_INFO) << ToString() << ": Bound channel, id=" << channel_id |
| 754 | << ", peer=" << peer_attr->GetAddress().ToSensitiveString(); |
| 755 |
| 756 | // Send a success response. |
| 757 | TurnMessage response(GetStunSuccessResponseTypeOrZero(*msg), |
| 758 | msg->transaction_id()); |
| 759 | SendResponse(&response); |
| 760 | } |
| 761 |
| 762 | void TurnServerAllocation::HandleChannelData( |
| 763 | rtc::ArrayView<const uint8_t> payload) { |
| 764 | // Extract the channel number from the data. |
| 765 | uint16_t channel_id = rtc::GetBE16(payload.data()); |
| 766 | auto channel = FindChannel(channel_id); |
| 767 | if (channel != channels_.end()) { |
| 768 | // Send the data to the peer address. |
| 769 | SendExternal(payload.data() + TURN_CHANNEL_HEADER_SIZE, |
| 770 | payload.size() - TURN_CHANNEL_HEADER_SIZE, channel->peer); |
| 771 | } else { |
| 772 | RTC_LOG(LS_WARNING) << ToString() |
| 773 | << ": Received channel data for invalid channel, id=" |
| 774 | << channel_id; |
| 775 | } |
| 776 | } |
| 777 |
| 778 | void TurnServerAllocation::OnExternalPacket(rtc::AsyncPacketSocket* socket, |
| 779 | const rtc::ReceivedPacket& packet) { |
| 780 | RTC_DCHECK(external_socket_.get() == socket); |
| 781 | auto channel = FindChannel(packet.source_address()); |
| 782 | if (channel != channels_.end()) { |
| 783 | // There is a channel bound to this address. Send as a channel message. |
| 784 | rtc::ByteBufferWriter buf; |
| 785 | buf.WriteUInt16(channel->id); |
| 786 | buf.WriteUInt16(static_cast<uint16_t>(packet.payload().size())); |
| 787 | buf.WriteBytes(packet.payload().data(), packet.payload().size()); |
| 788 | server_->Send(&conn_, buf); |
| 789 | } else if (!server_->enable_permission_checks_ || |
| 790 | HasPermission(packet.source_address().ipaddr())) { |
| 791 | // No channel, but a permission exists. Send as a data indication. |
| 792 | TurnMessage msg(TURN_DATA_INDICATION); |
| 793 | msg.AddAttribute(std::make_unique<StunXorAddressAttribute>( |
| 794 | STUN_ATTR_XOR_PEER_ADDRESS, packet.source_address())); |
| 795 | msg.AddAttribute(std::make_unique<StunByteStringAttribute>( |
| 796 | STUN_ATTR_DATA, packet.payload().data(), packet.payload().size())); |
| 797 | server_->SendStun(&conn_, &msg); |
| 798 | } else { |
| 799 | RTC_LOG(LS_WARNING) |
| 800 | << ToString() << ": Received external packet without permission, peer=" |
| 801 | << packet.source_address().ToSensitiveString(); |
| 802 | } |
| 803 | } |
| 804 |
| 805 | TimeDelta TurnServerAllocation::ComputeLifetime(const TurnMessage& msg) { |
| 806 | if (const StunUInt32Attribute* attr = msg.GetUInt32(STUN_ATTR_LIFETIME)) { |
| 807 | return std::min(TimeDelta::Seconds(static_cast<int>(attr->value())), |
| 808 | kDefaultAllocationTimeout); |
| 809 | } |
| 810 | return kDefaultAllocationTimeout; |
| 811 | } |
| 812 |
| 813 | bool TurnServerAllocation::HasPermission(const rtc::IPAddress& addr) { |
| 814 | return FindPermission(addr) != perms_.end(); |
| 815 | } |
| 816 |
| 817 | void TurnServerAllocation::AddPermission(const rtc::IPAddress& addr) { |
| 818 | auto perm = FindPermission(addr); |
| 819 | if (perm == perms_.end()) { |
| 820 | perm = perms_.insert(perms_.end(), {.peer = addr}); |
| 821 | } else { |
| 822 | perm->pending_delete.reset(); |
| 823 | } |
| 824 | thread_->PostDelayedTask(SafeTask(perm->pending_delete.flag(), |
| 825 | [this, perm] { perms_.erase(perm); }), |
| 826 | kPermissionTimeout); |
| 827 | } |
| 828 |
| 829 | TurnServerAllocation::PermissionList::iterator |
| 830 | TurnServerAllocation::FindPermission(const rtc::IPAddress& addr) { |
| 831 | return absl::c_find_if(perms_, |
| 832 | [&](const Permission& p) { return p.peer == addr; }); |
| 833 | } |
| 834 |
| 835 | TurnServerAllocation::ChannelList::iterator TurnServerAllocation::FindChannel( |
| 836 | int channel_id) { |
| 837 | return absl::c_find_if(channels_, |
| 838 | [&](const Channel& c) { return c.id == channel_id; }); |
| 839 | } |
| 840 |
| 841 | TurnServerAllocation::ChannelList::iterator TurnServerAllocation::FindChannel( |
| 842 | const rtc::SocketAddress& addr) { |
| 843 | return absl::c_find_if(channels_, |
| 844 | [&](const Channel& c) { return c.peer == addr; }); |
| 845 | } |
| 846 |
| 847 | void TurnServerAllocation::SendResponse(TurnMessage* msg) { |
| 848 | // Success responses always have M-I. |
| 849 | msg->AddMessageIntegrity(key_); |
| 850 | server_->SendStun(&conn_, msg); |
| 851 | } |
| 852 |
| 853 | void TurnServerAllocation::SendBadRequestResponse(const TurnMessage* req) { |
| 854 | SendErrorResponse(req, STUN_ERROR_BAD_REQUEST, STUN_ERROR_REASON_BAD_REQUEST); |
| 855 | } |
| 856 |
| 857 | void TurnServerAllocation::SendErrorResponse(const TurnMessage* req, |
| 858 | int code, |
| 859 | absl::string_view reason) { |
| 860 | server_->SendErrorResponse(&conn_, req, code, reason); |
| 861 | } |
| 862 |
| 863 | void TurnServerAllocation::SendExternal(const void* data, |
| 864 | size_t size, |
| 865 | const rtc::SocketAddress& peer) { |
| 866 | rtc::PacketOptions options; |
| 867 | external_socket_->SendTo(data, size, peer, options); |
| 868 | } |
| 869 |
| 870 | void TurnServerAllocation::PostDeleteSelf(TimeDelta delay) { |
| 871 | auto delete_self = [this] { |
| 872 | RTC_DCHECK_RUN_ON(server_->thread_); |
| 873 | server_->DestroyAllocation(this); |
| 874 | }; |
| 875 | thread_->PostDelayedTask(SafeTask(safety_.flag(), std::move(delete_self)), |
| 876 | delay); |
| 877 | } |
| 878 |
| 879 | } // namespace cricket |
| 880 |