Project

General

Profile

Download (10.9 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * autoconfigbackup.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2008-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-2021 Rubicon Communications, LLC (Netgate)
9
 * All rights reserved.
10
 *
11
 * Licensed under the Apache License, Version 2.0 (the "License");
12
 * you may not use this file except in compliance with the License.
13
 * You may obtain a copy of the License at
14
 *
15
 * http://www.apache.org/licenses/LICENSE-2.0
16
 *
17
 * Unless required by applicable law or agreed to in writing, software
18
 * distributed under the License is distributed on an "AS IS" BASIS,
19
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
 * See the License for the specific language governing permissions and
21
 * limitations under the License.
22
 */
23

    
24
require_once("filter.inc");
25
require_once("notices.inc");
26

    
27
// If there is no ssh key in the system to identify this firewall, generate a pair now
28
function get_device_key() {
29
	if (!file_exists("/etc/ssh/ssh_host_ed25519_key.pub")) {
30
		// Remove any possible matching key so we don't get an overwrite prompt
31
		if (file_exists('/etc/ssh/ssh_host_ed25519_key')) {
32
			unlink('/etc/ssh/ssh_host_ed25519_key');
33
		}
34

    
35
		// Generate a new key pair
36
		exec("/usr/bin/nice -n20 /usr/bin/ssh-keygen -t ed25519 -b 4096 -N '' -f /etc/ssh/ssh_host_ed25519_key");
37
		sleep(2);
38

    
39
		$cnt = 0;
40
		while(!file_exists("/etc/ssh/ssh_host_ed25519_key.pub")) {
41
			sleep(2);
42
			if (++$cnt > 10) {
43
				return "";
44
			}
45
		}
46
	}
47

    
48
	$pkey =  file_get_contents("/etc/ssh/ssh_host_ed25519_key.pub");
49

    
50
	// Check that the key looks reasonable
51
	if (substr($pkey, 0, 3) != "ssh") {
52
		return "";
53
	}
54

    
55
	return hash("sha256", $pkey);
56
}
57

    
58
$origkey = get_device_key();
59

    
60
if (isset($_REQUEST['userkey']) && !empty($_REQUEST['userkey'])) {
61
	$userkey = htmlentities($_REQUEST['userkey']);
62
} else {
63
	$userkey = get_device_key();
64
}
65

    
66
$uniqueID = system_get_uniqueid();
67

    
68
/* Check whether ACB is enabled */
69
function acb_enabled() {
70
	global $config;
71
	$acb_enabled = false;
72

    
73
	if (is_array($config['system']['acb'])) {
74
		if ($config['system']['acb']['enable'] == "yes") {
75
			$acb_enabled = true;
76
		}
77
	}
78

    
79
	return $acb_enabled;
80
}
81

    
82
// Ensures patches match
83
function acb_custom_php_validation_command($post, &$input_errors) {
84
	global $_POST, $savemsg, $config;
85

    
86
	// Do nothing when ACB is disabled in configuration
87
	// This also makes it possible to delete the credentials from config.xml
88
	if (!acb_enabled()) {
89
		// We do not need to store this value.
90
		unset($_POST['testconnection']);
91
		return;
92
	}
93

    
94
	if (!$post['crypto_password'] or !$post['crypto_password2']) {
95
		$input_errors[] = "The encryption password is required.";
96
	}
97

    
98
	if ($post['crypto_password'] <> $post['crypto_password2']) {
99
		$input_errors[] = "Sorry, the entered encryption passwords do not match.";
100
	}
101

    
102
	if ($post['testconnection']) {
103
		$status = test_connection($post);
104
		if ($status) {
105
			$savemsg = "Connection to the ACB server was tested with no errors.";
106
		}
107
	}
108

    
109
	// We do not need to store this value.
110
	unset($_POST['testconnection']);
111
}
112

    
113
function acb_custom_php_resync_config_command() {
114
	// Do nothing when ACB is disabled in configuration
115
	if (!acb_enabled()) {
116
		return;
117
	}
118

    
119
	unlink_if_exists("/cf/conf/lastpfSbackup.txt");
120

    
121
	if (!function_exists("filter_configure")) {
122
		require_once("filter.inc");
123
	}
124

    
125
	filter_configure();
126

    
127
	if ($savemsg) {
128
		$savemsg .= "<br/>";
129
	}
130

    
131
	$savemsg .= "A configuration backup has been queued.";
132
}
133

    
134
function test_connection($post) {
135
	global $savemsg, $config, $g;
136

    
137
	// Do nothing when booting or when not enabled
138
	if (platform_booting() || !acb_enabled()) {
139
		return;
140
	}
141

    
142
	// Separator used during client / server communications
143
	$oper_sep = "\|\|";
144

    
145
	// Encryption password
146
	$decrypt_password = $post['crypto_password'];
147

    
148
	// Defined username. Username must be sent lowercase. See Redmine #7127 and Netgate Redmine #163
149
	$username = strtolower($post['username']);
150

    
151
	// Defined password
152
	$password = $post['password'];
153

    
154
	// Set hostname
155
	$hostname = $config['system']['hostname'] . "." . $config['system']['domain'];
156

    
157
	// URL to restore.php
158
	$get_url = "https://acb.netgate.com/getbkp";
159

    
160
	// Populate available backups
161
	$curl_session = curl_init();
162
	curl_setopt($curl_session, CURLOPT_URL, $get_url);
163
	curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, 1);
164
	curl_setopt($curl_session, CURLOPT_POST, 1);
165
	curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, 1);
