-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocks5ssh.cpp
More file actions
1785 lines (1575 loc) · 69.9 KB
/
Copy pathsocks5ssh.cpp
File metadata and controls
1785 lines (1575 loc) · 69.9 KB
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file socks5ssh.cpp
* @brief SOCKS5 Proxy over SSH — Event-Driven, Full Diagnostics
* @version 3.2.6
*
* High-performance SOCKS5 proxy forwarding traffic through SSH tunnels.
* Uses ssh_get_fd() integrated with boost::asio for event-driven I/O.
* Single fd watcher per tunnel eliminates thundering herd.
* All libssh calls serialized through strand (no mutex for SSH ops).
*
* @section Changes_v3_2_6
* - Fix: TCP Keep-Alive via setsockopt (SSH_OPTIONS_TCP_KEEPALIVE
* does not exist in libssh 0.12.0; now sets SO_KEEPALIVE +
* TCP_KEEPIDLE=60s + TCP_KEEPINTVL=15s + TCP_KEEPCNT=4 on SSH fd)
* - Fix: destroy() accessible via public shutdown() for graceful stop
* - Fix: GCC warn_unused_result on write() in signal handler
*
* @section Changes_v3_2_5
* - Fix: graceful shutdown via stop() instead of ioc.stop()
* (prevents Teardown UAF/segfault on Ctrl+C)
* - Fix: SIGPIPE ignored (prevents process kill on broken client socket)
* - Fix: sessions_.clear() in destroy() (prevents double-iterate on reconnect)
*
* @section Changes_v3_2_4
* - Fix: destroy() invalidates all session channels before ssh_free()
* (prevents Use-After-Free/segfault when SSH server crashes)
* - Disconnected sessions are closed immediately (no zombie clients)
*
* @section Changes_v3_2_3
* - Fix: pump_ssh() detects SSH disconnect, destroys watcher
* (prevents 100% CPU spin loop on server crash/EOF)
* - Fix: signal handler uses write() instead of Log::info()
* (eliminates async-signal-unsafe mutex deadlock on Ctrl+C)
*
* @section Changes_v3_2_2
* - Security: bind_ip config field, default 127.0.0.1 (no open proxy)
* - Fix: TCP Keep-Alive enabled (prevents NAT timeout zombie sessions)
* - Removed: SIGHUP handler (async-signal-unsafe, deadlock risk)
*
* @section Changes_v3_2_1
* - Fix: bytes_up_/bytes_down_ atomic with memory_order_relaxed
* - Fix: dup'd fd gets FD_CLOEXEC to prevent leak on fork+exec
*
* @section Changes_v3_2
* - 5-level logging: ERROR, WARN, INFO, DEBUG, TRACE
* - Millisecond timestamps in all log lines
* - SSH session diagnostics: negotiated cipher, kex, mac, server banner,
* host key type + SHA256 fingerprint, OpenSSH version, protocol, fd
* - Session lifecycle with unique connection IDs: tunnel[#42]
* - Transfer stats on close: bytes up/down, duration, client address
* - --trace / -T flag for packet-level debug
* - --log-file / -L to redirect output to file
* - --version shows libssh, OpenSSL, Boost, nlohmann/json versions + build type
* - Extended --help with full usage guide, config format, examples
*
* @section Architecture
*
* ┌─────────┐ ┌──────────────┐
* │ Client │ ←── async TCP ──→│ Socks5Session │←── notify_data_ready()
* └─────────┘ boost::asio └──────┬───────┘
* │ ssh_channel_read/write
* ┌──────┴────────┐
* │ SSHManager │
* │ ssh_session │
* │ stream_desc │←── epoll (single watcher)
* │ ssh_strand_ │
* │ pump_ssh() │──→ notify all sessions
* └───────────────┘
*
* @section Performance
* Per tunnel: 300-800 concurrent connections (stable)
* Idle CPU: ~0%, relay latency: <1ms
* No thundering herd, proper backpressure
*
* @section Build
* make debug — for -d/-T logging (ASan + UBSan)
* make release — production (debug/trace compiled out)
*
*/
#define LIBSSH_STATIC 1
#include <boost/asio.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/version.hpp>
#include <nlohmann/json.hpp>
#include <libssh/libssh.h>
#include <openssl/opensslv.h>
#include <openssl/crypto.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <memory>
#include <string>
#include <vector>
#include <array>
#include <thread>
#include <mutex>
#include <atomic>
#include <chrono>
#include <csignal>
#include <cstdlib>
#include <cstring>
#include <unordered_set>
#include <functional>
#include <getopt.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
using boost::asio::ip::tcp;
using json = nlohmann::json;
// =============================================================================
// Constants
// =============================================================================
static constexpr const char* APP_NAME = "socks5proxy";
static constexpr const char* APP_VERSION = "3.2.6";
/** @brief Relay buffer size per direction (client↔SSH). */
static constexpr std::size_t RELAY_BUF = 32768;
/** @brief Default max reconnection attempts. */
static constexpr int MAX_RECONN_DEF = 5;
/** @brief Delay between reconnection attempts (seconds). */
static constexpr int RECONN_DELAY = 3;
/** @brief Default SSH connect timeout (seconds). */
static constexpr int SSH_TIMEOUT_DEF = 10;
// =============================================================================
// Log Level — 5 levels: ERROR, WARN, INFO, DEBUG, TRACE
// =============================================================================
enum class LogLevel : int {
SILENT = 0,
ERR = 1,
WARN = 2,
INFO = 3,
DBG = 4,
TRACE = 5
};
/** @brief Global log level, settable via CLI flags. */
static LogLevel g_ll = LogLevel::INFO;
/** @brief Optional log file stream (--log-file). */
static std::ofstream g_logfile;
// =============================================================================
// Logger — thread-safe, timestamped with milliseconds, severity-filtered
// =============================================================================
/**
* @class Log
* @brief Thread-safe logging with millisecond timestamps and 5 severity levels.
*
* Output goes to stdout (info/warn/debug/trace) or stderr (error).
* If --log-file is set, all output redirects to the file.
* In NDEBUG builds, debug() and trace() compile to no-ops.
*/
class Log {
public:
/** @brief Log error to stderr (always visible unless SILENT). */
template<typename... A>
static void err(A&&... a) {
if (g_ll >= LogLevel::ERR)
put(cerr_stream(), "[ERROR] ", std::forward<A>(a)...);
}
/** @brief Log warning to stdout. */
template<typename... A>
static void warn(A&&... a) {
if (g_ll >= LogLevel::WARN)
put(cout_stream(), "[WARN] ", std::forward<A>(a)...);
}
/** @brief Log informational message to stdout. */
template<typename... A>
static void info(A&&... a) {
if (g_ll >= LogLevel::INFO)
put(cout_stream(), "[INFO] ", std::forward<A>(a)...);
}
/** @brief Log debug message (SSH negotiation, channels, SOCKS5 steps). */
template<typename... A>
static void dbg([[maybe_unused]] A&&... a) {
#ifndef NDEBUG
if (g_ll >= LogLevel::DBG)
put(cout_stream(), "[DEBUG] ", std::forward<A>(a)...);
#endif
}
/** @brief Log trace message (every packet, fd events, byte counts). */
template<typename... A>
static void trace([[maybe_unused]] A&&... a) {
#ifndef NDEBUG
if (g_ll >= LogLevel::TRACE)
put(cout_stream(), "[TRACE] ", std::forward<A>(a)...);
#endif
}
private:
static std::mutex m_;
/** @brief Route output to log file if open, otherwise stdout. */
static std::ostream& cout_stream() {
return g_logfile.is_open() ? g_logfile : std::cout;
}
/** @brief Route error output to log file if open, otherwise stderr. */
static std::ostream& cerr_stream() {
return g_logfile.is_open() ? g_logfile : std::cerr;
}
/** @brief Generate timestamp with millisecond precision: "HH:MM:SS.mmm". */
static std::string ts() {
auto now = std::chrono::system_clock::now();
auto t = std::chrono::system_clock::to_time_t(now);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch()) % 1000;
std::tm l{};
localtime_r(&t, &l);
char b[32];
std::snprintf(b, sizeof(b), "%02d:%02d:%02d.%03d",
l.tm_hour, l.tm_min, l.tm_sec, static_cast<int>(ms.count()));
return b;
}
/** @brief Write formatted log line with timestamp + tag + args. */
template<typename S, typename... A>
static void put(S& s, const char* tag, A&&... a) {
std::lock_guard<std::mutex> lk(m_);
s << ts() << ' ' << tag;
(s << ... << std::forward<A>(a)) << std::endl;
}
};
std::mutex Log::m_;
// =============================================================================
// Helpers
// =============================================================================
/**
* @brief Format byte count as human-readable string.
* @param b Byte count.
* @return "123 B", "1.2 KB", "3.4 MB", "1.23 GB"
*/
static std::string fmt_bytes(uint64_t b) {
char buf[32];
if (b < 1024)
std::snprintf(buf, sizeof(buf), "%lu B", static_cast<unsigned long>(b));
else if (b < 1024 * 1024)
std::snprintf(buf, sizeof(buf), "%.1f KB", b / 1024.0);
else if (b < 1024ULL * 1024 * 1024)
std::snprintf(buf, sizeof(buf), "%.1f MB", b / (1024.0 * 1024));
else
std::snprintf(buf, sizeof(buf), "%.2f GB", b / (1024.0 * 1024 * 1024));
return buf;
}
/** @brief Global atomic connection counter for unique session IDs. */
static std::atomic<uint64_t> g_conn_id{0};
// =============================================================================
// TunnelConfig — deserialized from JSON
// =============================================================================
/**
* @struct TunnelConfig
* @brief Holds parameters for a single SSH tunnel from the JSON config.
*/
struct TunnelConfig {
std::string name; ///< Tunnel identifier (used in all log messages)
std::string host; ///< SSH server hostname or IP
std::string username; ///< SSH username
std::string password; ///< SSH password
std::string bind_ip = "127.0.0.1"; ///< Local bind address (default: loopback only)
int port = 22; ///< SSH server port
int max_reconnects = MAX_RECONN_DEF; ///< Max reconnection attempts
int ssh_timeout = SSH_TIMEOUT_DEF; ///< SSH connect timeout (seconds)
unsigned short local_port = 1080; ///< Local SOCKS5 listen port
};
/**
* @brief Parse JSON config file into a vector of TunnelConfig.
* @param path Path to JSON file (array of tunnel objects).
* @param[out] out Populated on success.
* @return true if at least one valid tunnel was parsed.
*/
bool read_config(const std::string& path, std::vector<TunnelConfig>& out) {
std::ifstream f(path);
if (!f.is_open()) {
Log::err("Cannot open config: ", path);
return false;
}
try {
json j = json::parse(f);
if (!j.is_array()) {
Log::err("Config must be a JSON array of tunnel objects.");
return false;
}
for (const auto& it : j) {
TunnelConfig c;
// Helper lambdas for required field extraction
auto str = [&](const char* k, std::string& o) -> bool {
if (!it.contains(k) || !it[k].is_string()) {
Log::err("Tunnel skipped: missing or invalid '", k, "'.");
return false;
}
o = it[k].get<std::string>();
return true;
};
auto num = [&](const char* k, int& o) -> bool {
if (!it.contains(k) || !it[k].is_number_integer()) {
Log::err("Tunnel skipped: missing or invalid '", k, "'.");
return false;
}
o = it[k].get<int>();
return true;
};
// Required fields
if (!str("name", c.name)) continue;
if (!str("host", c.host)) continue;
if (!num("port", c.port)) continue;
if (!str("username", c.username)) continue;
if (!str("password", c.password)) continue;
int lp;
if (!num("local_port", lp)) continue;
c.local_port = static_cast<unsigned short>(lp);
// Optional fields with defaults
if (it.contains("max_reconnects") && it["max_reconnects"].is_number_integer())
c.max_reconnects = it["max_reconnects"].get<int>();
if (it.contains("ssh_timeout") && it["ssh_timeout"].is_number_integer())
c.ssh_timeout = it["ssh_timeout"].get<int>();
if (it.contains("bind_ip") && it["bind_ip"].is_string())
c.bind_ip = it["bind_ip"].get<std::string>();
out.push_back(std::move(c));
Log::dbg("Config: tunnel '", out.back().name, "' → ",
out.back().username, "@", out.back().host, ":", out.back().port,
" bind:", out.back().bind_ip, ":", out.back().local_port);
}
} catch (const json::parse_error& e) {
Log::err("JSON parse error: ", e.what());
return false;
}
if (out.empty()) {
Log::err("No valid tunnels found in config.");
return false;
}
return true;
}
// =============================================================================
// Forward declarations & interface
// =============================================================================
class SSHManager;
class Socks5Session;
/**
* @brief Interface for sessions receiving data-ready notifications from SSHManager.
*
* SSHManager calls notify_data_ready() on ssh_strand_ when pump_ssh() detects
* new data on the SSH socket. Each session then drains its own channel.
*/
class ISessionNotify {
public:
virtual ~ISessionNotify() = default;
/** @brief Called on ssh_strand_ when SSH data may be available. */
virtual void notify_data_ready() = 0;
/** @brief Called on ssh_strand_ when SSH session is being destroyed.
* Nullifies channel pointer before ssh_free() to prevent Use-After-Free. */
virtual void invalidate_channel() = 0;
};
// =============================================================================
// SSHManager — single fd watcher, strand-only serialization
// =============================================================================
/**
* @class SSHManager
* @brief Manages one SSH session with event-driven fd integration.
*
* Key design decisions:
* - Single stream_descriptor per tunnel (no thundering herd)
* - ALL libssh calls execute on ssh_strand_ (no mutex for SSH operations)
* - Registered sessions receive broadcast notifications after pump_ssh()
* - Reconnect logic with configurable retry count and delay
*
* After successful connect, prints full SSH session diagnostics:
* server banner, negotiated cipher/kex/mac, host key fingerprint, etc.
*/
class SSHManager : public std::enable_shared_from_this<SSHManager> {
public:
/**
* @brief Construct SSHManager for a tunnel configuration.
* @param cfg Tunnel config (host, port, credentials, etc.)
* @param ioc Boost.Asio io_context for async operations.
*/
SSHManager(const TunnelConfig& cfg, boost::asio::io_context& ioc)
: cfg_(cfg), ioc_(ioc), strand_(boost::asio::make_strand(ioc))
{}
/// Non-copyable.
SSHManager(const SSHManager&) = delete;
SSHManager& operator=(const SSHManager&) = delete;
~SSHManager() { destroy(); }
/** @brief Get tunnel name for log messages. */
const std::string& name() const { return cfg_.name; }
/** @brief Get the strand serializing all SSH operations. */
boost::asio::strand<boost::asio::io_context::executor_type>& strand() { return strand_; }
/**
* @brief Initial blocking SSH connect. Call before starting accept loop.
* @return true on success.
*/
bool initial_connect() {
if (!do_connect()) return false;
setup_fd_watcher();
return true;
}
/**
* @brief Open SSH forwarding channel asynchronously.
* @note MUST be called on strand_.
* @param host Target hostname/IP to forward to.
* @param port Target port.
* @param cb Callback with ssh_channel (or nullptr on failure).
*/
void open_channel_async(const std::string& host, int port,
std::function<void(ssh_channel)> cb) {
if (!session_) {
Log::err(cfg_.name, ": No active SSH session.");
cb(nullptr);
return;
}
ssh_channel ch = ssh_channel_new(session_);
if (!ch) {
Log::err(cfg_.name, ": ssh_channel_new() failed.");
cb(nullptr);
return;
}
Log::dbg(cfg_.name, ": Opening channel → ", host, ":", port, "...");
if (ssh_channel_open_forward(ch, host.c_str(), port, "127.0.0.1", 0) != SSH_OK) {
Log::err(cfg_.name, ": ssh_channel_open_forward: ", ssh_get_error(session_));
ssh_channel_free(ch);
cb(nullptr);
return;
}
channels_++;
Log::dbg(cfg_.name, ": Channel opened → ", host, ":", port,
" (active: ", channels_, ", window: ", ssh_channel_window_size(ch), " bytes)");
cb(ch);
}
/**
* @brief Write data to SSH channel. MUST be called on strand_.
* @return Bytes written, or -1 on error.
*/
int channel_write(ssh_channel ch, const void* data, uint32_t len) {
if (!ch || !session_) return -1;
int w = ssh_channel_write(ch, data, len);
Log::trace(cfg_.name, ": channel_write ", len, " → ", w, " bytes");
return w;
}
/**
* @brief Non-blocking read from SSH channel. MUST be called on strand_.
* @return Bytes read, 0 if no data, -1 on error/EOF.
*/
int channel_read_nb(ssh_channel ch, void* buf, uint32_t len) {
if (!ch) return -1;
int r = ssh_channel_read_nonblocking(ch, buf, len, 0);
if (r > 0) Log::trace(cfg_.name, ": channel_read_nb → ", r, " bytes");
return r;
}
/** @brief Check if channel reached EOF. Call on strand_. */
bool channel_is_eof(ssh_channel ch) {
return ch && ssh_channel_is_eof(ch);
}
/** @brief Check if channel is closed. Call on strand_. */
bool channel_is_closed(ssh_channel ch) {
return !ch || ssh_channel_is_closed(ch);
}
/**
* @brief Close and free SSH channel. MUST be called on strand_.
* Decrements active channel counter.
*/
void close_channel(ssh_channel ch) {
if (ch) {
ssh_channel_send_eof(ch);
ssh_channel_close(ch);
ssh_channel_free(ch);
if (channels_ > 0) channels_--;
Log::dbg(cfg_.name, ": Channel closed (active: ", channels_, ")");
}
}
/** @brief Get last SSH error message. Call on strand_. */
std::string get_error() {
return session_ ? ssh_get_error(session_) : "No session";
}
/**
* @brief Asynchronous reconnect with retry loop. MUST be called on strand_.
* @param cb Callback with true on success, false on failure.
*/
void reconnect_async(std::function<void(bool)> cb) {
if (reconnecting_) { cb(false); return; }
if (channels_ > 0) {
Log::warn(cfg_.name, ": Cannot reconnect: ", channels_, " active channel(s).");
cb(false);
return;
}
reconnecting_ = true;
do_reconnect_loop(1, std::move(cb));
}
/** @brief Register session for data-ready broadcast. On strand_. */
void register_session(ISessionNotify* s) {
sessions_.insert(s);
Log::trace(cfg_.name, ": Session registered (total: ", sessions_.size(), ")");
}
/** @brief Unregister session from broadcast. On strand_. */
void unregister_session(ISessionNotify* s) {
sessions_.erase(s);
Log::trace(cfg_.name, ": Session unregistered (total: ", sessions_.size(), ")");
}
/**
* @brief Public shutdown entry point for graceful teardown.
* Called via post(strand_) from Socks5Proxy::stop().
*/
void shutdown() { destroy(); }
private:
// ── SSH Connect (blocking) ──────────────────────────────────────────────
/**
* @brief Create SSH session, set all options, connect, authenticate.
* Prints full session diagnostics on success.
* @return true on success.
*/
bool do_connect() {
destroy();
session_ = ssh_new();
if (!session_) {
Log::err(cfg_.name, ": ssh_new() failed.");
return false;
}
Log::info(cfg_.name, ": Connecting to ", cfg_.username, "@", cfg_.host, ":", cfg_.port, "...");
// --- Core options ---
if (!opt(SSH_OPTIONS_HOST, cfg_.host.c_str())) return false;
if (!opt(SSH_OPTIONS_PORT, &cfg_.port)) return false;
if (!opt(SSH_OPTIONS_USER, cfg_.username.c_str())) return false;
// --- Disable host key checking & config file processing ---
int no = 0;
if (!opt(SSH_OPTIONS_STRICTHOSTKEYCHECK, &no)) return false;
if (!opt(SSH_OPTIONS_PROCESS_CONFIG, &no)) return false;
// --- Timeout ---
long tmo = cfg_.ssh_timeout;
if (!opt(SSH_OPTIONS_TIMEOUT, &tmo)) return false;
// --- SSH verbosity tied to our log level ---
int verb = SSH_LOG_NOLOG;
#ifndef NDEBUG
if (g_ll >= LogLevel::TRACE)
verb = SSH_LOG_FUNCTIONS;
else if (g_ll >= LogLevel::DBG)
verb = SSH_LOG_PROTOCOL;
#endif
if (!opt(SSH_OPTIONS_LOG_VERBOSITY, &verb)) return false;
// --- Ciphers: modern + legacy (3des-cbc, blowfish-cbc) ---
const char* ciphers =
"^aes128-ctr,aes256-ctr,aes192-ctr,"
"aes256-cbc,aes192-cbc,aes128-cbc,"
"3des-cbc,blowfish-cbc,"
"chacha20-poly1305@openssh.com,"
"aes128-gcm@openssh.com,aes256-gcm@openssh.com";
if (!opt(SSH_OPTIONS_CIPHERS_C_S, ciphers)) return false;
if (!opt(SSH_OPTIONS_CIPHERS_S_C, ciphers)) return false;
// --- Key exchange: modern curves + legacy DH groups ---
const char* kex =
"^curve25519-sha256,curve25519-sha256@libssh.org,"
"ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,"
"diffie-hellman-group-exchange-sha256,"
"diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,"
"diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,"
"diffie-hellman-group1-sha1,"
"diffie-hellman-group-exchange-sha1";
if (!opt(SSH_OPTIONS_KEY_EXCHANGE, kex)) return false;
// --- MACs: modern ETM + legacy ---
const char* macs =
"^hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,"
"hmac-sha1-etm@openssh.com,"
"umac-128-etm@openssh.com,umac-64-etm@openssh.com,"
"hmac-sha2-256,hmac-sha2-512,hmac-sha1,"
"hmac-md5,hmac-sha1-96,hmac-md5-96,"
"umac-64@openssh.com,umac-128@openssh.com";
if (!opt(SSH_OPTIONS_HMAC_C_S, macs)) return false;
if (!opt(SSH_OPTIONS_HMAC_S_C, macs)) return false;
// --- Host keys ---
if (!opt(SSH_OPTIONS_HOSTKEYS, "ssh-ed25519,ecdsa-sha2-nistp256,ssh-rsa,ssh-dss")) return false;
// --- No compression ---
if (!opt(SSH_OPTIONS_COMPRESSION, "none")) return false;
// --- Connect ---
if (ssh_connect(session_) != SSH_OK) {
Log::err(cfg_.name, ": Connect: ", ssh_get_error(session_));
destroy();
return false;
}
// --- TCP Keep-Alive on SSH socket (prevents NAT timeout drops) ---
{
int fd = static_cast<int>(ssh_get_fd(session_));
if (fd >= 0) {
int on = 1;
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on));
#ifdef TCP_KEEPIDLE
int idle = 60; // first probe after 60s idle (default: 7200s)
setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(idle));
#endif
#ifdef TCP_KEEPINTVL
int intvl = 15; // probe every 15s
setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &intvl, sizeof(intvl));
#endif
#ifdef TCP_KEEPCNT
int cnt = 4; // give up after 4 failed probes
setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt));
#endif
Log::dbg(cfg_.name, ": TCP Keep-Alive enabled on fd ", fd);
}
}
// --- Print negotiated session details ---
print_ssh_info();
// --- Authenticate ---
Log::dbg(cfg_.name, ": Authenticating as '", cfg_.username, "'...");
if (ssh_userauth_password(session_, nullptr, cfg_.password.c_str()) != SSH_AUTH_SUCCESS) {
Log::err(cfg_.name, ": Auth: ", ssh_get_error(session_));
destroy();
return false;
}
Log::info(cfg_.name, ": SSH connected — ", cfg_.username, "@", cfg_.host, ":", cfg_.port);
return true;
}
/**
* @brief Print negotiated SSH session parameters after successful connect.
*
* Shows: server banner, client banner, OpenSSH version, issue banner (MOTD),
* negotiated KEX algorithm, cipher in/out, MAC in/out,
* host key type + SHA256 fingerprint, protocol version, socket fd.
*/
void print_ssh_info() {
if (!session_) return;
// Server banner (e.g., "SSH-2.0-OpenSSH_8.9p1 Ubuntu-3ubuntu0.6")
const char* sb = ssh_get_serverbanner(session_);
if (sb) Log::info(cfg_.name, ": Server: ", sb);
// Client banner
const char* cb = ssh_get_clientbanner(session_);
if (cb) Log::dbg(cfg_.name, ": Client: ", cb);
// Issue banner (MOTD from server)
char* ib = ssh_get_issue_banner(session_);
if (ib) {
Log::dbg(cfg_.name, ": MOTD: ", ib);
ssh_string_free_char(ib);
}
// OpenSSH version (encoded as major*0x10000 + minor*0x100 + patch)
int ov = ssh_get_openssh_version(session_);
if (ov > 0) {
Log::dbg(cfg_.name, ": OpenSSH: ", ((ov >> 16) & 0xFF), ".", ((ov >> 8) & 0xFF));
}
// Negotiated algorithms
const char* kex_algo = ssh_get_kex_algo(session_);
const char* cipher_in = ssh_get_cipher_in(session_);
const char* cipher_out = ssh_get_cipher_out(session_);
const char* hmac_in = ssh_get_hmac_in(session_);
const char* hmac_out = ssh_get_hmac_out(session_);
Log::info(cfg_.name, ": KEX: ", kex_algo ? kex_algo : "?");
Log::info(cfg_.name, ": Cipher: in=", cipher_in ? cipher_in : "?",
" out=", cipher_out ? cipher_out : "?");
Log::info(cfg_.name, ": MAC: in=", hmac_in ? hmac_in : "?",
" out=", hmac_out ? hmac_out : "?");
// Host key type + SHA256 fingerprint
ssh_key srv_key = nullptr;
if (ssh_get_server_publickey(session_, &srv_key) == SSH_OK && srv_key) {
const char* ktype = ssh_key_type_to_char(ssh_key_type(srv_key));
unsigned char* hash = nullptr;
size_t hlen = 0;
if (ssh_get_publickey_hash(srv_key, SSH_PUBLICKEY_HASH_SHA256, &hash, &hlen) == 0 && hash) {
char* fp = ssh_get_fingerprint_hash(SSH_PUBLICKEY_HASH_SHA256, hash, hlen);
if (fp) {
Log::info(cfg_.name, ": HostKey: ", ktype ? ktype : "?", " ", fp);
ssh_string_free_char(fp);
}
ssh_clean_pubkey_hash(&hash);
}
ssh_key_free(srv_key);
}
// Protocol version and socket fd
Log::dbg(cfg_.name, ": Protocol: ", ssh_get_version(session_),
" fd: ", static_cast<int>(ssh_get_fd(session_)));
}
/**
* @brief Set a single SSH option with error logging.
* @return true on success, false on error (session destroyed).
*/
bool opt(ssh_options_e t, const void* v) {
if (ssh_options_set(session_, t, v) != SSH_OK) {
Log::err(cfg_.name, ": SSH option error: ", ssh_get_error(session_));
destroy();
return false;
}
return true;
}
/** @brief Disconnect and free SSH session, close fd watcher. */
void destroy() {
if (fd_desc_) {
boost::system::error_code ec;
fd_desc_->cancel(ec);
fd_desc_->close(ec);
fd_desc_.reset();
}
// Invalidate all session channels BEFORE ssh_free().
// ssh_free() internally frees all associated ssh_channel memory.
// Without this, sessions hold dangling ch_ pointers → Use-After-Free.
for (auto* s : sessions_) {
s->invalidate_channel();
}
sessions_.clear();
channels_ = 0;
if (session_) {
if (ssh_is_connected(session_)) {
Log::dbg(cfg_.name, ": Disconnecting SSH session...");
ssh_disconnect(session_);
}
ssh_free(session_);
session_ = nullptr;
}
}
// ── Reconnect loop (async, on strand_) ──────────────────────────────────
/**
* @brief Recursive reconnect attempt with delay timer.
* @param attempt Current attempt number (1-based).
* @param cb Callback with result.
*/
void do_reconnect_loop(int attempt, std::function<void(bool)> cb) {
Log::info(cfg_.name, ": Reconnect attempt ", attempt, "/", cfg_.max_reconnects);
if (do_connect()) {
setup_fd_watcher();
reconnecting_ = false;
Log::info(cfg_.name, ": Reconnected successfully.");
cb(true);
return;
}
if (attempt >= cfg_.max_reconnects) {
reconnecting_ = false;
Log::err(cfg_.name, ": All ", cfg_.max_reconnects, " reconnect attempts failed.");
cb(false);
return;
}
// Delay before next attempt
auto timer = std::make_shared<boost::asio::steady_timer>(
ioc_, std::chrono::seconds(RECONN_DELAY));
auto self = shared_from_this();
timer->async_wait(boost::asio::bind_executor(strand_,
[this, self, attempt, cb = std::move(cb), timer](boost::system::error_code ec) mutable {
if (ec) { reconnecting_ = false; cb(false); return; }
do_reconnect_loop(attempt + 1, std::move(cb));
}));
}
// ── Single fd watcher (thundering-herd-free) ────────────────────────────
/**
* @brief Create stream_descriptor for SSH fd and start event monitoring.
*
* Uses dup(fd) so that descriptor lifetime is independent of SSH session.
* Only one watcher exists per SSHManager — no thundering herd.
*/
void setup_fd_watcher() {
if (!session_) return;
int fd = static_cast<int>(ssh_get_fd(session_));
if (fd < 0) {
Log::err(cfg_.name, ": Invalid SSH fd.");
return;
}
int duped = ::dup(fd);
if (duped < 0) {
Log::err(cfg_.name, ": dup() failed.");
return;
}
::fcntl(duped, F_SETFD, FD_CLOEXEC);
try {
fd_desc_ = std::make_unique<boost::asio::posix::stream_descriptor>(ioc_, duped);
} catch (const std::exception& e) {
::close(duped);
Log::err(cfg_.name, ": stream_descriptor: ", e.what());
return;
}
Log::dbg(cfg_.name, ": FD watcher armed on fd ", duped, " (original: ", fd, ")");
arm_fd_wait();
}
/**
* @brief Register for read-readiness on SSH socket fd.
* When the kernel signals readability, pump_ssh() fires.
*/
void arm_fd_wait() {
if (!fd_desc_ || !fd_desc_->is_open()) return;
auto self = shared_from_this();
fd_desc_->async_wait(
boost::asio::posix::stream_descriptor::wait_read,
boost::asio::bind_executor(strand_,
[this, self](boost::system::error_code ec) {
if (ec) {
if (ec != boost::asio::error::operation_aborted)
Log::dbg(cfg_.name, ": FD wait error: ", ec.message());
return;
}
pump_ssh();
}));
}
/**
* @brief Pump libssh state machine, then broadcast to all sessions.
*
* This is the single point of entry for SSH I/O. Runs on strand_.
* 1. ssh_event_dopoll(0) processes pending packets
* 2. Notify all registered sessions to drain their channels
* 3. Re-arm the fd watcher
*/
void pump_ssh() {
if (!session_) return;
Log::trace(cfg_.name, ": pump_ssh() → processing for ", sessions_.size(), " session(s)");
// Process pending SSH packets (non-blocking)
ssh_event ev = ssh_event_new();
if (ev) {
ssh_event_add_session(ev, session_);
ssh_event_dopoll(ev, 0);
ssh_event_free(ev);
}
// Check if SSH session died after polling (EOF/RST from server).
// Without this check, fd stays in EOF state, epoll returns readable
// immediately, and we spin at 100% CPU forever.
if (!ssh_is_connected(session_)) {
Log::warn(cfg_.name, ": SSH disconnected (detected in pump_ssh). Destroying watcher.");
destroy();
return;
}
// Broadcast: notify all sessions that data may be available
for (auto* s : sessions_) {
s->notify_data_ready();
}
// Re-arm for next event
arm_fd_wait();
}
// ── Members ─────────────────────────────────────────────────────────────
TunnelConfig cfg_;
boost::asio::io_context& ioc_;
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
ssh_session session_ = nullptr;
std::size_t channels_ = 0;
bool reconnecting_ = false;
/// Single fd watcher — only SSHManager listens on the SSH socket
std::unique_ptr<boost::asio::posix::stream_descriptor> fd_desc_;
/// Registered sessions for data-ready broadcast
std::unordered_set<ISessionNotify*> sessions_;
};
// =============================================================================
// Socks5Session — notified by SSHManager, no own fd watcher
// =============================================================================
/**
* @class Socks5Session
* @brief Handles one SOCKS5 client: handshake, CONNECT, bidirectional relay.
*
* All SSH operations dispatched to ssh_->strand().
* Receives data-ready notifications from SSHManager::pump_ssh().
* Backpressure: drain pauses while async_write to client is in flight.
*
* Each session has a unique ID (conn_id_) and a log tag "tunnel[#42]"
* for easy grep'ing in logs.
*/
class Socks5Session : public std::enable_shared_from_this<Socks5Session>,
public ISessionNotify {
public:
Socks5Session(tcp::socket socket, boost::asio::io_context& ioc,
std::shared_ptr<SSHManager> ssh, const std::string& tname)
: client_(std::move(socket))
, ioc_(ioc)
, strand_(boost::asio::make_strand(ioc))
, ssh_(std::move(ssh))
, tname_(tname)
, conn_id_(++g_conn_id)
{
// Build log tag: "tunnel_name[#42]"
tag_ = tname_ + "[#" + std::to_string(conn_id_) + "]";
// Capture client address for close-time logging
boost::system::error_code ec;
auto ep = client_.remote_endpoint(ec);
if (!ec)
client_addr_ = ep.address().to_string() + ":" + std::to_string(ep.port());
Log::dbg(tag_, ": New session from ", client_addr_);
}
~Socks5Session() override = default;
/** @brief Start SOCKS5 handshake. */
void start() {
auto self = shared_from_this();
boost::asio::post(strand_, [this, self]() { read_greeting(); });
}
/**
* @brief Called by SSHManager on ssh_strand_ when SSH data arrived.
*
* Posts drain to ssh_strand_ with backpressure check.
* If write to client is pending, drain is skipped — it will be
* re-triggered when the write completes.
*/
void notify_data_ready() override {
if (closed_.load()) return;
auto self = shared_from_this();
boost::asio::post(ssh_->strand(), [this, self]() {