summaryrefslogtreecommitdiffstats
path: root/modules-available/usblockoff/page.inc.php
blob: 8c32a699acab45a3c0c9a6a5c08260a8437c11ac (plain) (blame)
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
<?php
class Page_usblockoff extends Page
{

	/**
	 * Called before any page rendering happens - early hook to check parameters etc.
	 */
	protected function doPreprocess()
	{
		User::load();

		if (!User::isLoggedIn()) {
			Message::addError('main.no-permission');
			Util::redirect('?do=Main'); // does not return
		}

		$this->action = Request::any('action');

		if ($this->action === 'updateConfig') {
			$this->updateConfig();
		} elseif ($this->action === 'addDevices') {
			$this->addDevices();
		} elseif ($this->action === 'deleteConfig') {
			$this->deleteConfig();
		} elseif ($this->action === 'deleteRule') {
			$this->deleteRule();
		}
	}

	/**
	 * Menu etc. has already been generated, now it's time to generate page content.
	 */
	protected function doRender()
	{
		$show = Request::get("show", "config-table");
		if ($show === "config-table") {
			$this->loadConfigChooser();
		} else if ($show === "edit-config") {
			$configid = Request::get("configid", "");
			$configName = Database::queryFirst("SELECT configname FROM `usb_configs` WHERE configid=:id", array(
				'id' => $configid
			));

			$rulesConfigHtml = $this->loadRulesConfig($configid);
			$daemonConfigHtml = $this->loadDaemonConfig($configid);

			Render::addTemplate('usb-edit-config', array(
				'configid' => $configid,
				'configName' => $configName['configname'],
				'rulesConfigHtml' => $rulesConfigHtml,
				'daemonConfigHtml' => $daemonConfigHtml
			));
		} else if ($show === "add-devices") {
			$this->deviceList();
		} else if ($show === "add-generic-rule") {
			$this->addGenericRule();
		} else if ($show === "edit-rule") {
			$ruleid = Request::get("ruleid", 0, "int");
			if ($ruleid === 0) {
				Message::addError('invalid-rule-id');
				return;
			}

			// TODO: Use another html page where stuff can be configured.
			// WiP

		}
	}

	private function addDevices()
	{
		$configid = Request::any('configid', 0, 'int');

		$rules = json_decode(Request::post('rules', '', 'string'), true);

		error_log(json_encode($rules));
		foreach ($rules as $rule) {
			$rid = (int)$rule['id'];
			if($rid == 0) {
				// New entry so insert only with new id.
				$rid = Database::queryFirst("SELECT MAX(ruleid) AS ID FROM `usb_rule_prop`");
				$rid = $rid['ID'];
				if ($rid == null) $rid = 1;
				else $rid += 1;
			} else {
				// Old entry so delete all old ones and insert new ones.
				Database::exec("DELETE FROM `usb_rule_prop` WHERE ruleid=:ruleid", array('ruleid' => $rid));
			}

			Database::exec("INSERT INTO `usb_rule_prop` (ruleid, prop, value) VALUES (:ruleid, :prop, :val)", array(
				'ruleid' => $rid,
				'prop' => 'target',
				'val' => $rule['target']
			));

			foreach ($rule['attributes'] as $attribute) {
				// TODO: Better in one query?
				Database::exec("INSERT INTO `usb_rule_prop` (ruleid, prop, value) VALUES (:ruleid, :prop, :val)", array(
					'ruleid' => $rid,
					'prop' => $attribute['prop'],
					'val' => $attribute['value']
				));
			}

			// TODO: Add id at the end of the config entry.
			$config = Database::queryFirst("SELECT rulesconfig FROM `usb_configs` WHERE configid=:configid", array(
				'configid' => $configid
			));
			$rulesconfig = json_decode($config['rulesconfig'], true);
			$rulesconfig[] = $rid;
			Database::exec("UPDATE `usb_configs` SET rulesconfig = :rulesconfig WHERE configid=:configid", array(
				'configid' => $configid,
				'rulesconfig' => json_encode($rulesconfig)
			));
			//$result['rules'][] = $rid;
		}

		Util::redirect('?do=usblockoff&show=edit-config&configid=' . $configid);
	}