166
	curl_setopt($curl_session, CURLOPT_CONNECTTIMEOUT, 55);
167
	curl_setopt($curl_session, CURLOPT_TIMEOUT, 30);
168
	curl_setopt($curl_session, CURLOPT_USERAGENT, $g['product_label'] . '/' . rtrim(file_get_contents("/etc/version")));
169
	// Proxy
170
	set_curlproxy($curl_session);
171

    
172
	curl_setopt($curl_session, CURLOPT_POSTFIELDS, "action=showbackups&hostname={$hostname}");
173
	$data = curl_exec($curl_session);
174

    
175
	if (curl_errno($curl_session)) {
176
		return("An error occurred " . curl_error($curl_session));
177
	} else {
178
		curl_close($curl_session);
179
	}
180

    
181
	return;
182
}
183

    
184
function upload_config($manual = false) {
185
	global $config, $g, $input_errors, $userkey, $uniqueID;
186

    
187
	if (empty($userkey)) {
188
		$userkey = get_device_key();
189
	}
190

    
191
	if (empty($uniqueID)) {
192
		$uniqueID = system_get_uniqueid();
193
	}
194

    
195
	// Do nothing when booting or when not enabled
196
	if (platform_booting() || !acb_enabled()) {
197
		return;
198
	}
199

    
200
	/*
201
	 * pfSense upload config to acb.netgate.com script
202
	 * This file plugs into config.inc (/usr/local/pkg/parse_config)
203
	 * and runs every time the running firewall filter changes.
204
	 *
205
	 */
206

    
207
	if (file_exists("/tmp/acb_nooverwrite")) {
208
		unlink("/tmp/acb_nooverwrite");
209
		$nooverwrite = "true";
210
	} else {
211
		$nooverwrite = "false";
212
	}
213

    
214
	// Define some needed variables
215
	if (file_exists("/cf/conf/lastpfSbackup.txt")) {
216
		$last_backup_date = str_replace("\n", "", file_get_contents("/cf/conf/lastpfSbackup.txt"));
217
	} else {
218
		$last_backup_date = "";
219
	}
220

    
221
	$last_config_change = $config['revision']['time'];
222
	$hostname = $config['system']['hostname'] . "." . $config['system']['domain'];
223
	$reason	= $config['revision']['description'];
224

    
225
	if ($manual && array_key_exists('numman', $config['system']['acb'])) {
226
		$manmax = $config['system']['acb']['numman'];
227
	} else {
228
		$manmax = "0";
229
	}
230

    
231
	$encryptpw = $config['system']['acb']['encryption_password'];
232

    
233
	// Define upload_url, must be present after other variable definitions due to username, password
234
	$upload_url = "https://acb.netgate.com/save";
235

    
236
	if (!$encryptpw) {
237
		if (!file_exists("/cf/conf/autoconfigback.notice")) {
238
			$notice_text = "The encryption password is not set for Automatic Configuration Backup.";
239
			$notice_text .= " Please correct this in Services -> AutoConfigBackup -> Settings.";
240
			log_error($notice_text);
241
			file_notice("AutoConfigBackup", $notice_text, $notice_text, "");
242
			touch("/cf/conf/autoconfigback.notice");
243
		}
244
	} else {
245
		/* If configuration has changed, upload to pfS */
246
		if ($last_backup_date <> $last_config_change) {
247

    
248
			$notice_text = "Beginning configuration backup to " . $upload_url;
249
			log_error($notice_text);
250
			update_filter_reload_status($notice_text);
251

    
252
			// Encrypt config.xml
253
			$data = file_get_contents("/cf/conf/config.xml");
254
			$raw_config_sha256_hash = trim(shell_exec("/sbin/sha256 /cf/conf/config.xml | /usr/bin/awk '{ print $4 }'"));
255
			$data = encrypt_data($data, $encryptpw);
256
			$tmpname = "/tmp/" . $raw_config_sha256_hash . ".tmp";
257
			tagfile_reformat($data, $data, "config.xml");
258
			file_put_contents($tmpname, $data);
259

    
260
			$post_fields = array(
261
				'reason' => htmlspecialchars($reason),
262
				'uid' => $uniqueID,
263
				'file' => curl_file_create($tmpname, 'image/jpg', 'config.jpg'),
264
				'userkey' => htmlspecialchars($userkey),
265
				'sha256_hash' => $raw_config_sha256_hash,
266
				'version' => $g['product_version'],
267
				'hint' => $config['system']['acb']['hint'],
268
				'manmax' => $manmax
269
			);
270

    
271
			// Check configuration into the ESF repo
272
			$curl_session = curl_init();
273

    
274
			curl_setopt($curl_session, CURLOPT_URL, "https://acb.netgate.com/save");
275
			curl_setopt($curl_session, CURLOPT_POST, count($post_fields));
276
			curl_setopt($curl_session, CURLOPT_POSTFIELDS, $post_fields);
277
			curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, 1);
278
			curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, 1);
279
			curl_setopt($curl_session, CURLOPT_CONNECTTIMEOUT, 55);
280
			curl_setopt($curl_session, CURLOPT_TIMEOUT, 30);
281
			curl_setopt($curl_session, CURLOPT_USERAGENT, $g['product_label'] . '/' . rtrim(file_get_contents("/etc/version")));
282
			// Proxy
283
			set_curlproxy($curl_session);
284

    
285
			$data = curl_exec($curl_session);
286

    
287
			unlink_if_exists($tmpname);
288

    
289
			if (curl_errno($curl_session)) {
290
				$fd = fopen("/tmp/backupdebug.txt", "w");
291
				fwrite($fd, $upload_url . "" . $fields_string . "\n\n");
292
				fwrite($fd, $data);
293
				fwrite($fd, curl_error($curl_session));
294
				fclose($fd);
295
			} else {
296
				curl_close($curl_session);
297
			}
298

    
299
			if (strpos($data, "500") != false) {
300
				$notice_text = sprintf(gettext(
301
				    "An error occurred while uploading your %s configuration to "), $g['product_label']) .
302
				    $upload_url . " (" . htmlspecialchars($data) . ")";
303
				log_error($notice_text . " - " . $data);
304
				file_notice("AutoConfigBackup", $notice_text);
305
				update_filter_reload_status($notice_text);
306
				$input_errors["acb_upload"] = $notice_text;
307
			} else {
308
				// Update last pfS backup time
309
				$fd = fopen("/cf/conf/lastpfSbackup.txt", "w");
310
				fwrite($fd, $config['revision']['time']);
311
				fclose($fd);
312
				$notice_text = "End of configuration backup to " . $upload_url . " (success).";
313
				log_error($notice_text);
314
				update_filter_reload_status($notice_text);
315
			}
316

    
317
		} else {
318
			// Debugging
319
			//log_error("No https://acb.netgate.com backup required.");
320
		}
