summaryrefslogtreecommitdiff
path: root/socks5.cpp
blob: 641c086dcb8d75990d2f6862d0b68692203c3008 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
#include "socks5.hpp"

#include <boost/asio/completion_condition.hpp>
#include <boost/asio/impl/write.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/address_v4.hpp>
#include <boost/asio/ip/address_v6.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/strand.hpp>
#include <boost/bind/bind.hpp>
#include <boost/system/detail/error_code.hpp>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>

using namespace SOCKS5;
using boost::asio::io_context;
using boost::asio::ip::tcp;

ProxySessionBase::ProxySessionBase(std::uint32_t session_id,
                                   tcp::socket &&client_socket,
                                   std::size_t buffer_size)
    : m_sessionId{session_id}, m_inBuf{buffer_size}, m_outBuf{buffer_size},
      m_clientSocket{std::move(client_socket)} {}

ProxySessionBase::ProxySessionBase(std::uint32_t session_id,
                                   boost::asio::ip::tcp::socket &&client_socket,
                                   ContiguousStreamBuffer &&input_buffer,
                                   ContiguousStreamBuffer &&output_buffer)
    : m_sessionId{session_id}, m_inBuf{std::move(input_buffer)},
      m_outBuf{std::move(output_buffer)},
      m_clientSocket{std::move(client_socket)} {}

void ProxySessionBase::async_read(const CompletionHandler &handler,
                                  std::size_t expected_length) {
  if (expected_length == 0)
    m_clientSocket.async_read_some(
        +m_inBuf, [this, handler](const boost::system::error_code &ec,
                                  const std::size_t length) {
          if (ec || length == 0)
            return;
          handler(length);
        });
  else
    boost::asio::async_read(
        m_clientSocket, +m_inBuf,
        boost::asio::transfer_exactly(expected_length),
        [this, expected_length, handler](const boost::system::error_code &ec,
                                         const std::size_t length) {
          if (ec || length != expected_length)
            return;
          handler(length);
        });
}

ProxySessionAuth::ProxySessionAuth(std::uint32_t session_id,
                                   tcp::socket &&client_socket)
    : ProxySessionBase(session_id, std::move(client_socket), 32),
      m_resolver{m_clientSocket.get_executor()},
      m_destinationSocket{m_clientSocket.get_executor()} {}

void ProxySessionAuth::start() {
  async_read([self = shared_from_this()](
                 std::size_t length) { self->recv_client_greeting(length); },
             2);
}

void ProxySessionAuth::recv_client_greeting(std::size_t length) {
  m_inBuf += length;

  if (m_inBuf[0] != 0x05 || m_inBuf[1] > 0x09 || m_inBuf[1] == 0x00)
    return;
  const std::size_t expected_size = std::size_t(2) + m_inBuf[1];
  if (m_inBuf.size() < expected_size) {
    async_read([self = shared_from_this(), expected_size](
                   std::size_t length) { self->recv_client_greeting(length); },
               expected_size - m_inBuf.size());
    return;
  }

  auto found_no_auth = false; // only No Authentication supported
  for (auto i = std::size_t(2); i < expected_size; ++i) {
    if (m_inBuf[i] == 0x00) {
      found_no_auth = true;
      break;
    }
  }

  m_inBuf -= expected_size;
  send_server_greeting(found_no_auth);
}

void ProxySessionAuth::send_server_greeting(bool auth_supported) {
  if (!auth_supported) {
    m_outBuf += {0x05, 0xFF};
    m_clientSocket.async_send(
        -m_outBuf,
        boost::bind(&ProxySessionAuth::handle_write, shared_from_this(),
                    boost::asio::placeholders::error,
                    boost::asio::placeholders::bytes_transferred));
    return;
  }

  m_outBuf += {0x05, 0x00};
  m_clientSocket.async_send(
      -m_outBuf,
      boost::bind(&ProxySessionAuth::handle_write, shared_from_this(),
                  boost::asio::placeholders::error,
                  boost::asio::placeholders::bytes_transferred));
  async_read([self = shared_from_this()](
                 std::size_t length) { self->recv_connection_request(length); },
             6);
}

void ProxySessionAuth::recv_connection_request(std::size_t length) {
  m_inBuf += length;
  process_connection_request();
}