	private function deviceList()
	{
		$configid = Request::get("configid", 0, 'int');
		$usbdevices = $this->getUsbDeviceList();

		// TODO: Translate Operator Action etc..

		$settings = array();
		$setting = array();
		$setting['title'] = "Action";
		$setting['select_list'] = array(array(
			'option' => 'allow',
			'active' => true,
		),
			array(
				'option' => 'block',
				'active' => false,
			),
			array(
				'option' => 'reject',
				'active' => false,
			));
		$setting['helptext'] = array('helptext' => Dictionary::translateFile('rule', 'abr_helptext'));
		$setting['property'] = 'action';
		$setting['settingHtml'] = Render::parse('server-prop-dropdown', (array)$setting);
		$settings[] = $setting;

		$ruleValues = array('id' => true,
			'serial' => true,
			'name' => true,
			//'hash' => false,
			//'parent-hash' => false,
			'via-port' => false,
			'with-interface' => false);
		foreach ($ruleValues as $key => $value) {
			$settings[] = array(
				'settingHtml' => Render::parse('server-prop-bool', array('title' => Dictionary::translateFile('rule', $key),
					'helptext' => array('helptext' => Dictionary::translateFile('rule', $key . "_helptext")),
					'property' => $key,
					'currentvalue' => $value)),
			);
		}
		Render::addTemplate('usb-device-list', array(
			'list' => array_values($usbdevices),
			'settings' => array_values($settings),
			'configid' => $configid
		));
	}

	private function addGenericRule($target = 'allow') {
		$settings = array();
		$configid = Request::get("configid", "");

		// TODO: Translate Operator Action etc..

		$setting = array();
		$setting['title'] = "Action";
		$setting['select_list'] = array(array(
			'option' => 'allow',
			'active' => ($target == 'allow' ? true : false),
		),
			array(
				'option' => 'block',
				'active' => ($target == 'block' ? true : false),
			),
			array(
				'option' => 'reject',
				'active' => ($target == 'reject' ? true : false),
			));
		$setting['helptext'] = array('helptext' => Dictionary::translateFile('rule', 'abr_helptext'));
		$setting['property'] = 'action';
		$setting['settingHtml'] = Render::parse('server-prop-dropdown', (array)$setting);
		$settings[] = $setting;

		Render::addTemplate('usb-add-generic-rule', array(
			'settings' => array_values($settings),
			'configid' => $configid
		));
	}

	protected function loadConfigChooser()
	{
		$dbquery = Database::simpleQuery("SELECT configid, configname FROM `usb_configs`");
		$configs = array();
		while ($dbentry = $dbquery->fetch(PDO::FETCH_ASSOC)) {
			$config['config_id'] = $dbentry['configid'];
			$config['config_name'] = $dbentry['configname'];
			$configs[] = $config;
		}
		Render::addTemplate('usb-configuration-table', array('config_list' => array_values($configs)));
	}

	protected function deleteConfig()
	{
		$configID = Request::any('id', 0, 'int');
		if ($configID != 0) {
			Database::exec("DELETE FROM `usb_configs` WHERE configid=:configid", array('configid' => $configID));
		}

		Message::addSuccess('config-deleted');
		Util::redirect('?do=usblockoff');
	}

	protected function deleteRule()
	{
		$configid = Request::any('configid', 0, 'int');
		$ruleid = Request::any('id', 0, 'int');
		if ($ruleid != 0) {
			Database::exec("DELETE FROM `usb_rule_prop` WHERE ruleid=:ruleid", array('ruleid' => $ruleid));
		}

		Message::addSuccess('rule-deleted');
		Util::redirect('?do=usblockoff&show=edit-config&configid=' . $configid);
	}