321
	}
322
}
323

    
324
// Save the updated ACB configuration
325
// Create a crontab entry for scheduled backups
326
// if frequency == "cron", a new crontab entry is created, otherwise any existing
327
// ACB entry is removed
328
function setup_ACB($enable, $hint, $frequency, $hours, $month, $day, $dow, $numman, $pwd) {
329
	global $config;
330

    
331
	$config['system']['acb']['enable'] = $enable;
332
	$config['system']['acb']['hint'] = $hint;
333
	$config['system']['acb']['frequency'] = $frequency;
334
	$config['system']['acb']['hour'] = $hours;
335
	$config['system']['acb']['month'] = $month;
336
	$config['system']['acb']['day'] = $day;
337
	$config['system']['acb']['dow'] = $dow;
338
	$config['system']['acb']['numman'] = $numman;
339
	if (strlen($pwd) >= 8) {
340
		$config['system']['acb']['encryption_password'] = $pwd;
341
	}
342

    
343

    
344
	init_config_arr(array('cron'));
345
	$a_cron = &$config['cron']['item'];
346
	$croncmd = "/usr/bin/nice -n20 /usr/local/bin/php /usr/local/sbin/execacb.php";
347

    
348
	$i = 0;
349

    
350
	// Remove the existing cron job
351
	if (count($a_cron) > 0) {
352
		foreach ($a_cron as $ent) {
353
			if ($ent['command'] === $croncmd) {
354
				unset($a_cron[$i]);
355
				break;
356
			}
357

    
358
		$i++;
359
		}
360
	}
361

    
362
	if ($frequency == "cron") {
363
		$crondef = array();
364
		$crondef['minute'] = '0';
365
		$crondef['hour'] = $hours;
366
		$crondef['mday'] = $day;
367
		$crondef['month'] = $month;
368
		$crondef['wday'] = $dow;
369
		$crondef['who'] = 'root';
370
		$crondef['command'] = $croncmd;
371

    
372
		$a_cron[$i] = $crondef;
373
	}
374

    
375
	write_config("AutoConfigBackup settings updated");
376
	configure_cron();
377
}
(1-1/61)