forked from RaspAP/SamplePlugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSocksProxy.php
332 lines (284 loc) · 10.9 KB
/
SocksProxy.php
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
<?php
/**
* SOCKS5 Proxy Plugin
*
* @description A Dante SOCKS Server add-on for RaspAP
* @author Bill Zimmerman <[email protected]>
* @license https://github.com/billz/SamplePlugin/blob/master/LICENSE
* @see src/RaspAP/Plugins/PluginInterface.php
* @see src/RaspAP/UI/Sidebar.php
*/
namespace RaspAP\Plugins\SocksProxy;
use RaspAP\Plugins\PluginInterface;
use RaspAP\UI\Sidebar;
class SocksProxy implements PluginInterface
{
private string $pluginPath;
private string $pluginName;
private string $templateMain;
private string $serviceName;
private string $danteConfig;
private string $serviceStatus;
public function __construct(string $pluginPath, string $pluginName)
{
$this->pluginPath = $pluginPath;
$this->pluginName = $pluginName;
$this->templateMain = 'main';
$this->serviceName = 'danted.service';
$this->danteConfig = '/etc/danted.conf';
$this->serviceStatus = $this->getServiceStatus();
if ($loaded = self::loadData()) {
$this->serviceStatus = $loaded->getServiceStatus();
}
}
/**
* Initialize the SocksProxy plugin and create a sidebar item
*
* @param Sidebar $sidebar an instance of the Sidebar
* @see src/RaspAP/UI/Sidebar.php
* @see https://fontawesome.com/icons
*/
public function initialize(Sidebar $sidebar): void
{
$label = _('Socks Proxy');
$icon = 'fas fa-socks';
$action = 'plugin__'.$this->getName();
$priority = 65;
$service_name = $this->serviceName;
$sidebar->addItem($label, $icon, $action, $priority);
}
/**
* Handle page actions by processing inputs and rendering a plugin template
*
* @param string $page the current page route
*/
public function handlePageAction(string $page): bool
{
// Verify that this plugin should handle the page
if (str_starts_with($page, "/plugin__" . $this->getName())) {
// Instantiate a StatusMessage object
$status = new \RaspAP\Messages\StatusMessage;
if (!RASPI_MONITOR_ENABLED) {
if (isset($_POST['saveSettings'])) {
if (isset($_POST['interface'])) {
$return = $this->persistConfig($status, $_POST);
$status->addMessage('Restarting '.$this->serviceName, 'info');
}
} elseif (isset($_POST['startDanteService'])) {
$status->addMessage('Attempting to start '.$this->serviceName, 'info');
exec('sudo /bin/systemctl start '.$this->serviceName, $output, $return);
if ($return == 0) {
$status->addMessage('Successfully started '.$this->serviceName, 'success');
$this->setServiceStatus('up');
} else {
$status->addMessage('Failed to start '.$this->serviceName, 'danger');
$this->setServiceStatus('down');
}
} elseif (isset($_POST['restartDanteService'])) {
$status->addMessage('Attempting to restart '.$this->serviceName, 'info');
exec('sudo /bin/systemctl restart '.$this->serviceName, $output, $return);
if ($return == 0) {
$status->addMessage('Successfully restarted '.$this->serviceName, 'success');
$this->setServiceStatus('up');
} else {
$status->addMessage('Failed to start '.$this->serviceName, 'danger');
$this->setServiceStatus('down');
}
} elseif (isset($_POST['stopDanteService'])) {
$status->addMessage('Attempting to stop '.$this->serviceName, 'info');
exec('sudo /bin/systemctl stop '.$this->serviceName, $output, $return);
if ($return == 0) {
$status->addMessage('Successfully stopped '.$this->serviceName, 'success');
$this->setServiceStatus('down');
} else {
$status->addMessage('Failed to stop '.$this->serviceName, 'danger');
}
}
}
// Parse the current Dante configuration
$config = $this->parseConfig();
// Populate template data
$__template_data = [
'title' => _('Socks Proxy'),
'description' => _('A Dante SOCKS Server add-on for RaspAP'),
'author' => _('Bill Zimmerman'),
'uri' => 'https://github.com/billz/SocksProxy',
'icon' => 'fas fa-socks',
'interfaces' => $this->getInterfaces(),
'serviceStatus' => $this->getServiceStatus(),
'serviceName' => $this->serviceName,
'action' => 'plugin__'.$this->getName(),
'pluginName' => $this->getName(),
'content' => _('Administer the Dante SOCKS server with the settings below.'),
'serviceLog' => $this->getServiceLog(),
'arrConfig' => $config
];
echo $this->renderTemplate($this->templateMain, compact(
"status",
"__template_data"
));
return true;
}
return false;
}
/**
* Renders a template from inside a plugin directory
* @param string $templateName
* @param array $__data
*/
public function renderTemplate(string $templateName, array $__data = []): string
{
$templateFile = "{$this->pluginPath}/{$this->getName()}/templates/{$templateName}.php";
if (!file_exists($templateFile)) {
return "Template file {$templateFile} not found.";
}
if (!empty($__data)) {
extract($__data);
}
ob_start();
include $templateFile;
return ob_get_clean();
}
/**
* Returns a service status
* @return string $status
*/
public function getServiceStatus()
{
exec('sudo /bin/systemctl status '.$this->serviceName, $output, $return);
foreach ($output as $line) {
if (strpos($line, 'Active: active (running)') !== false) {
return 'up';
}
}
return 'down';
}
/**
* Returns the current Dante configuration
* @return array $arrConfig
*/
public function parseConfig()
{
$arrConfig = [];
exec('cat ' . escapeshellarg($this->danteConfig), $cfg);
$blockKey = null;
$blockLines = []; // accumulate block lines
foreach ($cfg as $line) {
// skip empty lines or comments
$line = trim($line);
if (strlen($line) === 0 || $line[0] === '#') {
continue;
}
// block start
if (preg_match('/^(client|socks)\s+pass\s*\{$/', $line, $matches)) {
$blockKey = $matches[1] . '_pass';
$blockLines = [];
continue;
}
// block end
if ($blockKey && $line === '}') {
$arrConfig[$blockKey] = $blockLines;
$blockKey = null;
$blockLines = [];
continue;
}
// accumulate block lines
if (preg_match('/^([^:]+):(.*)$/', $line, $matches)) {
$key = trim($matches[1]);
$value = trim($matches[2]);
// split internal address and port
if ($key === 'internal' && preg_match('/^([\d\.]+)\s+port=(\d+)$/', $value, $internalMatches)) {
$arrConfig['internal_addr'] = $internalMatches[1];
$arrConfig['internal_port'] = $internalMatches[2];
} else {
$arrConfig[$key] = $value;
}
} elseif (preg_match('/^([^=]+)=(.*)$/', $line, $matches)) {
$key = trim($matches[1]);
$value = trim($matches[2]);
$arrConfig[$key] = $value;
}
}
return $arrConfig;
}
/* Persists the Dante configuration
*
* @param object $status
* @param object $post
*/
public function persistConfig($status, $post)
{
$status->addMessage('Saving Socks Proxy settings', 'info');
$content = <<<CONFIG
logoutput: syslog
user.privileged: {$post['txtuserprivileged']}
user.unprivileged: {$post['txtuserunprivileged']}
# The listening network interface or address.
internal: {$post['txtinternal']} port={$post['txtport']}
# The proxying network interface or address.
external: {$post['interface']}
# socks-rules determine what is proxied through the external interface.
socksmethod: {$post['txtsocksmethod']}
# client-rules determine who can connect to the internal interface.
clientmethod: {$post['txtclientmethod']}
client pass {
from: {$post['txtclientip']}
}
socks pass {
from: 0.0.0.0/0 to: 0.0.0.0/0
}
CONFIG;
try {
file_put_contents('/tmp/danted.conf', $content);
system('sudo cp /tmp/danted.conf ' .$this->danteConfig, $result);
if ($result == 0) {
$status->addMessage('Dante configuration saved successfully to '.$this->danteConfig, 'success');
} else {
$status->addMessage('Failed to save Dante configuration to '.$this->danteConfig, 'error');
}
} catch (\Exception $e) {
$status->addMessage('Failed to save Dante configuration: ' .$e->getMessage(), 'error');
}
return $status;
}
/**
* Returns the current danted.service status
* @return string $serviceLog
*/
public function getServiceLog()
{
exec('sudo /bin/systemctl status '.$this->serviceName, $output);
$serviceLog = implode("\n", $output);
return $serviceLog;
}
/**
* Returns the currently available network interfaces
* @return array $interfaces
*/
public function getInterfaces()
{
exec("ip -o link show | awk -F': ' '{print $2}'", $interfaces);
sort($interfaces);
return $interfaces;
}
// Setter for service status
public function setServiceStatus($status)
{
$this->serviceStatus = $status;
}
// Static method to load persisted data
public static function loadData(): ?self
{
$filePath = "/tmp/plugin__".self::getName() .".data";
if (file_exists($filePath)) {
$data = file_get_contents($filePath);
return unserialize($data);
}
return null;
}
// Returns an abbreviated class name
public static function getName(): string
{
return basename(str_replace('\\', '/', static::class));
}
}