	protected function updateConfig()
	{
		$result['saveAsNewConfig'] = Request::post('saveAsNewConfig', false, 'bool');
		// Add new settings in usbguard-daemon.conf here:
		$result['RuleFile'] = Request::post('RuleFile', '', 'string');
		$result['ImplicitPolicyTarget'] = Request::post('ImplicitPolicyTarget', '', 'string');
		$result['PresentDevicePolicy'] = Request::post('PresentDevicePolicy', '', 'string');
		$result['PresentControllerPolicy'] = Request::post('PresentControllerPolicy', '', 'string');
		$result['InsertedDevicePolicy'] = Request::post('InsertedDevicePolicy', '', 'string');
		$result['RestoreControllerDeviceState'] = Request::post('RestoreControllerDeviceState', '', 'string');
		$result['DeviceManagerBackend'] = Request::post('DeviceManagerBackend', '', 'string');
		$result['IPCAllowedUsers'] = Request::post('IPCAllowedUsers', '', 'string');
		$result['IPCAllowedGroups'] = Request::post('IPCAllowedGroups', '', 'string');
		$result['IPCAccessControlFiles'] = Request::post('IPCAccessControlFiles', '', 'string');
		$result['DeviceRulesWithPort'] = Request::post('DeviceRulesWithPort', '', 'string');
		$result['AuditFilePath'] = Request::post('AuditFilePath', '', 'string');
		$result['rules'] = json_decode(Request::post('rules', '', 'string'), true);

		$id = Request::post('id', 0, 'int');
		$configname = Request::post('configName', '', 'string');
		$dbquery = Database::queryFirst("SELECT * FROM `usb_configs` WHERE configid=:id", array('id' => $id));

		// Load daemon.conf from db else load default
		if ($dbquery !== false) {
			$daemonConf = explode("\r\n", $dbquery['daemonconfig']);
		} else {
			$currentdir = getcwd();
			$file = $currentdir . '/modules/usblockoff/inc/default-configs/usbguard-daemon.conf';
			$daemonConf = file($file);
		}
		$newDaemonConf = array();

		foreach ($daemonConf as $line) {
			$t_line = trim($line, "\r\n");
			if ($t_line == '' || $t_line[0] == '#') {
				$newDaemonConf[] = $line . "\r\n";
				continue;
			} else {
				$splitstr = explode('=', $line);

				$splitstr[1] = $result[$splitstr[0]];
				$newDaemonConf[] = implode('=', $splitstr) . "\r\n";
			}
		}

		// INSERT IN DB
		if ($id == '0' || $result['saveAsNewConfig']) {
			$dbquery = Database::exec("INSERT INTO `usb_configs` (configname, rulesconfig, daemonconfig) VALUES (:configname, :rulesconfig, :daemonconfig)",
				array('configname' => $configname,
					'rulesconfig' => json_encode($result['rules']),
					'daemonconfig' => implode($newDaemonConf)));
		} else {
			$dbquery = Database::exec("UPDATE `usb_configs` SET configname=:configname, rulesconfig=:rulesconfig, daemonconfig=:daemonconfig WHERE configid=:configid",
				array('configid' => $id,
					'configname' => $configname,
					'rulesconfig' => json_encode($result['rules']),
					'daemonconfig' => implode($newDaemonConf)));
		}
		Message::addSuccess('config-saved');
	}

	private function loadRulesConfig($configid) {
		$rulesConf = null;

		if ($configid == 0) {
			$currentdir = getcwd();
			// TODO: No need for that with the new rule db structure.
			$rulesConf = file_get_contents($currentdir . '/modules/usblockoff/inc/default-configs/rules.conf');
		} else {
			$dbquery = Database::queryFirst("SELECT * FROM `usb_configs` WHERE configid=:id", array('id' => $configid));
			$ruleIds = json_decode($dbquery['rulesconfig'], true);
		}


		$rulesArray = [];
		foreach ($ruleIds as $id) {
			// TODO: Query rule and prepare array for the html file.
			$dbq = Database::simpleQuery("SELECT * FROM `usb_rule_prop` WHERE ruleid=:id", array('id' => $id));
			$rule = [];
			$rule['id'] = $id;
			$rule['hasoverload'] = false;
			$rule['num_overload'] = 0;
			$rule['attributes'] = array();
			$rule['attributes_overload'] = "";
			while ($entry = $dbq->fetch(PDO::FETCH_ASSOC)) {
				if ($entry['prop'] == "target") {
					$rule['target'] = $entry['value'];
				} else {
					$attributes = [];
					$attributes['prop'] = $entry['prop'];
					$attributes['value'] = $entry['value'];

					if(sizeof($rule['attributes']) >= 3) {
						$rule['hasoverload'] = true;
						$rule['num_overload'] += 1;
						$rule['attributes_overload'] .= $attributes['prop'] . ': ' . $attributes['value'] . "<br>";
					} else {
						$rule['attributes'][] = $attributes;
					}
				}
			}

			if (!empty($rule['target'])) {
				$rulesArray[] = $rule;
			}
		}
		return Render::parse('usb-rules-config', array(
			'rules' => (array)$rulesArray,
			'configid' => $configid
		));
	}

