tls_client_socket_unittest.cc 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  1. // Copyright 2018 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 <stdint.h>
  5. #include <string>
  6. #include <utility>
  7. #include <vector>
  8. #include "base/bind.h"
  9. #include "base/check_op.h"
  10. #include "base/run_loop.h"
  11. #include "base/test/bind.h"
  12. #include "base/test/task_environment.h"
  13. #include "base/threading/thread.h"
  14. #include "mojo/public/cpp/bindings/pending_receiver.h"
  15. #include "mojo/public/cpp/bindings/remote.h"
  16. #include "net/base/completion_once_callback.h"
  17. #include "net/base/net_errors.h"
  18. #include "net/base/network_isolation_key.h"
  19. #include "net/base/test_completion_callback.h"
  20. #include "net/proxy_resolution/configured_proxy_resolution_service.h"
  21. #include "net/socket/server_socket.h"
  22. #include "net/socket/socket_test_util.h"
  23. #include "net/test/embedded_test_server/embedded_test_server.h"
  24. #include "net/test/embedded_test_server/http_request.h"
  25. #include "net/test/embedded_test_server/http_response.h"
  26. #include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
  27. #include "net/url_request/url_request_context.h"
  28. #include "net/url_request/url_request_context_builder.h"
  29. #include "net/url_request/url_request_test_util.h"
  30. #include "services/network/mojo_socket_test_util.h"
  31. #include "services/network/proxy_resolving_socket_factory_mojo.h"
  32. #include "services/network/public/mojom/network_service.mojom.h"
  33. #include "services/network/public/mojom/tls_socket.mojom.h"
  34. #include "services/network/socket_factory.h"
  35. #include "testing/gtest/include/gtest/gtest.h"
  36. namespace network {
  37. namespace {
  38. // Message sent over the tcp connection.
  39. const char kMsg[] = "please start tls!";
  40. const size_t kMsgSize = strlen(kMsg);
  41. // Message sent over the tls connection.
  42. const char kSecretMsg[] = "here is secret.";
  43. const size_t kSecretMsgSize = strlen(kSecretMsg);
  44. class TLSClientSocketTestBase {
  45. public:
  46. enum Mode { kDirect, kProxyResolving };
  47. explicit TLSClientSocketTestBase(Mode mode)
  48. : mode_(mode),
  49. task_environment_(base::test::TaskEnvironment::MainThreadType::IO) {}
  50. TLSClientSocketTestBase(const TLSClientSocketTestBase&) = delete;
  51. TLSClientSocketTestBase& operator=(const TLSClientSocketTestBase&) = delete;
  52. virtual ~TLSClientSocketTestBase() {}
  53. Mode mode() { return mode_; }
  54. protected:
  55. // One of the two fields will be set, depending on the mode.
  56. struct SocketHandle {
  57. mojo::Remote<mojom::TCPConnectedSocket> tcp_socket;
  58. mojo::Remote<mojom::ProxyResolvingSocket> proxy_socket;
  59. };
  60. struct SocketRequest {
  61. mojo::PendingReceiver<mojom::TCPConnectedSocket> tcp_socket_receiver;
  62. mojo::PendingReceiver<mojom::ProxyResolvingSocket> proxy_socket_receiver;
  63. };
  64. // Initializes the test fixture. If |use_mock_sockets|, mock client socket
  65. // factory will be used.
  66. void Init(bool use_mock_sockets, bool configure_proxy) {
  67. auto context_builder = net::CreateTestURLRequestContextBuilder();
  68. if (use_mock_sockets) {
  69. mock_client_socket_factory_.set_enable_read_if_ready(true);
  70. context_builder->set_client_socket_factory_for_testing(
  71. &mock_client_socket_factory_);
  72. }
  73. if (configure_proxy) {
  74. context_builder->set_proxy_resolution_service(
  75. net::ConfiguredProxyResolutionService::CreateFixedForTest(
  76. "http://proxy:8080", TRAFFIC_ANNOTATION_FOR_TESTS));
  77. }
  78. url_request_context_ = context_builder->Build();
  79. factory_ = std::make_unique<SocketFactory>(/*net_log=*/nullptr,
  80. url_request_context_.get());
  81. proxy_resolving_factory_ =
  82. std::make_unique<ProxyResolvingSocketFactoryMojo>(
  83. url_request_context_.get());
  84. }
  85. // Reads |num_bytes| from |handle| or reads until an error occurs. Returns the
  86. // bytes read as a string.
  87. std::string Read(mojo::ScopedDataPipeConsumerHandle* handle,
  88. size_t num_bytes) {
  89. std::string received_contents;
  90. while (received_contents.size() < num_bytes) {
  91. base::RunLoop().RunUntilIdle();
  92. std::vector<char> buffer(num_bytes);
  93. uint32_t read_size = static_cast<uint32_t>(num_bytes);
  94. MojoResult result = handle->get().ReadData(buffer.data(), &read_size,
  95. MOJO_READ_DATA_FLAG_NONE);
  96. if (result == MOJO_RESULT_SHOULD_WAIT)
  97. continue;
  98. if (result != MOJO_RESULT_OK)
  99. return received_contents;
  100. received_contents.append(buffer.data(), read_size);
  101. }
  102. return received_contents;
  103. }
  104. SocketRequest MakeRequest(SocketHandle* handle) {
  105. SocketRequest result;
  106. if (mode_ == kDirect)
  107. result.tcp_socket_receiver =
  108. handle->tcp_socket.BindNewPipeAndPassReceiver();
  109. else
  110. result.proxy_socket_receiver =
  111. handle->proxy_socket.BindNewPipeAndPassReceiver();
  112. return result;
  113. }
  114. void ResetSocket(SocketHandle* handle) {
  115. if (mode_ == kDirect)
  116. handle->tcp_socket.reset();
  117. else
  118. handle->proxy_socket.reset();
  119. }
  120. int CreateSocketSync(SocketRequest request,
  121. const net::IPEndPoint& remote_addr) {
  122. if (mode_ == kDirect) {
  123. return CreateTCPConnectedSocketSync(
  124. std::move(request.tcp_socket_receiver), remote_addr);
  125. } else {
  126. return CreateProxyResolvingSocketSync(
  127. std::move(request.proxy_socket_receiver), remote_addr);
  128. }
  129. }
  130. int CreateTCPConnectedSocketSync(
  131. mojo::PendingReceiver<mojom::TCPConnectedSocket> receiver,
  132. const net::IPEndPoint& remote_addr) {
  133. net::AddressList remote_addr_list(remote_addr);
  134. base::RunLoop run_loop;
  135. int net_error = net::ERR_FAILED;
  136. factory_->CreateTCPConnectedSocket(
  137. absl::nullopt /* local_addr */, remote_addr_list,
  138. nullptr /* tcp_connected_socket_options */,
  139. TRAFFIC_ANNOTATION_FOR_TESTS, std::move(receiver),
  140. pre_tls_observer()->GetObserverRemote(),
  141. base::BindLambdaForTesting(
  142. [&](int result,
  143. const absl::optional<net::IPEndPoint>& actual_local_addr,
  144. const absl::optional<net::IPEndPoint>& peer_addr,
  145. mojo::ScopedDataPipeConsumerHandle receive_pipe_handle,
  146. mojo::ScopedDataPipeProducerHandle send_pipe_handle) {
  147. net_error = result;
  148. pre_tls_recv_handle_ = std::move(receive_pipe_handle);
  149. pre_tls_send_handle_ = std::move(send_pipe_handle);
  150. run_loop.Quit();
  151. }));
  152. run_loop.Run();
  153. return net_error;
  154. }
  155. int CreateProxyResolvingSocketSync(
  156. mojo::PendingReceiver<mojom::ProxyResolvingSocket> receiver,
  157. const net::IPEndPoint& remote_addr) {
  158. GURL url("https://" + remote_addr.ToString());
  159. base::RunLoop run_loop;
  160. int net_error = net::ERR_FAILED;
  161. proxy_resolving_factory_->CreateProxyResolvingSocket(
  162. url, net::NetworkIsolationKey(), nullptr /* options */,
  163. net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS),
  164. std::move(receiver), mojo::NullRemote() /* observer */,
  165. base::BindLambdaForTesting(
  166. [&](int result,
  167. const absl::optional<net::IPEndPoint>& actual_local_addr,
  168. const absl::optional<net::IPEndPoint>& peer_addr,
  169. mojo::ScopedDataPipeConsumerHandle receive_pipe_handle,
  170. mojo::ScopedDataPipeProducerHandle send_pipe_handle) {
  171. net_error = result;
  172. pre_tls_recv_handle_ = std::move(receive_pipe_handle);
  173. pre_tls_send_handle_ = std::move(send_pipe_handle);
  174. run_loop.Quit();
  175. }));
  176. run_loop.Run();
  177. return net_error;
  178. }
  179. void UpgradeToTLS(SocketHandle* handle,
  180. const net::HostPortPair& host_port_pair,
  181. mojo::PendingReceiver<mojom::TLSClientSocket> receiver,
  182. net::CompletionOnceCallback callback) {
  183. if (mode_ == kDirect) {
  184. UpgradeTCPConnectedSocketToTLS(handle->tcp_socket.get(), host_port_pair,
  185. nullptr /* options */, std::move(receiver),
  186. std::move(callback));
  187. } else {
  188. UpgradeProxyResolvingSocketToTLS(handle->proxy_socket.get(),
  189. host_port_pair, std::move(receiver),
  190. std::move(callback));
  191. }
  192. }
  193. void UpgradeTCPConnectedSocketToTLS(
  194. mojom::TCPConnectedSocket* client_socket,
  195. const net::HostPortPair& host_port_pair,
  196. mojom::TLSClientSocketOptionsPtr options,
  197. mojo::PendingReceiver<mojom::TLSClientSocket> receiver,
  198. net::CompletionOnceCallback callback) {
  199. client_socket->UpgradeToTLS(
  200. host_port_pair, std::move(options),
  201. net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS),
  202. std::move(receiver), post_tls_observer()->GetObserverRemote(),
  203. base::BindOnce(
  204. [](net::CompletionOnceCallback cb,
  205. mojo::ScopedDataPipeConsumerHandle* consumer_handle_out,
  206. mojo::ScopedDataPipeProducerHandle* producer_handle_out,
  207. absl::optional<net::SSLInfo>* ssl_info_out, int result,
  208. mojo::ScopedDataPipeConsumerHandle receive_pipe_handle,
  209. mojo::ScopedDataPipeProducerHandle send_pipe_handle,
  210. const absl::optional<net::SSLInfo>& ssl_info) {
  211. *consumer_handle_out = std::move(receive_pipe_handle);
  212. *producer_handle_out = std::move(send_pipe_handle);
  213. *ssl_info_out = ssl_info;
  214. std::move(cb).Run(result);
  215. },
  216. std::move(callback), &post_tls_recv_handle_, &post_tls_send_handle_,
  217. &ssl_info_));
  218. }
  219. void UpgradeProxyResolvingSocketToTLS(
  220. mojom::ProxyResolvingSocket* client_socket,
  221. const net::HostPortPair& host_port_pair,
  222. mojo::PendingReceiver<mojom::TLSClientSocket> receiver,
  223. net::CompletionOnceCallback callback) {
  224. client_socket->UpgradeToTLS(
  225. host_port_pair,
  226. net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS),
  227. std::move(receiver), post_tls_observer()->GetObserverRemote(),
  228. base::BindOnce(
  229. [](net::CompletionOnceCallback cb,
  230. mojo::ScopedDataPipeConsumerHandle* consumer_handle,
  231. mojo::ScopedDataPipeProducerHandle* producer_handle, int result,
  232. mojo::ScopedDataPipeConsumerHandle receive_pipe_handle,
  233. mojo::ScopedDataPipeProducerHandle send_pipe_handle) {
  234. *consumer_handle = std::move(receive_pipe_handle);
  235. *producer_handle = std::move(send_pipe_handle);
  236. std::move(cb).Run(result);
  237. },
  238. std::move(callback), &post_tls_recv_handle_,
  239. &post_tls_send_handle_));
  240. }
  241. TestSocketObserver* pre_tls_observer() { return &pre_tls_observer_; }
  242. TestSocketObserver* post_tls_observer() { return &post_tls_observer_; }
  243. mojo::ScopedDataPipeConsumerHandle* pre_tls_recv_handle() {
  244. return &pre_tls_recv_handle_;
  245. }
  246. mojo::ScopedDataPipeProducerHandle* pre_tls_send_handle() {
  247. return &pre_tls_send_handle_;
  248. }
  249. mojo::ScopedDataPipeConsumerHandle* post_tls_recv_handle() {
  250. return &post_tls_recv_handle_;
  251. }
  252. mojo::ScopedDataPipeProducerHandle* post_tls_send_handle() {
  253. return &post_tls_send_handle_;
  254. }
  255. const absl::optional<net::SSLInfo>& ssl_info() { return ssl_info_; }
  256. net::MockClientSocketFactory* mock_client_socket_factory() {
  257. return &mock_client_socket_factory_;
  258. }
  259. Mode mode() const { return mode_; }
  260. private:
  261. Mode mode_;
  262. base::test::TaskEnvironment task_environment_;
  263. // Mojo data handles obtained from CreateTCPConnectedSocket.
  264. mojo::ScopedDataPipeConsumerHandle pre_tls_recv_handle_;
  265. mojo::ScopedDataPipeProducerHandle pre_tls_send_handle_;
  266. // Mojo data handles obtained from UpgradeToTLS.
  267. mojo::ScopedDataPipeConsumerHandle post_tls_recv_handle_;
  268. mojo::ScopedDataPipeProducerHandle post_tls_send_handle_;
  269. // SSLInfo obtained from UpgradeToTLS.
  270. absl::optional<net::SSLInfo> ssl_info_;
  271. net::MockClientSocketFactory mock_client_socket_factory_;
  272. std::unique_ptr<net::URLRequestContext> url_request_context_;
  273. std::unique_ptr<SocketFactory> factory_;
  274. std::unique_ptr<ProxyResolvingSocketFactoryMojo> proxy_resolving_factory_;
  275. TestSocketObserver pre_tls_observer_;
  276. TestSocketObserver post_tls_observer_;
  277. };
  278. class TLSClientSocketTest
  279. : public ::testing::TestWithParam<TLSClientSocketTestBase::Mode>,
  280. public TLSClientSocketTestBase {
  281. public:
  282. TLSClientSocketTest() : TLSClientSocketTestBase(GetParam()) {
  283. Init(true /* use_mock_sockets */, false /* configure_proxy */);
  284. }
  285. TLSClientSocketTest(const TLSClientSocketTest&) = delete;
  286. TLSClientSocketTest& operator=(const TLSClientSocketTest&) = delete;
  287. ~TLSClientSocketTest() override {}
  288. };
  289. // Basic test to call UpgradeToTLS, and then read/write after UpgradeToTLS is
  290. // successful.
  291. TEST_P(TLSClientSocketTest, UpgradeToTLS) {
  292. const net::MockRead kReads[] = {net::MockRead(net::ASYNC, kMsg, kMsgSize, 1),
  293. net::MockRead(net::SYNCHRONOUS, net::OK, 2)};
  294. const net::MockWrite kWrites[] = {
  295. net::MockWrite(net::SYNCHRONOUS, kMsg, kMsgSize, 0)};
  296. net::SequencedSocketData data_provider(kReads, kWrites);
  297. data_provider.set_connect_data(net::MockConnect(net::SYNCHRONOUS, net::OK));
  298. mock_client_socket_factory()->AddSocketDataProvider(&data_provider);
  299. net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK);
  300. mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket);
  301. SocketHandle client_socket;
  302. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(), 1234);
  303. EXPECT_EQ(net::OK,
  304. CreateSocketSync(MakeRequest(&client_socket), server_addr));
  305. net::HostPortPair host_port_pair("example.org", 443);
  306. pre_tls_recv_handle()->reset();
  307. pre_tls_send_handle()->reset();
  308. net::TestCompletionCallback callback;
  309. mojo::Remote<mojom::TLSClientSocket> tls_socket;
  310. UpgradeToTLS(&client_socket, host_port_pair,
  311. tls_socket.BindNewPipeAndPassReceiver(), callback.callback());
  312. ASSERT_EQ(net::OK, callback.WaitForResult());
  313. ResetSocket(&client_socket);
  314. uint32_t num_bytes = strlen(kMsg);
  315. EXPECT_EQ(MOJO_RESULT_OK, post_tls_send_handle()->get().WriteData(
  316. &kMsg, &num_bytes, MOJO_WRITE_DATA_FLAG_NONE));
  317. EXPECT_EQ(kMsg, Read(post_tls_recv_handle(), kMsgSize));
  318. base::RunLoop().RunUntilIdle();
  319. EXPECT_TRUE(ssl_socket.ConnectDataConsumed());
  320. EXPECT_TRUE(data_provider.AllReadDataConsumed());
  321. EXPECT_TRUE(data_provider.AllWriteDataConsumed());
  322. }
  323. // Same as the UpgradeToTLS test above, except this test calls
  324. // base::RunLoop().RunUntilIdle() after destroying the pre-tls data pipes.
  325. TEST_P(TLSClientSocketTest, ClosePipesRunUntilIdleAndUpgradeToTLS) {
  326. const net::MockRead kReads[] = {net::MockRead(net::ASYNC, kMsg, kMsgSize, 1),
  327. net::MockRead(net::SYNCHRONOUS, net::OK, 2)};
  328. const net::MockWrite kWrites[] = {
  329. net::MockWrite(net::SYNCHRONOUS, kMsg, kMsgSize, 0)};
  330. net::SequencedSocketData data_provider(kReads, kWrites);
  331. data_provider.set_connect_data(net::MockConnect(net::SYNCHRONOUS, net::OK));
  332. mock_client_socket_factory()->AddSocketDataProvider(&data_provider);
  333. net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK);
  334. mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket);
  335. SocketHandle client_socket;
  336. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(), 1234);
  337. EXPECT_EQ(net::OK,
  338. CreateSocketSync(MakeRequest(&client_socket), server_addr));
  339. net::HostPortPair host_port_pair("example.org", 443);
  340. // Call RunUntilIdle() to test the case that pipes are closed before
  341. // UpgradeToTLS.
  342. pre_tls_recv_handle()->reset();
  343. pre_tls_send_handle()->reset();
  344. base::RunLoop().RunUntilIdle();
  345. net::TestCompletionCallback callback;
  346. mojo::Remote<mojom::TLSClientSocket> tls_socket;
  347. UpgradeToTLS(&client_socket, host_port_pair,
  348. tls_socket.BindNewPipeAndPassReceiver(), callback.callback());
  349. ASSERT_EQ(net::OK, callback.WaitForResult());
  350. ResetSocket(&client_socket);
  351. uint32_t num_bytes = strlen(kMsg);
  352. EXPECT_EQ(MOJO_RESULT_OK, post_tls_send_handle()->get().WriteData(
  353. &kMsg, &num_bytes, MOJO_WRITE_DATA_FLAG_NONE));
  354. EXPECT_EQ(kMsg, Read(post_tls_recv_handle(), kMsgSize));
  355. base::RunLoop().RunUntilIdle();
  356. EXPECT_TRUE(ssl_socket.ConnectDataConsumed());
  357. EXPECT_TRUE(data_provider.AllReadDataConsumed());
  358. EXPECT_TRUE(data_provider.AllWriteDataConsumed());
  359. }
  360. // Calling UpgradeToTLS on the same mojo::Remote<TCPConnectedSocket> is illegal
  361. // and should receive an error.
  362. TEST_P(TLSClientSocketTest, UpgradeToTLSTwice) {
  363. const net::MockRead kReads[] = {net::MockRead(net::ASYNC, net::OK, 0)};
  364. net::SequencedSocketData data_provider(kReads, base::span<net::MockWrite>());
  365. data_provider.set_connect_data(net::MockConnect(net::SYNCHRONOUS, net::OK));
  366. mock_client_socket_factory()->AddSocketDataProvider(&data_provider);
  367. net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK);
  368. mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket);
  369. SocketHandle client_socket;
  370. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(), 1234);
  371. EXPECT_EQ(net::OK,
  372. CreateSocketSync(MakeRequest(&client_socket), server_addr));
  373. net::HostPortPair host_port_pair("example.org", 443);
  374. pre_tls_recv_handle()->reset();
  375. pre_tls_send_handle()->reset();
  376. // First UpgradeToTLS should complete successfully.
  377. net::TestCompletionCallback callback;
  378. mojo::Remote<mojom::TLSClientSocket> tls_socket;
  379. UpgradeToTLS(&client_socket, host_port_pair,
  380. tls_socket.BindNewPipeAndPassReceiver(), callback.callback());
  381. ASSERT_EQ(net::OK, callback.WaitForResult());
  382. // Second time UpgradeToTLS is called, it should fail.
  383. mojo::Remote<mojom::TLSClientSocket> tls_socket2;
  384. base::RunLoop run_loop;
  385. int net_error = net::ERR_FAILED;
  386. if (mode() == kDirect) {
  387. auto upgrade2_callback = base::BindLambdaForTesting(
  388. [&](int result, mojo::ScopedDataPipeConsumerHandle receive_pipe_handle,
  389. mojo::ScopedDataPipeProducerHandle send_pipe_handle,
  390. const absl::optional<net::SSLInfo>& ssl_info) {
  391. net_error = result;
  392. run_loop.Quit();
  393. });
  394. client_socket.tcp_socket->UpgradeToTLS(
  395. host_port_pair, nullptr /* ssl_config_ptr */,
  396. net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS),
  397. tls_socket2.BindNewPipeAndPassReceiver(),
  398. mojo::NullRemote() /*observer */, std::move(upgrade2_callback));
  399. } else {
  400. auto upgrade2_callback = base::BindLambdaForTesting(
  401. [&](int result, mojo::ScopedDataPipeConsumerHandle receive_pipe_handle,
  402. mojo::ScopedDataPipeProducerHandle send_pipe_handle) {
  403. net_error = result;
  404. run_loop.Quit();
  405. });
  406. client_socket.proxy_socket->UpgradeToTLS(
  407. host_port_pair,
  408. net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS),
  409. tls_socket2.BindNewPipeAndPassReceiver(),
  410. mojo::NullRemote() /*observer */, std::move(upgrade2_callback));
  411. }
  412. run_loop.Run();
  413. ASSERT_EQ(net::ERR_SOCKET_NOT_CONNECTED, net_error);
  414. base::RunLoop().RunUntilIdle();
  415. EXPECT_TRUE(ssl_socket.ConnectDataConsumed());
  416. EXPECT_TRUE(data_provider.AllReadDataConsumed());
  417. EXPECT_TRUE(data_provider.AllWriteDataConsumed());
  418. }
  419. TEST_P(TLSClientSocketTest, UpgradeToTLSWithCustomSSLConfig) {
  420. // No custom options in the proxy-resolving case.
  421. if (mode() != kDirect)
  422. return;
  423. const net::MockRead kReads[] = {net::MockRead(net::ASYNC, net::OK, 0)};
  424. net::SequencedSocketData data_provider(kReads, base::span<net::MockWrite>());
  425. data_provider.set_connect_data(net::MockConnect(net::SYNCHRONOUS, net::OK));
  426. mock_client_socket_factory()->AddSocketDataProvider(&data_provider);
  427. net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK);
  428. ssl_socket.expected_ssl_version_min = net::SSL_PROTOCOL_VERSION_TLS1_2;
  429. ssl_socket.expected_ssl_version_max = net::SSL_PROTOCOL_VERSION_TLS1_3;
  430. mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket);
  431. SocketHandle client_socket;
  432. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(), 1234);
  433. EXPECT_EQ(net::OK,
  434. CreateSocketSync(MakeRequest(&client_socket), server_addr));
  435. net::HostPortPair host_port_pair("example.org", 443);
  436. pre_tls_recv_handle()->reset();
  437. pre_tls_send_handle()->reset();
  438. mojo::Remote<mojom::TLSClientSocket> tls_socket;
  439. base::RunLoop run_loop;
  440. mojom::TLSClientSocketOptionsPtr options =
  441. mojom::TLSClientSocketOptions::New();
  442. options->version_min = mojom::SSLVersion::kTLS12;
  443. options->version_max = mojom::SSLVersion::kTLS13;
  444. int net_error = net::ERR_FAILED;
  445. auto upgrade_callback = base::BindLambdaForTesting(
  446. [&](int result, mojo::ScopedDataPipeConsumerHandle receive_pipe_handle,
  447. mojo::ScopedDataPipeProducerHandle send_pipe_handle,
  448. const absl::optional<net::SSLInfo>& ssl_info) {
  449. net_error = result;
  450. run_loop.Quit();
  451. });
  452. client_socket.tcp_socket->UpgradeToTLS(
  453. host_port_pair, std::move(options),
  454. net::MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS),
  455. tls_socket.BindNewPipeAndPassReceiver(), mojo::NullRemote() /*observer */,
  456. std::move(upgrade_callback));
  457. run_loop.Run();
  458. ASSERT_EQ(net::OK, net_error);
  459. base::RunLoop().RunUntilIdle();
  460. EXPECT_TRUE(ssl_socket.ConnectDataConsumed());
  461. EXPECT_TRUE(data_provider.AllReadDataConsumed());
  462. EXPECT_TRUE(data_provider.AllWriteDataConsumed());
  463. }
  464. // Same as the UpgradeToTLS test, except this also reads and writes to the tcp
  465. // connection before UpgradeToTLS is called.
  466. TEST_P(TLSClientSocketTest, ReadWriteBeforeUpgradeToTLS) {
  467. const net::MockRead kReads[] = {
  468. net::MockRead(net::SYNCHRONOUS, kMsg, kMsgSize, 0),
  469. net::MockRead(net::ASYNC, kSecretMsg, kSecretMsgSize, 3),
  470. net::MockRead(net::SYNCHRONOUS, net::OK, 4)};
  471. const net::MockWrite kWrites[] = {
  472. net::MockWrite(net::SYNCHRONOUS, kMsg, kMsgSize, 1),
  473. net::MockWrite(net::SYNCHRONOUS, kSecretMsg, kSecretMsgSize, 2),
  474. };
  475. net::SequencedSocketData data_provider(kReads, kWrites);
  476. data_provider.set_connect_data(net::MockConnect(net::SYNCHRONOUS, net::OK));
  477. mock_client_socket_factory()->AddSocketDataProvider(&data_provider);
  478. net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK);
  479. mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket);
  480. SocketHandle client_socket;
  481. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(), 1234);
  482. EXPECT_EQ(net::OK,
  483. CreateSocketSync(MakeRequest(&client_socket), server_addr));
  484. EXPECT_EQ(kMsg, Read(pre_tls_recv_handle(), kMsgSize));
  485. uint32_t num_bytes = kMsgSize;
  486. EXPECT_EQ(MOJO_RESULT_OK, pre_tls_send_handle()->get().WriteData(
  487. &kMsg, &num_bytes, MOJO_WRITE_DATA_FLAG_NONE));
  488. net::HostPortPair host_port_pair("example.org", 443);
  489. pre_tls_recv_handle()->reset();
  490. pre_tls_send_handle()->reset();
  491. net::TestCompletionCallback callback;
  492. mojo::Remote<mojom::TLSClientSocket> tls_socket;
  493. UpgradeToTLS(&client_socket, host_port_pair,
  494. tls_socket.BindNewPipeAndPassReceiver(), callback.callback());
  495. ASSERT_EQ(net::OK, callback.WaitForResult());
  496. ResetSocket(&client_socket);
  497. num_bytes = strlen(kSecretMsg);
  498. EXPECT_EQ(MOJO_RESULT_OK,
  499. post_tls_send_handle()->get().WriteData(&kSecretMsg, &num_bytes,
  500. MOJO_WRITE_DATA_FLAG_NONE));
  501. EXPECT_EQ(kSecretMsg, Read(post_tls_recv_handle(), kSecretMsgSize));
  502. base::RunLoop().RunUntilIdle();
  503. EXPECT_TRUE(ssl_socket.ConnectDataConsumed());
  504. EXPECT_TRUE(data_provider.AllReadDataConsumed());
  505. EXPECT_TRUE(data_provider.AllWriteDataConsumed());
  506. }
  507. // Tests that a read error is encountered after UpgradeToTLS completes
  508. // successfully.
  509. TEST_P(TLSClientSocketTest, ReadErrorAfterUpgradeToTLS) {
  510. const net::MockRead kReads[] = {
  511. net::MockRead(net::ASYNC, kSecretMsg, kSecretMsgSize, 1),
  512. net::MockRead(net::SYNCHRONOUS, net::ERR_CONNECTION_CLOSED, 2)};
  513. const net::MockWrite kWrites[] = {
  514. net::MockWrite(net::SYNCHRONOUS, kSecretMsg, kSecretMsgSize, 0)};
  515. net::SequencedSocketData data_provider(kReads, kWrites);
  516. data_provider.set_connect_data(net::MockConnect(net::SYNCHRONOUS, net::OK));
  517. mock_client_socket_factory()->AddSocketDataProvider(&data_provider);
  518. net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK);
  519. mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket);
  520. SocketHandle client_socket;
  521. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(), 1234);
  522. EXPECT_EQ(net::OK,
  523. CreateSocketSync(MakeRequest(&client_socket), server_addr));
  524. net::HostPortPair host_port_pair("example.org", 443);
  525. pre_tls_recv_handle()->reset();
  526. pre_tls_send_handle()->reset();
  527. net::TestCompletionCallback callback;
  528. mojo::Remote<mojom::TLSClientSocket> tls_socket;
  529. UpgradeToTLS(&client_socket, host_port_pair,
  530. tls_socket.BindNewPipeAndPassReceiver(), callback.callback());
  531. ASSERT_EQ(net::OK, callback.WaitForResult());
  532. ResetSocket(&client_socket);
  533. uint32_t num_bytes = strlen(kSecretMsg);
  534. EXPECT_EQ(MOJO_RESULT_OK,
  535. post_tls_send_handle()->get().WriteData(&kSecretMsg, &num_bytes,
  536. MOJO_WRITE_DATA_FLAG_NONE));
  537. EXPECT_EQ(kSecretMsg, Read(post_tls_recv_handle(), kSecretMsgSize));
  538. EXPECT_EQ(net::ERR_CONNECTION_CLOSED,
  539. post_tls_observer()->WaitForReadError());
  540. base::RunLoop().RunUntilIdle();
  541. EXPECT_TRUE(ssl_socket.ConnectDataConsumed());
  542. EXPECT_TRUE(data_provider.AllReadDataConsumed());
  543. EXPECT_TRUE(data_provider.AllWriteDataConsumed());
  544. }
  545. // Tests that a read error is encountered after UpgradeToTLS completes
  546. // successfully.
  547. TEST_P(TLSClientSocketTest, WriteErrorAfterUpgradeToTLS) {
  548. const net::MockRead kReads[] = {net::MockRead(net::ASYNC, net::OK, 0)};
  549. const net::MockWrite kWrites[] = {
  550. net::MockWrite(net::SYNCHRONOUS, net::ERR_CONNECTION_CLOSED, 1)};
  551. net::SequencedSocketData data_provider(kReads, kWrites);
  552. data_provider.set_connect_data(net::MockConnect(net::SYNCHRONOUS, net::OK));
  553. mock_client_socket_factory()->AddSocketDataProvider(&data_provider);
  554. net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK);
  555. mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket);
  556. SocketHandle client_socket;
  557. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(), 1234);
  558. EXPECT_EQ(net::OK,
  559. CreateSocketSync(MakeRequest(&client_socket), server_addr));
  560. net::HostPortPair host_port_pair("example.org", 443);
  561. pre_tls_recv_handle()->reset();
  562. pre_tls_send_handle()->reset();
  563. net::TestCompletionCallback callback;
  564. mojo::Remote<mojom::TLSClientSocket> tls_socket;
  565. UpgradeToTLS(&client_socket, host_port_pair,
  566. tls_socket.BindNewPipeAndPassReceiver(), callback.callback());
  567. ASSERT_EQ(net::OK, callback.WaitForResult());
  568. ResetSocket(&client_socket);
  569. uint32_t num_bytes = strlen(kSecretMsg);
  570. EXPECT_EQ(MOJO_RESULT_OK,
  571. post_tls_send_handle()->get().WriteData(&kSecretMsg, &num_bytes,
  572. MOJO_WRITE_DATA_FLAG_NONE));
  573. EXPECT_EQ(net::ERR_CONNECTION_CLOSED,
  574. post_tls_observer()->WaitForWriteError());
  575. base::RunLoop().RunUntilIdle();
  576. EXPECT_TRUE(ssl_socket.ConnectDataConsumed());
  577. EXPECT_TRUE(data_provider.AllReadDataConsumed());
  578. EXPECT_TRUE(data_provider.AllWriteDataConsumed());
  579. }
  580. // Tests that reading from the pre-tls data pipe is okay even after UpgradeToTLS
  581. // is called.
  582. TEST_P(TLSClientSocketTest, ReadFromPreTlsDataPipeAfterUpgradeToTLS) {
  583. const net::MockRead kReads[] = {
  584. net::MockRead(net::ASYNC, kMsg, kMsgSize, 0),
  585. net::MockRead(net::ASYNC, kSecretMsg, kSecretMsgSize, 2),
  586. net::MockRead(net::SYNCHRONOUS, net::OK, 3)};
  587. const net::MockWrite kWrites[] = {
  588. net::MockWrite(net::SYNCHRONOUS, kSecretMsg, kSecretMsgSize, 1)};
  589. net::SequencedSocketData data_provider(kReads, kWrites);
  590. data_provider.set_connect_data(net::MockConnect(net::SYNCHRONOUS, net::OK));
  591. mock_client_socket_factory()->AddSocketDataProvider(&data_provider);
  592. net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK);
  593. mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket);
  594. SocketHandle client_socket;
  595. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(), 1234);
  596. EXPECT_EQ(net::OK,
  597. CreateSocketSync(MakeRequest(&client_socket), server_addr));
  598. net::HostPortPair host_port_pair("example.org", 443);
  599. pre_tls_send_handle()->reset();
  600. net::TestCompletionCallback callback;
  601. mojo::Remote<mojom::TLSClientSocket> tls_socket;
  602. UpgradeToTLS(&client_socket, host_port_pair,
  603. tls_socket.BindNewPipeAndPassReceiver(), callback.callback());
  604. base::RunLoop().RunUntilIdle();
  605. EXPECT_EQ(kMsg, Read(pre_tls_recv_handle(), kMsgSize));
  606. // Reset pre-tls receive pipe now and UpgradeToTLS should complete.
  607. pre_tls_recv_handle()->reset();
  608. ASSERT_EQ(net::OK, callback.WaitForResult());
  609. ResetSocket(&client_socket);
  610. uint32_t num_bytes = strlen(kSecretMsg);
  611. EXPECT_EQ(MOJO_RESULT_OK,
  612. post_tls_send_handle()->get().WriteData(&kSecretMsg, &num_bytes,
  613. MOJO_WRITE_DATA_FLAG_NONE));
  614. EXPECT_EQ(kSecretMsg, Read(post_tls_recv_handle(), kSecretMsgSize));
  615. base::RunLoop().RunUntilIdle();
  616. EXPECT_TRUE(ssl_socket.ConnectDataConsumed());
  617. EXPECT_TRUE(data_provider.AllReadDataConsumed());
  618. EXPECT_TRUE(data_provider.AllWriteDataConsumed());
  619. }
  620. // Tests that writing to the pre-tls data pipe is okay even after UpgradeToTLS
  621. // is called.
  622. TEST_P(TLSClientSocketTest, WriteToPreTlsDataPipeAfterUpgradeToTLS) {
  623. const net::MockRead kReads[] = {
  624. net::MockRead(net::ASYNC, kSecretMsg, kSecretMsgSize, 2),
  625. net::MockRead(net::SYNCHRONOUS, net::OK, 3)};
  626. const net::MockWrite kWrites[] = {
  627. net::MockWrite(net::SYNCHRONOUS, kMsg, kMsgSize, 0),
  628. net::MockWrite(net::SYNCHRONOUS, kSecretMsg, kSecretMsgSize, 1)};
  629. net::SequencedSocketData data_provider(kReads, kWrites);
  630. data_provider.set_connect_data(net::MockConnect(net::SYNCHRONOUS, net::OK));
  631. mock_client_socket_factory()->AddSocketDataProvider(&data_provider);
  632. net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK);
  633. mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket);
  634. SocketHandle client_socket;
  635. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(), 1234);
  636. EXPECT_EQ(net::OK,
  637. CreateSocketSync(MakeRequest(&client_socket), server_addr));
  638. net::HostPortPair host_port_pair("example.org", 443);
  639. pre_tls_recv_handle()->reset();
  640. net::TestCompletionCallback callback;
  641. mojo::Remote<mojom::TLSClientSocket> tls_socket;
  642. UpgradeToTLS(&client_socket, host_port_pair,
  643. tls_socket.BindNewPipeAndPassReceiver(), callback.callback());
  644. base::RunLoop().RunUntilIdle();
  645. uint32_t num_bytes = strlen(kMsg);
  646. EXPECT_EQ(MOJO_RESULT_OK, pre_tls_send_handle()->get().WriteData(
  647. &kMsg, &num_bytes, MOJO_WRITE_DATA_FLAG_NONE));
  648. // Reset pre-tls send pipe now and UpgradeToTLS should complete.
  649. pre_tls_send_handle()->reset();
  650. ASSERT_EQ(net::OK, callback.WaitForResult());
  651. ResetSocket(&client_socket);
  652. num_bytes = strlen(kSecretMsg);
  653. EXPECT_EQ(MOJO_RESULT_OK,
  654. post_tls_send_handle()->get().WriteData(&kSecretMsg, &num_bytes,
  655. MOJO_WRITE_DATA_FLAG_NONE));
  656. EXPECT_EQ(kSecretMsg, Read(post_tls_recv_handle(), kSecretMsgSize));
  657. base::RunLoop().RunUntilIdle();
  658. EXPECT_TRUE(ssl_socket.ConnectDataConsumed());
  659. EXPECT_TRUE(data_provider.AllReadDataConsumed());
  660. EXPECT_TRUE(data_provider.AllWriteDataConsumed());
  661. }
  662. // Tests that reading from and writing to pre-tls data pipe is okay even after
  663. // UpgradeToTLS is called.
  664. TEST_P(TLSClientSocketTest, ReadAndWritePreTlsDataPipeAfterUpgradeToTLS) {
  665. const net::MockRead kReads[] = {
  666. net::MockRead(net::ASYNC, kMsg, kMsgSize, 0),
  667. net::MockRead(net::ASYNC, kSecretMsg, kSecretMsgSize, 3),
  668. net::MockRead(net::SYNCHRONOUS, net::OK, 4)};
  669. const net::MockWrite kWrites[] = {
  670. net::MockWrite(net::SYNCHRONOUS, kMsg, kMsgSize, 1),
  671. net::MockWrite(net::SYNCHRONOUS, kSecretMsg, kSecretMsgSize, 2)};
  672. net::SequencedSocketData data_provider(kReads, kWrites);
  673. data_provider.set_connect_data(net::MockConnect(net::SYNCHRONOUS, net::OK));
  674. mock_client_socket_factory()->AddSocketDataProvider(&data_provider);
  675. net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK);
  676. mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket);
  677. SocketHandle client_socket;
  678. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(), 1234);
  679. EXPECT_EQ(net::OK,
  680. CreateSocketSync(MakeRequest(&client_socket), server_addr));
  681. net::HostPortPair host_port_pair("example.org", 443);
  682. base::RunLoop run_loop;
  683. net::TestCompletionCallback callback;
  684. mojo::Remote<mojom::TLSClientSocket> tls_socket;
  685. UpgradeToTLS(&client_socket, host_port_pair,
  686. tls_socket.BindNewPipeAndPassReceiver(), callback.callback());
  687. EXPECT_EQ(kMsg, Read(pre_tls_recv_handle(), kMsgSize));
  688. uint32_t num_bytes = strlen(kMsg);
  689. EXPECT_EQ(MOJO_RESULT_OK, pre_tls_send_handle()->get().WriteData(
  690. &kMsg, &num_bytes, MOJO_WRITE_DATA_FLAG_NONE));
  691. // Reset pre-tls pipes now and UpgradeToTLS should complete.
  692. pre_tls_recv_handle()->reset();
  693. pre_tls_send_handle()->reset();
  694. ASSERT_EQ(net::OK, callback.WaitForResult());
  695. ResetSocket(&client_socket);
  696. num_bytes = strlen(kSecretMsg);
  697. EXPECT_EQ(MOJO_RESULT_OK,
  698. post_tls_send_handle()->get().WriteData(&kSecretMsg, &num_bytes,
  699. MOJO_WRITE_DATA_FLAG_NONE));
  700. EXPECT_EQ(kSecretMsg, Read(post_tls_recv_handle(), kSecretMsgSize));
  701. base::RunLoop().RunUntilIdle();
  702. EXPECT_TRUE(ssl_socket.ConnectDataConsumed());
  703. EXPECT_TRUE(data_provider.AllReadDataConsumed());
  704. EXPECT_TRUE(data_provider.AllWriteDataConsumed());
  705. }
  706. // Tests that a read error is encountered before UpgradeToTLS completes.
  707. TEST_P(TLSClientSocketTest, ReadErrorBeforeUpgradeToTLS) {
  708. // This requires pre_tls_observer(), which is not provided by proxy resolving
  709. // sockets.
  710. if (mode() != kDirect)
  711. return;
  712. const net::MockRead kReads[] = {
  713. net::MockRead(net::ASYNC, kMsg, kMsgSize, 0),
  714. net::MockRead(net::SYNCHRONOUS, net::ERR_CONNECTION_CLOSED, 1)};
  715. net::SequencedSocketData data_provider(kReads, base::span<net::MockWrite>());
  716. data_provider.set_connect_data(net::MockConnect(net::SYNCHRONOUS, net::OK));
  717. mock_client_socket_factory()->AddSocketDataProvider(&data_provider);
  718. SocketHandle client_socket;
  719. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(), 1234);
  720. EXPECT_EQ(net::OK,
  721. CreateSocketSync(MakeRequest(&client_socket), server_addr));
  722. net::HostPortPair host_port_pair("example.org", 443);
  723. pre_tls_send_handle()->reset();
  724. net::TestCompletionCallback callback;
  725. mojo::Remote<mojom::TLSClientSocket> tls_socket;
  726. UpgradeToTLS(&client_socket, host_port_pair,
  727. tls_socket.BindNewPipeAndPassReceiver(), callback.callback());
  728. EXPECT_EQ(kMsg, Read(pre_tls_recv_handle(), kMsgSize));
  729. EXPECT_EQ(net::ERR_CONNECTION_CLOSED, pre_tls_observer()->WaitForReadError());
  730. // Reset pre-tls receive pipe now and UpgradeToTLS should complete.
  731. pre_tls_recv_handle()->reset();
  732. ASSERT_EQ(net::ERR_SOCKET_NOT_CONNECTED, callback.WaitForResult());
  733. ResetSocket(&client_socket);
  734. base::RunLoop().RunUntilIdle();
  735. EXPECT_TRUE(data_provider.AllReadDataConsumed());
  736. EXPECT_TRUE(data_provider.AllWriteDataConsumed());
  737. }
  738. // Tests that a write error is encountered before UpgradeToTLS completes.
  739. TEST_P(TLSClientSocketTest, WriteErrorBeforeUpgradeToTLS) {
  740. // This requires pre_tls_observer(), which is not provided by proxy resolving
  741. // sockets.
  742. if (mode() != kDirect)
  743. return;
  744. const net::MockRead kReads[] = {net::MockRead(net::ASYNC, net::OK, 1)};
  745. const net::MockWrite kWrites[] = {
  746. net::MockWrite(net::SYNCHRONOUS, net::ERR_CONNECTION_CLOSED, 0)};
  747. net::SequencedSocketData data_provider(kReads, kWrites);
  748. data_provider.set_connect_data(net::MockConnect(net::SYNCHRONOUS, net::OK));
  749. mock_client_socket_factory()->AddSocketDataProvider(&data_provider);
  750. SocketHandle client_socket;
  751. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(), 1234);
  752. EXPECT_EQ(net::OK,
  753. CreateSocketSync(MakeRequest(&client_socket), server_addr));
  754. net::HostPortPair host_port_pair("example.org", 443);
  755. pre_tls_recv_handle()->reset();
  756. net::TestCompletionCallback callback;
  757. mojo::Remote<mojom::TLSClientSocket> tls_socket;
  758. UpgradeToTLS(&client_socket, host_port_pair,
  759. tls_socket.BindNewPipeAndPassReceiver(), callback.callback());
  760. uint32_t num_bytes = strlen(kMsg);
  761. EXPECT_EQ(MOJO_RESULT_OK, pre_tls_send_handle()->get().WriteData(
  762. &kMsg, &num_bytes, MOJO_WRITE_DATA_FLAG_NONE));
  763. EXPECT_EQ(net::ERR_CONNECTION_CLOSED,
  764. pre_tls_observer()->WaitForWriteError());
  765. // Reset pre-tls send pipe now and UpgradeToTLS should complete.
  766. pre_tls_send_handle()->reset();
  767. ASSERT_EQ(net::ERR_SOCKET_NOT_CONNECTED, callback.WaitForResult());
  768. ResetSocket(&client_socket);
  769. base::RunLoop().RunUntilIdle();
  770. // Write failed before the mock read can be consumed.
  771. EXPECT_FALSE(data_provider.AllReadDataConsumed());
  772. EXPECT_TRUE(data_provider.AllWriteDataConsumed());
  773. }
  774. INSTANTIATE_TEST_SUITE_P(
  775. All,
  776. TLSClientSocketTest,
  777. ::testing::Values(TLSClientSocketTestBase::kDirect,
  778. TLSClientSocketTestBase::kProxyResolving));
  779. // Tests with proxy resolving socket and a proxy actually configured.
  780. class TLSCLientSocketProxyTest : public ::testing::Test,
  781. public TLSClientSocketTestBase {
  782. public:
  783. TLSCLientSocketProxyTest()
  784. : TLSClientSocketTestBase(TLSClientSocketTestBase::kProxyResolving) {
  785. Init(true /* use_mock_sockets*/, true /* configure_proxy */);
  786. }
  787. TLSCLientSocketProxyTest(const TLSCLientSocketProxyTest&) = delete;
  788. TLSCLientSocketProxyTest& operator=(const TLSCLientSocketProxyTest&) = delete;
  789. ~TLSCLientSocketProxyTest() override {}
  790. };
  791. TEST_F(TLSCLientSocketProxyTest, UpgradeToTLS) {
  792. const char kConnectRequest[] =
  793. "CONNECT 192.168.1.1:1234 HTTP/1.1\r\n"
  794. "Host: 192.168.1.1:1234\r\n"
  795. "Proxy-Connection: keep-alive\r\n\r\n";
  796. const char kConnectResponse[] = "HTTP/1.1 200 OK\r\n\r\n";
  797. const net::MockRead kReads[] = {
  798. net::MockRead(net::ASYNC, kConnectResponse, strlen(kConnectResponse), 1),
  799. net::MockRead(net::ASYNC, kMsg, kMsgSize, 3),
  800. net::MockRead(net::SYNCHRONOUS, net::OK, 4)};
  801. const net::MockWrite kWrites[] = {
  802. net::MockWrite(net::ASYNC, kConnectRequest, strlen(kConnectRequest), 0),
  803. net::MockWrite(net::SYNCHRONOUS, kMsg, kMsgSize, 2)};
  804. net::SequencedSocketData data_provider(kReads, kWrites);
  805. data_provider.set_connect_data(net::MockConnect(net::SYNCHRONOUS, net::OK));
  806. mock_client_socket_factory()->AddSocketDataProvider(&data_provider);
  807. net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK);
  808. mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket);
  809. SocketHandle client_socket;
  810. net::IPEndPoint server_addr(net::IPAddress(192, 168, 1, 1), 1234);
  811. EXPECT_EQ(net::OK,
  812. CreateSocketSync(MakeRequest(&client_socket), server_addr));
  813. net::HostPortPair host_port_pair("example.org", 443);
  814. pre_tls_recv_handle()->reset();
  815. pre_tls_send_handle()->reset();
  816. net::TestCompletionCallback callback;
  817. mojo::Remote<mojom::TLSClientSocket> tls_socket;
  818. UpgradeToTLS(&client_socket, host_port_pair,
  819. tls_socket.BindNewPipeAndPassReceiver(), callback.callback());
  820. ASSERT_EQ(net::OK, callback.WaitForResult());
  821. ResetSocket(&client_socket);
  822. uint32_t num_bytes = strlen(kMsg);
  823. EXPECT_EQ(MOJO_RESULT_OK, post_tls_send_handle()->get().WriteData(
  824. &kMsg, &num_bytes, MOJO_WRITE_DATA_FLAG_NONE));
  825. EXPECT_EQ(kMsg, Read(post_tls_recv_handle(), kMsgSize));
  826. base::RunLoop().RunUntilIdle();
  827. EXPECT_TRUE(ssl_socket.ConnectDataConsumed());
  828. EXPECT_TRUE(data_provider.AllReadDataConsumed());
  829. EXPECT_TRUE(data_provider.AllWriteDataConsumed());
  830. }
  831. class TLSClientSocketIoModeTest : public TLSClientSocketTestBase,
  832. public testing::TestWithParam<net::IoMode> {
  833. public:
  834. TLSClientSocketIoModeTest()
  835. : TLSClientSocketTestBase(TLSClientSocketTestBase::kDirect) {
  836. Init(true /* use_mock_sockets*/, false /* configure_proxy */);
  837. }
  838. TLSClientSocketIoModeTest(const TLSClientSocketIoModeTest&) = delete;
  839. TLSClientSocketIoModeTest& operator=(const TLSClientSocketIoModeTest&) =
  840. delete;
  841. ~TLSClientSocketIoModeTest() override {}
  842. };
  843. INSTANTIATE_TEST_SUITE_P(All,
  844. TLSClientSocketIoModeTest,
  845. testing::Values(net::SYNCHRONOUS, net::ASYNC));
  846. TEST_P(TLSClientSocketIoModeTest, MultipleWriteToTLSSocket) {
  847. const int kNumIterations = 3;
  848. std::vector<net::MockRead> reads;
  849. std::vector<net::MockWrite> writes;
  850. int sequence_number = 0;
  851. net::IoMode mode = GetParam();
  852. for (int j = 0; j < kNumIterations; ++j) {
  853. for (size_t i = 0; i < kSecretMsgSize; ++i) {
  854. writes.push_back(
  855. net::MockWrite(mode, &kSecretMsg[i], 1, sequence_number++));
  856. }
  857. for (size_t i = 0; i < kSecretMsgSize; ++i) {
  858. reads.push_back(
  859. net::MockRead(net::ASYNC, &kSecretMsg[i], 1, sequence_number++));
  860. }
  861. if (j == kNumIterations - 1) {
  862. reads.push_back(net::MockRead(mode, net::OK, sequence_number++));
  863. }
  864. }
  865. net::SequencedSocketData data_provider(reads, writes);
  866. data_provider.set_connect_data(net::MockConnect(GetParam(), net::OK));
  867. mock_client_socket_factory()->AddSocketDataProvider(&data_provider);
  868. net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK);
  869. mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket);
  870. mojo::Remote<mojom::TCPConnectedSocket> client_socket;
  871. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(), 1234);
  872. EXPECT_EQ(net::OK,
  873. CreateTCPConnectedSocketSync(
  874. client_socket.BindNewPipeAndPassReceiver(), server_addr));
  875. net::HostPortPair host_port_pair("example.org", 443);
  876. pre_tls_recv_handle()->reset();
  877. pre_tls_send_handle()->reset();
  878. net::TestCompletionCallback callback;
  879. mojo::Remote<mojom::TLSClientSocket> tls_socket;
  880. UpgradeTCPConnectedSocketToTLS(
  881. client_socket.get(), host_port_pair, nullptr /* options */,
  882. tls_socket.BindNewPipeAndPassReceiver(), callback.callback());
  883. ASSERT_EQ(net::OK, callback.WaitForResult());
  884. client_socket.reset();
  885. EXPECT_FALSE(ssl_info());
  886. // Loop kNumIterations times to test that writes can follow reads, and reads
  887. // can follow writes.
  888. for (int j = 0; j < kNumIterations; ++j) {
  889. // Write multiple times.
  890. for (size_t i = 0; i < kSecretMsgSize; ++i) {
  891. uint32_t num_bytes = 1;
  892. EXPECT_EQ(MOJO_RESULT_OK,
  893. post_tls_send_handle()->get().WriteData(
  894. &kSecretMsg[i], &num_bytes, MOJO_WRITE_DATA_FLAG_NONE));
  895. // Flush the 1 byte write.
  896. base::RunLoop().RunUntilIdle();
  897. }
  898. // Reading kSecretMsgSize should coalesce the 1-byte mock reads.
  899. EXPECT_EQ(kSecretMsg, Read(post_tls_recv_handle(), kSecretMsgSize));
  900. }
  901. EXPECT_TRUE(ssl_socket.ConnectDataConsumed());
  902. EXPECT_TRUE(data_provider.AllReadDataConsumed());
  903. EXPECT_TRUE(data_provider.AllWriteDataConsumed());
  904. }
  905. // Check SSLInfo is provided in both sync and async cases.
  906. TEST_P(TLSClientSocketIoModeTest, SSLInfo) {
  907. // End of file. Reads don't matter, only the handshake does.
  908. std::vector<net::MockRead> reads = {net::MockRead(net::SYNCHRONOUS, net::OK)};
  909. std::vector<net::MockWrite> writes;
  910. net::SequencedSocketData data_provider(reads, writes);
  911. data_provider.set_connect_data(net::MockConnect(net::SYNCHRONOUS, net::OK));
  912. mock_client_socket_factory()->AddSocketDataProvider(&data_provider);
  913. net::SSLSocketDataProvider ssl_socket(GetParam(), net::OK);
  914. // Set a value on SSLInfo to make sure it's correctly received.
  915. ssl_socket.ssl_info.is_issued_by_known_root = true;
  916. mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket);
  917. mojo::Remote<mojom::TCPConnectedSocket> client_socket;
  918. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(), 1234);
  919. EXPECT_EQ(net::OK,
  920. CreateTCPConnectedSocketSync(
  921. client_socket.BindNewPipeAndPassReceiver(), server_addr));
  922. net::HostPortPair host_port_pair("example.org", 443);
  923. pre_tls_recv_handle()->reset();
  924. pre_tls_send_handle()->reset();
  925. net::TestCompletionCallback callback;
  926. mojo::Remote<mojom::TLSClientSocket> tls_socket;
  927. mojom::TLSClientSocketOptionsPtr options =
  928. mojom::TLSClientSocketOptions::New();
  929. options->send_ssl_info = true;
  930. UpgradeTCPConnectedSocketToTLS(
  931. client_socket.get(), host_port_pair, std::move(options),
  932. tls_socket.BindNewPipeAndPassReceiver(), callback.callback());
  933. ASSERT_EQ(net::OK, callback.WaitForResult());
  934. ASSERT_TRUE(ssl_info());
  935. EXPECT_TRUE(ssl_socket.ssl_info.is_issued_by_known_root);
  936. EXPECT_FALSE(ssl_socket.ssl_info.is_fatal_cert_error);
  937. }
  938. class TLSClientSocketTestWithEmbeddedTestServerBase
  939. : public TLSClientSocketTestBase {
  940. public:
  941. explicit TLSClientSocketTestWithEmbeddedTestServerBase(Mode mode)
  942. : TLSClientSocketTestBase(mode),
  943. server_(net::EmbeddedTestServer::TYPE_HTTPS) {
  944. Init(false /* use_mock_sockets */, false /* configure_proxy */);
  945. }
  946. TLSClientSocketTestWithEmbeddedTestServerBase(
  947. const TLSClientSocketTestWithEmbeddedTestServerBase&) = delete;
  948. TLSClientSocketTestWithEmbeddedTestServerBase& operator=(
  949. const TLSClientSocketTestWithEmbeddedTestServerBase&) = delete;
  950. ~TLSClientSocketTestWithEmbeddedTestServerBase() override {}
  951. // Starts the test server using the specified certificate.
  952. [[nodiscard]] bool StartTestServer(
  953. net::EmbeddedTestServer::ServerCertificate certificate) {
  954. server_.RegisterRequestHandler(
  955. base::BindRepeating([](const net::test_server::HttpRequest& request) {
  956. if (base::StartsWith(request.relative_url, "/secret",
  957. base::CompareCase::INSENSITIVE_ASCII)) {
  958. return std::unique_ptr<net::test_server::HttpResponse>(
  959. new net::test_server::RawHttpResponse("HTTP/1.1 200 OK",
  960. "Hello There!"));
  961. }
  962. return std::unique_ptr<net::test_server::HttpResponse>();
  963. }));
  964. server_.SetSSLConfig(certificate);
  965. return server_.Start();
  966. }
  967. // Attempts to eastablish a TLS connection to the test server by first
  968. // establishing a TCP connection, and then upgrading it. Returns the
  969. // resulting network error code.
  970. [[nodiscard]] int CreateTLSSocket() {
  971. SocketHandle client_socket;
  972. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(),
  973. server_.port());
  974. EXPECT_EQ(net::OK,
  975. CreateSocketSync(MakeRequest(&client_socket), server_addr));
  976. pre_tls_recv_handle()->reset();
  977. pre_tls_send_handle()->reset();
  978. net::TestCompletionCallback callback;
  979. UpgradeToTLS(&client_socket, server_.host_port_pair(),
  980. tls_socket_.BindNewPipeAndPassReceiver(), callback.callback());
  981. int result = callback.WaitForResult();
  982. ResetSocket(&client_socket);
  983. return result;
  984. }
  985. [[nodiscard]] int CreateTLSSocketWithOptions(
  986. mojom::TLSClientSocketOptionsPtr options) {
  987. // Proxy connections don't support TLSClientSocketOptions.
  988. DCHECK_EQ(kDirect, mode());
  989. mojo::Remote<mojom::TCPConnectedSocket> tcp_socket;
  990. net::IPEndPoint server_addr(net::IPAddress::IPv4Localhost(),
  991. server_.port());
  992. EXPECT_EQ(net::OK,
  993. CreateTCPConnectedSocketSync(
  994. tcp_socket.BindNewPipeAndPassReceiver(), server_addr));
  995. pre_tls_recv_handle()->reset();
  996. pre_tls_send_handle()->reset();
  997. net::TestCompletionCallback callback;
  998. UpgradeTCPConnectedSocketToTLS(
  999. tcp_socket.get(), server_.host_port_pair(), std::move(options),
  1000. tls_socket_.BindNewPipeAndPassReceiver(), callback.callback());
  1001. int result = callback.WaitForResult();
  1002. tcp_socket.reset();
  1003. return result;
  1004. }
  1005. void TestTlsSocket() {
  1006. ASSERT_TRUE(tls_socket_.is_bound());
  1007. const char kTestMsg[] = "GET /secret HTTP/1.1\r\n\r\n";
  1008. uint32_t num_bytes = strlen(kTestMsg);
  1009. const char kResponse[] = "HTTP/1.1 200 OK\n\n";
  1010. EXPECT_EQ(MOJO_RESULT_OK,
  1011. post_tls_send_handle()->get().WriteData(
  1012. &kTestMsg, &num_bytes, MOJO_WRITE_DATA_FLAG_NONE));
  1013. EXPECT_EQ(kResponse, Read(post_tls_recv_handle(), strlen(kResponse)));
  1014. }
  1015. net::EmbeddedTestServer* server() { return &server_; }
  1016. private:
  1017. net::EmbeddedTestServer server_;
  1018. mojo::Remote<mojom::TLSClientSocket> tls_socket_;
  1019. };
  1020. class TLSClientSocketTestWithEmbeddedTestServer
  1021. : public TLSClientSocketTestWithEmbeddedTestServerBase,
  1022. public ::testing::TestWithParam<TLSClientSocketTestBase::Mode> {
  1023. public:
  1024. TLSClientSocketTestWithEmbeddedTestServer()
  1025. : TLSClientSocketTestWithEmbeddedTestServerBase(GetParam()) {}
  1026. TLSClientSocketTestWithEmbeddedTestServer(
  1027. const TLSClientSocketTestWithEmbeddedTestServer&) = delete;
  1028. TLSClientSocketTestWithEmbeddedTestServer& operator=(
  1029. const TLSClientSocketTestWithEmbeddedTestServer&) = delete;
  1030. ~TLSClientSocketTestWithEmbeddedTestServer() override {}
  1031. };
  1032. TEST_P(TLSClientSocketTestWithEmbeddedTestServer, Basic) {
  1033. ASSERT_TRUE(StartTestServer(net::EmbeddedTestServer::CERT_OK));
  1034. ASSERT_EQ(net::OK, CreateTLSSocket());
  1035. // No SSLInfo should be received by default. SSLInfo is only supported in the
  1036. // kDirect case, but it doesn't hurt to check it's null it in the
  1037. // kProxyResolving case.
  1038. EXPECT_FALSE(ssl_info());
  1039. TestTlsSocket();
  1040. }
  1041. TEST_P(TLSClientSocketTestWithEmbeddedTestServer, ServerCertError) {
  1042. ASSERT_TRUE(StartTestServer(net::EmbeddedTestServer::CERT_MISMATCHED_NAME));
  1043. ASSERT_EQ(net::ERR_CERT_COMMON_NAME_INVALID, CreateTLSSocket());
  1044. // No SSLInfo should be received by default. SSLInfo is only supported in the
  1045. // kDirect case, but it doesn't hurt to check it's null in the kProxyResolving
  1046. // case.
  1047. EXPECT_FALSE(ssl_info());
  1048. // Handles should be invalid.
  1049. EXPECT_FALSE(post_tls_recv_handle()->is_valid());
  1050. EXPECT_FALSE(post_tls_send_handle()->is_valid());
  1051. }
  1052. INSTANTIATE_TEST_SUITE_P(
  1053. All,
  1054. TLSClientSocketTestWithEmbeddedTestServer,
  1055. ::testing::Values(TLSClientSocketTestBase::kDirect,
  1056. TLSClientSocketTestBase::kProxyResolving));
  1057. class TLSClientSocketDirectTestWithEmbeddedTestServer
  1058. : public TLSClientSocketTestWithEmbeddedTestServerBase,
  1059. public testing::Test {
  1060. public:
  1061. TLSClientSocketDirectTestWithEmbeddedTestServer()
  1062. : TLSClientSocketTestWithEmbeddedTestServerBase(kDirect) {}
  1063. TLSClientSocketDirectTestWithEmbeddedTestServer(
  1064. const TLSClientSocketDirectTestWithEmbeddedTestServer&) = delete;
  1065. TLSClientSocketDirectTestWithEmbeddedTestServer& operator=(
  1066. const TLSClientSocketDirectTestWithEmbeddedTestServer&) = delete;
  1067. ~TLSClientSocketDirectTestWithEmbeddedTestServer() override {}
  1068. };
  1069. TEST_F(TLSClientSocketDirectTestWithEmbeddedTestServer, SSLInfo) {
  1070. ASSERT_TRUE(StartTestServer(net::EmbeddedTestServer::CERT_OK));
  1071. mojom::TLSClientSocketOptionsPtr options =
  1072. mojom::TLSClientSocketOptions::New();
  1073. options->send_ssl_info = true;
  1074. ASSERT_EQ(net::OK, CreateTLSSocketWithOptions(std::move(options)));
  1075. ASSERT_TRUE(ssl_info());
  1076. EXPECT_TRUE(ssl_info()->is_valid());
  1077. EXPECT_FALSE(ssl_info()->is_fatal_cert_error);
  1078. TestTlsSocket();
  1079. }
  1080. TEST_F(TLSClientSocketDirectTestWithEmbeddedTestServer,
  1081. SSLInfoServerCertError) {
  1082. ASSERT_TRUE(StartTestServer(net::EmbeddedTestServer::CERT_MISMATCHED_NAME));
  1083. mojom::TLSClientSocketOptionsPtr options =
  1084. mojom::TLSClientSocketOptions::New();
  1085. options->send_ssl_info = true;
  1086. // Requesting SSLInfo should not bypass cert verification.
  1087. ASSERT_EQ(net::ERR_CERT_COMMON_NAME_INVALID,
  1088. CreateTLSSocketWithOptions(std::move(options)));
  1089. // No SSLInfo should be provided on error.
  1090. EXPECT_FALSE(ssl_info());
  1091. // Handles should be invalid.
  1092. EXPECT_FALSE(post_tls_recv_handle()->is_valid());
  1093. EXPECT_FALSE(post_tls_send_handle()->is_valid());
  1094. }
  1095. // Check skipping cert verification always received SSLInfo, even with valid
  1096. // certs.
  1097. TEST_F(TLSClientSocketDirectTestWithEmbeddedTestServer,
  1098. UnsafelySkipCertVerification) {
  1099. ASSERT_TRUE(StartTestServer(net::EmbeddedTestServer::CERT_OK));
  1100. mojom::TLSClientSocketOptionsPtr options =
  1101. mojom::TLSClientSocketOptions::New();
  1102. options->unsafely_skip_cert_verification = true;
  1103. ASSERT_EQ(net::OK, CreateTLSSocketWithOptions(std::move(options)));
  1104. ASSERT_TRUE(ssl_info());
  1105. EXPECT_TRUE(ssl_info()->is_valid());
  1106. EXPECT_FALSE(ssl_info()->is_fatal_cert_error);
  1107. TestTlsSocket();
  1108. }
  1109. TEST_F(TLSClientSocketDirectTestWithEmbeddedTestServer,
  1110. UnsafelySkipCertVerificationServerCertError) {
  1111. ASSERT_TRUE(StartTestServer(net::EmbeddedTestServer::CERT_MISMATCHED_NAME));
  1112. mojom::TLSClientSocketOptionsPtr options =
  1113. mojom::TLSClientSocketOptions::New();
  1114. options->unsafely_skip_cert_verification = true;
  1115. ASSERT_EQ(net::OK, CreateTLSSocketWithOptions(std::move(options)));
  1116. ASSERT_TRUE(ssl_info());
  1117. EXPECT_TRUE(ssl_info()->is_valid());
  1118. EXPECT_FALSE(ssl_info()->is_fatal_cert_error);
  1119. TestTlsSocket();
  1120. }
  1121. } // namespace
  1122. } // namespace network