fuzzed_socket.cc 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. // Copyright 2016 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/socket/fuzzed_socket.h"
  5. #include <fuzzer/FuzzedDataProvider.h>
  6. #include <algorithm>
  7. #include "base/bind.h"
  8. #include "base/check_op.h"
  9. #include "base/location.h"
  10. #include "base/notreached.h"
  11. #include "base/threading/thread_task_runner_handle.h"
  12. #include "net/base/io_buffer.h"
  13. #include "net/log/net_log_source_type.h"
  14. #include "net/traffic_annotation/network_traffic_annotation.h"
  15. namespace net {
  16. namespace {
  17. const int kMaxAsyncReadsAndWrites = 1000;
  18. // Some of the socket errors that can be returned by normal socket connection
  19. // attempts.
  20. const Error kConnectErrors[] = {
  21. ERR_CONNECTION_RESET, ERR_CONNECTION_CLOSED, ERR_FAILED,
  22. ERR_CONNECTION_TIMED_OUT, ERR_ACCESS_DENIED, ERR_CONNECTION_REFUSED,
  23. ERR_ADDRESS_UNREACHABLE};
  24. // Some of the socket errors that can be returned by normal socket reads /
  25. // writes. The first one is returned when no more input data remains, so it's
  26. // one of the most common ones.
  27. const Error kReadWriteErrors[] = {ERR_CONNECTION_CLOSED, ERR_FAILED,
  28. ERR_TIMED_OUT, ERR_CONNECTION_RESET};
  29. } // namespace
  30. FuzzedSocket::FuzzedSocket(FuzzedDataProvider* data_provider,
  31. net::NetLog* net_log)
  32. : data_provider_(data_provider),
  33. net_log_(NetLogWithSource::Make(net_log, NetLogSourceType::SOCKET)),
  34. remote_address_(IPEndPoint(IPAddress::IPv4Localhost(), 80)) {}
  35. FuzzedSocket::~FuzzedSocket() = default;
  36. int FuzzedSocket::Read(IOBuffer* buf,
  37. int buf_len,
  38. CompletionOnceCallback callback) {
  39. DCHECK(!connect_pending_);
  40. DCHECK(!read_pending_);
  41. bool sync;
  42. int result;
  43. if (net_error_ != OK) {
  44. // If an error has already been generated, use it to determine what to do.
  45. result = net_error_;
  46. sync = !error_pending_;
  47. } else {
  48. // Otherwise, use |data_provider_|. Always consume a bool, even when
  49. // ForceSync() is true, to behave more consistently against input mutations.
  50. sync = data_provider_->ConsumeBool() || ForceSync();
  51. num_async_reads_and_writes_ += static_cast<int>(!sync);
  52. std::string data = data_provider_->ConsumeRandomLengthString(buf_len);
  53. result = data.size();
  54. if (result > 0) {
  55. std::copy(data.data(), data.data() + result, buf->data());
  56. } else {
  57. result = ConsumeReadWriteErrorFromData();
  58. net_error_ = result;
  59. if (!sync)
  60. error_pending_ = true;
  61. }
  62. }
  63. // Graceful close of a socket returns OK, at least in theory. This doesn't
  64. // perfectly reflect real socket behavior, but close enough.
  65. if (result == ERR_CONNECTION_CLOSED)
  66. result = 0;
  67. if (sync) {
  68. if (result > 0)
  69. total_bytes_read_ += result;
  70. return result;
  71. }
  72. read_pending_ = true;
  73. base::ThreadTaskRunnerHandle::Get()->PostTask(
  74. FROM_HERE,
  75. base::BindOnce(&FuzzedSocket::OnReadComplete, weak_factory_.GetWeakPtr(),
  76. std::move(callback), result));
  77. return ERR_IO_PENDING;
  78. }
  79. int FuzzedSocket::Write(
  80. IOBuffer* buf,
  81. int buf_len,
  82. CompletionOnceCallback callback,
  83. const NetworkTrafficAnnotationTag& /* traffic_annotation */) {
  84. DCHECK(!connect_pending_);
  85. DCHECK(!write_pending_);
  86. bool sync;
  87. int result;
  88. if (net_error_ != OK) {
  89. // If an error has already been generated, use it to determine what to do.
  90. result = net_error_;
  91. sync = !error_pending_;
  92. } else {
  93. // Otherwise, use |data_provider_|. Always consume a bool, even when
  94. // ForceSync() is true, to behave more consistently against input mutations.
  95. sync = data_provider_->ConsumeBool() || ForceSync();
  96. num_async_reads_and_writes_ += static_cast<int>(!sync);
  97. // Intentionally using smaller |result| size here.
  98. result = data_provider_->ConsumeIntegralInRange<int>(0, 0xFF);
  99. if (result > buf_len)
  100. result = buf_len;
  101. if (result == 0) {
  102. net_error_ = ConsumeReadWriteErrorFromData();
  103. result = net_error_;
  104. if (!sync)
  105. error_pending_ = true;
  106. }
  107. }
  108. if (sync) {
  109. if (result > 0)
  110. total_bytes_written_ += result;
  111. return result;
  112. }
  113. write_pending_ = true;
  114. base::ThreadTaskRunnerHandle::Get()->PostTask(
  115. FROM_HERE,
  116. base::BindOnce(&FuzzedSocket::OnWriteComplete, weak_factory_.GetWeakPtr(),
  117. std::move(callback), result));
  118. return ERR_IO_PENDING;
  119. }
  120. int FuzzedSocket::SetReceiveBufferSize(int32_t size) {
  121. return OK;
  122. }
  123. int FuzzedSocket::SetSendBufferSize(int32_t size) {
  124. return OK;
  125. }
  126. int FuzzedSocket::Bind(const net::IPEndPoint& local_addr) {
  127. NOTREACHED();
  128. return ERR_NOT_IMPLEMENTED;
  129. }
  130. int FuzzedSocket::Connect(CompletionOnceCallback callback) {
  131. // Sockets can normally be reused, but don't support it here.
  132. DCHECK_NE(net_error_, OK);
  133. DCHECK(!connect_pending_);
  134. DCHECK(!read_pending_);
  135. DCHECK(!write_pending_);
  136. DCHECK(!error_pending_);
  137. DCHECK(!total_bytes_read_);
  138. DCHECK(!total_bytes_written_);
  139. bool sync = true;
  140. Error result = OK;
  141. if (fuzz_connect_result_) {
  142. // Decide if sync or async. Use async, if no data is left.
  143. sync = data_provider_->ConsumeBool();
  144. // Decide if the connect succeeds or not, and if so, pick an error code.
  145. if (data_provider_->ConsumeBool())
  146. result = data_provider_->PickValueInArray(kConnectErrors);
  147. }
  148. if (sync) {
  149. net_error_ = result;
  150. return result;
  151. }
  152. connect_pending_ = true;
  153. if (result != OK)
  154. error_pending_ = true;
  155. base::ThreadTaskRunnerHandle::Get()->PostTask(
  156. FROM_HERE,
  157. base::BindOnce(&FuzzedSocket::OnConnectComplete,
  158. weak_factory_.GetWeakPtr(), std::move(callback), result));
  159. return ERR_IO_PENDING;
  160. }
  161. void FuzzedSocket::Disconnect() {
  162. net_error_ = ERR_CONNECTION_CLOSED;
  163. weak_factory_.InvalidateWeakPtrs();
  164. connect_pending_ = false;
  165. read_pending_ = false;
  166. write_pending_ = false;
  167. error_pending_ = false;
  168. }
  169. bool FuzzedSocket::IsConnected() const {
  170. return net_error_ == OK && !error_pending_;
  171. }
  172. bool FuzzedSocket::IsConnectedAndIdle() const {
  173. return IsConnected();
  174. }
  175. int FuzzedSocket::GetPeerAddress(IPEndPoint* address) const {
  176. if (!IsConnected())
  177. return ERR_SOCKET_NOT_CONNECTED;
  178. *address = remote_address_;
  179. return OK;
  180. }
  181. int FuzzedSocket::GetLocalAddress(IPEndPoint* address) const {
  182. if (!IsConnected())
  183. return ERR_SOCKET_NOT_CONNECTED;
  184. *address = IPEndPoint(IPAddress(127, 0, 0, 1), 43434);
  185. return OK;
  186. }
  187. const NetLogWithSource& FuzzedSocket::NetLog() const {
  188. return net_log_;
  189. }
  190. bool FuzzedSocket::WasEverUsed() const {
  191. return total_bytes_written_ != 0 || total_bytes_read_ != 0;
  192. }
  193. bool FuzzedSocket::WasAlpnNegotiated() const {
  194. return false;
  195. }
  196. NextProto FuzzedSocket::GetNegotiatedProtocol() const {
  197. return kProtoUnknown;
  198. }
  199. bool FuzzedSocket::GetSSLInfo(SSLInfo* ssl_info) {
  200. return false;
  201. }
  202. int64_t FuzzedSocket::GetTotalReceivedBytes() const {
  203. return total_bytes_read_;
  204. }
  205. void FuzzedSocket::ApplySocketTag(const net::SocketTag& tag) {}
  206. Error FuzzedSocket::ConsumeReadWriteErrorFromData() {
  207. return data_provider_->PickValueInArray(kReadWriteErrors);
  208. }
  209. void FuzzedSocket::OnReadComplete(CompletionOnceCallback callback, int result) {
  210. CHECK(read_pending_);
  211. read_pending_ = false;
  212. if (result <= 0) {
  213. error_pending_ = false;
  214. } else {
  215. total_bytes_read_ += result;
  216. }
  217. std::move(callback).Run(result);
  218. }
  219. void FuzzedSocket::OnWriteComplete(CompletionOnceCallback callback,
  220. int result) {
  221. CHECK(write_pending_);
  222. write_pending_ = false;
  223. if (result <= 0) {
  224. error_pending_ = false;
  225. } else {
  226. total_bytes_written_ += result;
  227. }
  228. std::move(callback).Run(result);
  229. }
  230. void FuzzedSocket::OnConnectComplete(CompletionOnceCallback callback,
  231. int result) {
  232. CHECK(connect_pending_);
  233. connect_pending_ = false;
  234. if (result < 0)
  235. error_pending_ = false;
  236. net_error_ = result;
  237. std::move(callback).Run(result);
  238. }
  239. bool FuzzedSocket::ForceSync() const {
  240. return (num_async_reads_and_writes_ >= kMaxAsyncReadsAndWrites);
  241. }
  242. } // namespace net