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.

1019 lines
35 KiB

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