void ProxySessionAuth::process_connection_request() {
  if (m_inBuf[0] != 0x05 || m_inBuf[1] > 0x03 || m_inBuf[2] != 0x00)
    return;

  size_t expected_size = 0;
  uint8_t address_size;
  switch (m_inBuf[3]) {
  // IPv4 Address
  case 0x01:
    address_size = 4;
    break;
  // DNS FQDN
  case 0x03:
    address_size = m_inBuf[4];
    expected_size++;
    break;
  // IPv6 Address
  case 0x04:
    address_size = 16;
    break;
  default:
    return;
  }

  expected_size += std::size_t(6) + address_size;
  if (m_inBuf.size() < expected_size) {
    async_read(
        [self = shared_from_this(), expected_size](std::size_t length) {
          self->recv_connection_request(length);
        },
        expected_size - m_inBuf.size());
    return;
  }

  const uint8_t proxy_cmd = m_inBuf[1];
  switch (m_inBuf[3]) {
  case 0x01: {
    auto ip4_bytes = ::ntohl(*reinterpret_cast<const uint32_t *>(m_inBuf(4)));
    m_endpoint = tcp::endpoint(boost::asio::ip::make_address_v4(ip4_bytes),
                               ::ntohs(*reinterpret_cast<const uint16_t *>(
                                   m_inBuf(4 + address_size))));
    connect_to_destination(proxy_cmd);
    return;
  }
  case 0x03: {
    auto host = std::string_view(reinterpret_cast<const char *>(m_inBuf(5)),
                                 address_size);
    auto port =
        ::ntohs(*reinterpret_cast<const uint16_t *>(m_inBuf(5 + address_size)));
    resolve_destination_host(proxy_cmd, host, port);
    return;
  }
  case 0x04: {
    auto ip6_array =
        *reinterpret_cast<const std::array<std::uint8_t, 16> *>(m_inBuf(4));
    m_endpoint = tcp::endpoint(boost::asio::ip::make_address_v6(ip6_array),
                               ::ntohs(*reinterpret_cast<const uint16_t *>(
                                   m_inBuf(4 + address_size))));
    connect_to_destination(proxy_cmd);
    return;
  }
  default:
    return;
  }
}

void ProxySessionAuth::send_server_response(std::uint8_t proxy_cmd,
                                            std::uint8_t status_code) {
  m_outBuf += {0x05, status_code, 0x00};
  // TODO: Set DNS domain if available
  if (m_endpoint.address().is_v4()) {
    const uint32_t addr = ::htonl(m_endpoint.address().to_v4().to_uint());
    m_outBuf += {0x01, static_cast<uint8_t>(addr & 0x000000FF),
                 static_cast<uint8_t>((addr & 0x0000FF00) >> 8),
                 static_cast<uint8_t>((addr & 0x00FF0000) >> 16),
                 static_cast<uint8_t>((addr & 0xFF000000) >> 24)};
  } else {
    m_outBuf += {0x04};
    const auto addr = m_endpoint.address().to_v6().to_bytes();
    for (const auto byte : addr)
      m_outBuf += {byte};
  }
  const auto port = ::htons(m_endpoint.port());
  m_outBuf += {static_cast<uint8_t>(port & 0x00FF),
               static_cast<uint8_t>((port & 0xFF00) >> 8)};
  m_clientSocket.async_send(
      -m_outBuf,
      boost::bind(&ProxySessionAuth::handle_response_write, shared_from_this(),
                  proxy_cmd, status_code, boost::asio::placeholders::error,
                  boost::asio::placeholders::bytes_transferred));
}

void ProxySessionAuth::resolve_destination_host(std::uint8_t proxy_cmd,
                                                const std::string_view &host,
                                                std::uint16_t port) {
  m_resolver.async_resolve(host, std::to_string(port),
                           [this, self = shared_from_this(),
                            proxy_cmd](const boost::system::error_code &ec,
                                       const tcp::resolver::iterator &it) {
                             if (ec) {
                               send_server_response(proxy_cmd, 0x04);
                               return;
                             }
                             /* TODO: Support iterating and connecting to
                              * multiple resolved hosts on failure. */
                             m_endpoint = *it;
                             connect_to_destination(proxy_cmd);
                           });
}

void ProxySessionAuth::connect_to_destination(std::uint8_t proxy_cmd) {
  switch (proxy_cmd) {
  case 0x01: // TCP client connection
  {
    m_destinationSocket.async_connect(
        m_endpoint, [this, self = shared_from_this(),
                     proxy_cmd](const boost::system::error_code &ec) {
          if (ec) {
            send_server_response(proxy_cmd, 0x04);
            return;
          }
          send_server_response(proxy_cmd, 0x00);
        });
    return;
  }
  case 0x02: // TCP port bind
  {
    send_server_response(proxy_cmd, 0x02);
    return;
  }
  case 0x03: // UDP port bind
  {
    send_server_response(proxy_cmd, 0x02);
    return;
  }
  default:
    send_server_response(proxy_cmd, 0x01);
    return;
  }
}

void ProxySessionAuth::handle_write(const boost::system::error_code &ec,
                                    std::size_t length) {
  if (ec || length == 0)
    m_clientSocket.cancel();
  m_outBuf -= length;

  if (m_outBuf.size() > 0)
    m_clientSocket.async_send(
        -m_outBuf,
        boost::bind(&ProxySessionAuth::handle_write, shared_from_this(),
                    boost::asio::placeholders::error,
                    boost::asio::placeholders::bytes_transferred));
}

