-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathSshTunnelService.cs
More file actions
196 lines (169 loc) · 5.52 KB
/
SshTunnelService.cs
File metadata and controls
196 lines (169 loc) · 5.52 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
using OpenClaw.Shared;
using System;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
namespace OpenClawTray.Services;
/// <summary>
/// Manages an SSH local port-forward process for gateway access.
/// </summary>
public sealed class SshTunnelService : IDisposable
{
private readonly IOpenClawLogger _logger;
private Process? _process;
private string? _lastSpec;
private bool _stopping;
public SshTunnelService(IOpenClawLogger logger)
{
_logger = logger;
}
/// <summary>
/// Raised when the SSH tunnel process exits unexpectedly (i.e., not as a result of <see cref="Stop"/>).
/// </summary>
public event EventHandler? TunnelExited;
public bool IsRunning => _process is { HasExited: false };
public void EnsureStarted(SettingsManager settings)
{
if (!settings.UseSshTunnel)
{
Stop();
return;
}
EnsureStarted(
settings.SshTunnelUser,
settings.SshTunnelHost,
settings.SshTunnelRemotePort,
settings.SshTunnelLocalPort);
}
public void EnsureStarted(string user, string host, int remotePort, int localPort)
{
user = user.Trim();
host = host.Trim();
var spec = BuildSpec(user, host, remotePort, localPort);
if (IsRunning && string.Equals(_lastSpec, spec, StringComparison.Ordinal))
{
return;
}
Stop();
StartProcess(user, host, remotePort, localPort);
_lastSpec = spec;
}
public void Stop()
{
if (_process == null)
{
return;
}
_stopping = true;
_logger.Info("Stopping SSH tunnel process");
try
{
if (!_process.HasExited)
{
_process.Kill(entireProcessTree: true);
_process.WaitForExit(3000);
}
}
catch (Exception ex)
{
_logger.Warn($"SSH tunnel stop failed: {ex.Message}");
}
finally
{
try { _process.Dispose(); } catch { }
_process = null;
_lastSpec = null;
_stopping = false;
}
}
private void StartProcess(string user, string host, int remotePort, int localPort)
{
var psi = new ProcessStartInfo
{
FileName = "ssh",
Arguments = BuildArguments(user, host, remotePort, localPort),
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
};
var process = new Process
{
StartInfo = psi,
EnableRaisingEvents = true,
};
process.OutputDataReceived += (_, e) =>
{
if (!string.IsNullOrWhiteSpace(e.Data))
{
_logger.Info($"[SSH] {e.Data}");
}
};
process.ErrorDataReceived += (_, e) =>
{
if (!string.IsNullOrWhiteSpace(e.Data))
{
_logger.Warn($"[SSH] {e.Data}");
}
};
process.Exited += (_, _) =>
{
var exitCode = process.ExitCode;
if (_stopping)
{
_logger.Info($"SSH tunnel exited during shutdown (code {exitCode})");
}
else
{
_logger.Warn($"SSH tunnel exited unexpectedly (code {exitCode})");
_process = null;
_lastSpec = null;
try { process.Dispose(); } catch (Exception disposeEx) { _logger.Warn($"SSH tunnel process dispose failed: {disposeEx.Message}"); }
TunnelExited?.Invoke(this, EventArgs.Empty);
}
};
try
{
if (!process.Start())
{
throw new InvalidOperationException("Failed to start ssh process");
}
}
catch (Exception ex)
{
process.Dispose();
throw new InvalidOperationException("Unable to start SSH tunnel process. Ensure OpenSSH client is installed and available in PATH.", ex);
}
process.BeginOutputReadLine();
process.BeginErrorReadLine();
_process = process;
_logger.Info($"SSH tunnel started: 127.0.0.1:{localPort} -> 127.0.0.1:{remotePort} via {user}@{host}");
}
private static string BuildSpec(string user, string host, int remotePort, int localPort)
=> $"{user}@{host}:{localPort}:{remotePort}";
// Strict validation for SSH user/host to prevent command injection
private static readonly Regex s_validSshUser = new(@"^[a-zA-Z0-9._-]+$", RegexOptions.Compiled);
private static readonly Regex s_validSshHost = new(@"^[a-zA-Z0-9._-]+$", RegexOptions.Compiled);
private static string BuildArguments(string user, string host, int remotePort, int localPort)
{
if (!s_validSshUser.IsMatch(user))
throw new ArgumentException($"SSH user contains invalid characters: '{user}'");
if (!s_validSshHost.IsMatch(host))
throw new ArgumentException($"SSH host contains invalid characters: '{host}'");
var sb = new StringBuilder();
sb.Append("-N ");
sb.Append("-L ");
sb.Append(localPort);
sb.Append(":127.0.0.1:");
sb.Append(remotePort);
sb.Append(' ');
sb.Append(user);
sb.Append('@');
sb.Append(host);
return sb.ToString();
}
public void Dispose()
{
Stop();
}
}