	private function loadDaemonConfig($id)
	{
		$form = array();
		$rulesConf = null;

		if ($id == 0) {
			$currentdir = getcwd();

			$daemonConf = file($currentdir . '/modules/usblockoff/inc/default-configs/usbguard-daemon.conf');
		} else {
			$dbquery = Database::queryFirst("SELECT * FROM `usb_configs` WHERE configid=:id", array('id' => $id));
			$daemonConf = explode("\r\n", $dbquery['daemonconfig']);
		}
		$element = array();
		$hlptxt = '';

		foreach ($daemonConf as $line) {
			$t_line = trim($line, "\r\n");
			if ($t_line == '#' || $t_line == '' || strpos($t_line, '#!!!') !== false) {
				continue;
			} elseif ($t_line[0] == '#') {
				$ttxt = trim($line, "#");
				$hlptxt .= $ttxt . '<br>';
			} else {
				$splitstr = explode('=', $t_line);
				$element['name'] = $splitstr[0];
				$element['value'] = $splitstr[1];
				$element['helptext'] = $hlptxt;

				$form[] = $element;
				$hlptxt = '';
			}
		}

		return Render::parse('usb-daemon-config', array(
			'list' => array_values($form),
		));
	}

	/**
	 * AJAX
	 */
	protected function doAjax()
	{
		User::load();
		if (!User::isLoggedIn()) {
			die('Unauthorized');
		}
		$action = Request::any('action');

		// TODO: Removed if not needed anymore.
		if ($action === '') {
			//$this->ajaxDeviceList();
		}
	}

	private function getUsbDeviceList() {
		$usbdevices = array();

		// TODO: Per USB Device 3 querys are executed.. better build a more complex sql query?
		$uid = 0;
		$dbquery = Database::simpleQuery("SELECT * FROM `usblockoff_hw`");
		while ($entry = $dbquery->fetch(PDO::FETCH_ASSOC)) {

			$device = array();

			// Get all props from the hw table.
			$dbquery2 = Database::simpleQuery("SELECT * FROM `statistic_hw_prop` WHERE hwid=:hwid", array(
				'hwid' => $entry['hwid']
			));

			while ($prop = $dbquery2->fetch(PDO::FETCH_ASSOC)) {
				$device[$prop['prop']] = $prop['value'];
			}

			// Get all props from the device table.
			$dbquery3 = Database::simpleQuery("SELECT * FROM `usblockoff_hw_prop` WHERE hwid=:hwid AND serial=:serial", array(
				'hwid' => $entry['hwid'],
				'serial' => $entry['serial']
			));

			while ($prop = $dbquery3->fetch(PDO::FETCH_ASSOC)) {
				$device[$prop['prop']] = $prop['value'];
			}
			if (!empty($device['machineuuid'])) {
				$locationquery = Database::queryFirst("SELECT l.locationname AS 'name', m.clientip AS 'ip' FROM machine AS m JOIN location AS l ON l.locationid=m.locationid
				 WHERE m.machineuuid=:machineuuid", array('machineuuid' => $entry['machineuuid']));
				$device['clientip'] = $locationquery['ip'];
				$device['location'] = $locationquery['name'];
			}

			$device['uid'] = ++$uid;
			$device['id'] = $device['vendorid'] . ":" . $device['productid'];
			$device['serial'] = $entry['serial'];
			$device['date'] = date('d.m.Y', $device['lastseen']);
			$device['time'] = date('G:i', $device['lastseen']);
			$usbdevices[] = $device;
		}

		return $usbdevices;
	}
}