void ProxySessionAuth::handle_response_write(
    std::uint8_t proxy_cmd, std::uint8_t status_code,
    const boost::system::error_code &ec, std::size_t length) {
  if (ec || length == 0)
    m_clientSocket.cancel();
  m_outBuf -= length;

  if (m_outBuf.size() > 0) {
    m_clientSocket.async_send(
        -m_outBuf, boost::bind(&ProxySessionAuth::handle_response_write,
                               shared_from_this(), proxy_cmd, status_code,
                               boost::asio::placeholders::error,
                               boost::asio::placeholders::bytes_transferred));
    return;
  }

  if (status_code == 0x00)
    switch (proxy_cmd) {
    case 0x01: // TCP client connection
    {
      auto tcp_session = std::make_shared<ProxySessionTcp>(
          m_sessionId, std::move(m_clientSocket),
          std::move(m_destinationSocket));
      tcp_session->start();
      break;
    }
    case 0x02: // TCP port bind
    {
      return;
    }
    case 0x03: // UDP port bind
    {
      return;
    }
    default:
      return;
    }
}

ProxySessionTcp::ProxySessionTcp(
    std::uint32_t session_id, boost::asio::ip::tcp::socket &&client_socket,
    boost::asio::ip::tcp::socket &&destination_socket, std::size_t buffer_size)
    : ProxySessionBase(session_id, std::move(client_socket), buffer_size),
      m_destinationSocket(std::move(destination_socket)) {}

void ProxySessionTcp::start() { recv_from_both(); }

void ProxySessionTcp::recv_from_both() {
  BOOST_ASIO_HANDLER_LOCATION((__FILE__, __LINE__, __func__));

  async_read([self = shared_from_this()](std::size_t length) {
    self->recv_from_client(length);
  });
  m_destinationSocket.async_read_some(
      +m_outBuf,
      boost::bind(&ProxySessionTcp::recv_from_destination, shared_from_this(),
                  boost::asio::placeholders::error,
                  boost::asio::placeholders::bytes_transferred));
}

void ProxySessionTcp::recv_from_destination(const boost::system::error_code &ec,
                                            std::size_t length) {
  BOOST_ASIO_HANDLER_LOCATION((__FILE__, __LINE__, __func__));

  if (ec || length == 0) {
    m_destinationSocket.cancel();
    return;
  }

  m_outBuf += length;
  boost::asio::async_write(
      m_clientSocket, -m_outBuf, boost::asio::transfer_all(),
      boost::bind(&ProxySessionTcp::handle_client_write, shared_from_this(),
                  boost::asio::placeholders::error,
                  boost::asio::placeholders::bytes_transferred));
}

void ProxySessionTcp::recv_from_client(
                                       std::size_t length) {
  BOOST_ASIO_HANDLER_LOCATION((__FILE__, __LINE__, __func__));

  m_inBuf += length;
  boost::asio::async_write(
      m_destinationSocket, -m_inBuf, boost::asio::transfer_exactly(length),
      boost::bind(&ProxySessionTcp::handle_destination_write,
                  shared_from_this(), boost::asio::placeholders::error,
                  boost::asio::placeholders::bytes_transferred));
}

void ProxySessionTcp::handle_client_write(const boost::system::error_code &ec,
                                          std::size_t length) {
  BOOST_ASIO_HANDLER_LOCATION((__FILE__, __LINE__, __func__));

  if (ec || length == 0) {
    m_clientSocket.cancel();
    return;
  }

  m_outBuf -= length;
  m_destinationSocket.async_read_some(
      +m_outBuf,
      boost::bind(&ProxySessionTcp::recv_from_destination, shared_from_this(),
                  boost::asio::placeholders::error,
                  boost::asio::placeholders::bytes_transferred));
}

void ProxySessionTcp::handle_destination_write(
    const boost::system::error_code &ec, std::size_t length) {
  BOOST_ASIO_HANDLER_LOCATION((__FILE__, __LINE__, __func__));

  if (ec || length == 0) {
    m_destinationSocket.cancel();
    return;
  }

  m_inBuf -= length;
  async_read([self = shared_from_this()](std::size_t length) {
    self->recv_from_client(length);
  });
}

ProxyServer::ProxyServer(io_context &ioc, const tcp::endpoint &local_endpoint)
    : m_nextSessionId{1}, m_acceptor(ioc, local_endpoint) {}

ProxyServer::ProxyServer(io_context &ioc, const std::string &listen_addr,
                         std::uint16_t listen_port)
    : ProxyServer(ioc, tcp::endpoint(boost::asio::ip::make_address(listen_addr),
                                     listen_port)) {}

void ProxyServer::start() { async_accept(); }

void ProxyServer::async_accept() {
  m_acceptor.async_accept(
      boost::asio::make_strand(m_acceptor.get_executor()),
      [this](const boost::system::error_code &ec, tcp::socket client_socket) {
        if (!ec) {
          auto auth_session = std::make_shared<ProxySessionAuth>(
              m_nextSessionId.fetch_add(1, std::memory_order_relaxed),
              std::move(client_socket));
          if (auth_session)
            auth_session->start();
        }
        async_accept();
      });
}