Project

General

Profile

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

    
28
/* Allow additional execution time 0 = no limit. */
29
ini_set('max_execution_time', '0');
30
ini_set('max_input_time', '0');
31

    
32
/* omit no-cache headers because it confuses IE with file downloads */
33
$omit_nocacheheaders = true;
34
require_once("config.gui.inc");
35
require_once("functions.inc");
36
require_once("filter.inc");
37
require_once("shaper.inc");
38
require_once("pkg-utils.inc");
39

    
40
$rrddbpath = "/var/db/rrd";
41
$rrdtool = "/usr/bin/nice -n20 /usr/local/bin/rrdtool";
42

    
43
function rrd_data_xml() {
44
	global $rrddbpath;
45
	global $rrdtool;
46

    
47
	$result = "\t<rrddata>\n";
48
	$rrd_files = glob("{$rrddbpath}/*.rrd");
49
	$xml_files = array();
50
	foreach ($rrd_files as $rrd_file) {
51
		$basename = basename($rrd_file);
52
		$xml_file = preg_replace('/\.rrd$/', ".xml", $rrd_file);
53
		exec("$rrdtool dump '{$rrd_file}' '{$xml_file}'");
54
		$xml_data = file_get_contents($xml_file);
55
		unlink($xml_file);
56
		if ($xml_data !== false) {
57
			$result .= "\t\t<rrddatafile>\n";
58
			$result .= "\t\t\t<filename>{$basename}</filename>\n";
59
			$result .= "\t\t\t<xmldata>" . base64_encode(gzdeflate($xml_data)) . "</xmldata>\n";
60
			$result .= "\t\t</rrddatafile>\n";
61
		}
62
	}
63
	$result .= "\t</rrddata>\n";
64
	return $result;
65
}
66

    
67
function restore_rrddata() {
68
	global $config, $g, $rrdtool, $input_errors;
69
	foreach ($config['rrddata']['rrddatafile'] as $rrd) {
70
		if ($rrd['xmldata']) {
71
			$rrd_file = "{$g['vardb_path']}/rrd/{$rrd['filename']}";
72
			$xml_file = preg_replace('/\.rrd$/', ".xml", $rrd_file);
73
			if (file_put_contents($xml_file, gzinflate(base64_decode($rrd['xmldata']))) === false) {
74
				log_error(sprintf(gettext("Cannot write %s"), $xml_file));
75
				continue;
76
			}
77
			$output = array();
78
			$status = null;
79
			exec("$rrdtool restore -f '{$xml_file}' '{$rrd_file}'", $output, $status);
80
			if ($status) {
81
				log_error("rrdtool restore -f '{$xml_file}' '{$rrd_file}' failed returning {$status}.");
82
				continue;
83
			}
84
			unlink($xml_file);
85
		} else if ($rrd['data']) {
86
			$rrd_file = "{$g['vardb_path']}/rrd/{$rrd['filename']}";
87
			$rrd_fd = fopen($rrd_file, "w");
88
			if (!$rrd_fd) {
89
				log_error(sprintf(gettext("Cannot write %s"), $rrd_file));
90
				continue;
91
			}
92
			$data = base64_decode($rrd['data']);
93
			/* Try to decompress the data. */
94
			$dcomp = @gzinflate($data);
95
			if ($dcomp) {
96
				/* If the decompression worked, write the decompressed data */
97
				if (fwrite($rrd_fd, $dcomp) === false) {
98
					log_error(sprintf(gettext("fwrite %s failed"), $rrd_file));
99
					continue;
100
				}
101
			} else {
102
				/* If the decompression failed, it wasn't compressed, so write raw data */
103
				if (fwrite($rrd_fd, $data) === false) {
104
					log_error(sprintf(gettext("fwrite %s failed"), $rrd_file));
105
					continue;
106
				}
107
			}
108
			if (fclose($rrd_fd) === false) {
109
				log_error(sprintf(gettext("fclose %s failed"), $rrd_file));
110
				continue;
111
			}
112
		}
113
	}
114
}
115

    
116
function restore_xmldatafile($type='voucher') {
117
	global $config, $g;
118
	foreach ($config[$type]["{$type}data"]["xmldatafile"] as $file) {
119
		$basename = basename($file['filename']);
120
		$xmldata_file = "{$g['vardb_path']}/{$basename}";
121
		if (file_put_contents($xmldata_file, gzinflate(base64_decode($file['data']))) === false) {
122
			log_error(sprintf(gettext("Cannot write %s"), $xmldata_file));
123
			continue;
124
		}
125
	}
126
}
127

    
128
function backup_xmldatafile($tab=false, $type='voucher') {
129
	global $g;
130

    
131
	$xmldata_files = glob("{$g['vardb_path']}/{$type}*.db");
132
	if (empty($xmldata_files)) {
133
		return;
134
	}
135
	$t = ($tab) ? "\t" : "";
136
	$result = "\t<{$type}data>\n";
137
	foreach ($xmldata_files as $xmldata_file) {
138
		$basename = basename($xmldata_file);
139
		$data = file_get_contents($xmldata_file);
140
		if ($data !== false) {
141
			$result .= "{$t}\t\t<xmldatafile>\n";
142
			$result .= "{$t}\t\t\t<filename>{$basename}</filename>\n";
143
			$result .= "{$t}\t\t\t<data>" . base64_encode(gzdeflate($data)) . "</data>\n";
144
			$result .= "{$t}\t\t</xmldatafile>\n";
145
		}
146
	}
147
	$result .= "{$t}\t</{$type}data>\n";
148

    
149
	return $result;
150
}
151

    
152
function check_and_returnif_section_exists($section) {
153
	global $config;
154
	if (is_array($config[$section])) {
155
		return true;
156
	}
157
	return false;
158
}
159

    
160
function execPost($post, $postfiles, $ui = true) {
161
	global $config, $g;
162

    
163
	unset($input_errors);
164

    
165
	if ($post['restore']) {
166
		$mode = "restore";
167
	} else if ($post['download']) {
168
		$mode = "download";
169
	}
170
	if ($post["nopackages"] <> "") {
171
		$options = "nopackages";
172
	}
173

    
174
	if ($mode) {
175
		if ($mode == "download") {
176
			if ($post['encrypt']) {
177
				if (!$post['encrypt_password'] || ($post['encrypt_password'] != $post['encrypt_password_confirm'])) {
178
					$input_errors[] = gettext("Supplied password and confirmation do not match.");
179
				}
180
			}
181

    
182
			if (!$input_errors) {
183
				$host = "{$config['system']['hostname']}.{$config['system']['domain']}";
184
				$name = "config-{$host}-".date("YmdHis").".xml";
185
				$data = "";
186

    
187
				if ($options == "nopackages") {
188
					if (!$post['backuparea']) {
189
						/* backup entire configuration */
190
						$data = file_get_contents("{$g['conf_path']}/config.xml");
191
					} else {
192
						/* backup specific area of configuration */
193
						$data = backup_config_section($post['backuparea']);
194
						$name = "{$post['backuparea']}-{$name}";
195
					}
196
					$data = preg_replace('/\t*<installedpackages>.*<\/installedpackages>\n/sm', '', $data);
197
				} else {
198
					if (!$post['backuparea']) {
199
						/* backup entire configuration */
200
						$data = file_get_contents("{$g['conf_path']}/config.xml");
201
					} else if ($post['backuparea'] === "rrddata") {
202
						$data = rrd_data_xml();
203
						$name = "{$post['backuparea']}-{$name}";
204
					} else if ($post['backuparea'] === "captiveportal") {
205
						$data = backup_config_section($post['backuparea']);
206
						$captiveportal_data_xml = backup_xmldatafile(false, 'captiveportal');
207
						$closing_tag = "</captiveportal>";
208
						$data = str_replace($closing_tag, $captiveportal_data_xml . $closing_tag, $data);
209
						$name = "{$post['backuparea']}-{$name}";
210
					} else if ($post['backuparea'] === "voucher") {
211
						$data = backup_config_section($post['backuparea']);
212
						$voucher_data_xml = backup_xmldatafile(false, 'voucher');
213
						$closing_tag = "</voucher>";
214
						$data = str_replace($closing_tag, $voucher_data_xml . $closing_tag, $data);
215
						$name = "{$post['backuparea']}-{$name}";
216
					} else {
217
						/* backup specific area of configuration */
218
						$data = backup_config_section($post['backuparea']);
219
						$name = "{$post['backuparea']}-{$name}";
220
					}
221
				}
222

    
223
				//unlock($lockbckp);
224

    
225
				/*
226
				 *	Backup RRD Data
227
				 */
228

    
229
				/* If the config on disk had rrddata tags already, remove that section first.
230
				 * See https://redmine.pfsense.org/issues/8994 and
231
				 *     https://redmine.pfsense.org/issues/10508 */
232
				$data = preg_replace("/[[:blank:]]*<rrddata>.*<\\/rrddata>[[:blank:]]*\n*/s", "", $data);
233
				$data = preg_replace("/[[:blank:]]*<rrddata\\/>[[:blank:]]*\n*/", "", $data);
234

    
235
				if (!$post['backuparea'] && !empty($config['captiveportal'])) {
236
					$captiveportal_data_xml = backup_xmldatafile(true, 'captiveportal');
237
					$closing_tag = "</captiveportal>";
238
					$data = str_replace($closing_tag, $captiveportal_data_xml . $closing_tag, $data);
239
				}
240

    
241
				if (!$post['backuparea'] && !empty($config['voucher'])) {
242
					$voucher_data_xml = backup_xmldatafile(true, 'voucher');
243
					$closing_tag = "</voucher>";
244
					$data = str_replace($closing_tag, $voucher_data_xml . $closing_tag, $data);
245
				}
246

    
247
				if ($post['backuparea'] !== "rrddata" && !$post['donotbackuprrd']) {
248
					$rrd_data_xml = rrd_data_xml();
249
					$closing_tag = "</" . $g['xml_rootobj'] . ">";
250
					$data = str_replace($closing_tag, $rrd_data_xml . $closing_tag, $data);
251
				}
252

    
253
				if ($post['encrypt']) {
254
					$data = encrypt_data($data, $post['encrypt_password']);
255
					tagfile_reformat($data, $data, "config.xml");
256
				}
257

    
258
				if ($ui) {
259
					send_user_download('data', $data, $name);
260
				} else {
261
					return ui_encode(array("contents" => base64_encode($data), "name" => $name));
262
				}
263
			}
264
		}
265

    
266
		if ($mode == "restore") {
267
			if ($post['decrypt']) {
268
				if (!$post['decrypt_password']) {
269
					$input_errors[] = gettext("A password for decryption must be supplied and confirmed.");
270
				}
271
			}
272

    
273
			if (!$input_errors) {
274
				if (!$ui || is_uploaded_file($postfiles['conffile']['tmp_name'])) {
275

    
276
					/* read the file contents */
277
					$data = $ui ? file_get_contents($postfiles['conffile']['tmp_name']) : $postfiles['conffile']['tmp_name'];
278
					if (!$data) {
279
						$input_errors[] = gettext("Warning, could not read file {$postfiles['conffile']['tmp_name']}");
280
					} elseif ($post['decrypt']) {
281
						if (!tagfile_deformat($data, $data, "config.xml")) {
282
							$input_errors[] = gettext("The uploaded file does not appear to contain an encrypted pfsense configuration.");
283
						} else {
284
							$data = decrypt_data($data, $post['decrypt_password']);
285
							if (empty($data)) {
286
								$input_errors[] = gettext("File decryption failed. Incorrect password or file is invalid.");
287
							}
288
						}
289
					}
290
					if (stristr($data, "<m0n0wall>")) {
291
						log_error(gettext("Upgrading m0n0wall configuration to pfsense."));
292
						/* m0n0wall was found in config.  convert it. */
293
						$data = str_replace("m0n0wall", "pfsense", $data);
294
						$m0n0wall_upgrade = true;
295
					}
296

    
297
					/* If the config on disk had empty rrddata tags, remove them to
298
					 * avoid an XML parsing error.
299
					 * See https://redmine.pfsense.org/issues/8994 */
300
					$data = preg_replace("/<rrddata><\\/rrddata>/", "", $data);
301
					$data = preg_replace("/<rrddata\\/>/", "", $data);
302

    
303
					if ($post['restorearea'] && !$input_errors) {
304
						/* restore a specific area of the configuration */
305
						if (!stristr($data, "<" . $post['restorearea'] . ">")) {
306
							$input_errors[] = gettext("An area to restore was selected but the correct xml tag could not be located.");
307
						} else {
308
							if (!restore_config_section($post['restorearea'], $data)) {
309
								$input_errors[] = gettext("An area to restore was selected but the correct xml tag could not be located.");
310
							} else {
311
								if ($config['rrddata'] || $config['voucher']['voucherdata'] ||
312
								    $config['captiveportal']['captiveportaldata']) {
313
									if ($config['rrddata']) {
314
										restore_rrddata();
315
										unset($config['rrddata']);
316
										write_config(sprintf(gettext("Unset RRD data from configuration after restoring %s configuration area"), $post['restorearea']));
317
									}
318
									if (($post['restorearea'] == 'voucher') && $config['voucher']['voucherdata']) {
319
										restore_xmldatafile('voucher');
320
										unset($config['voucher']['voucherdata']);
321
										write_config(sprintf(gettext("Unset Voucher data from configuration after restoring %s configuration area"), $post['restorearea']));
322
									}
323
									if (($post['restorearea'] == 'captiveportal') &&
324
									    $config['captiveportal']['captiveportaldata']) {
325
										restore_xmldatafile('captiveportal');
326
										unset($config['captiveportal']['captiveportaldata']);
327
										write_config(sprintf(gettext("Unset Captive Portal DB and Used MACs data from configuration after restoring %s configuration area"), $post['restorearea']));
328
									}
329
									unlink_if_exists("{$g['tmp_path']}/config.cache");
330
									convert_config();
331
								}
332
								filter_configure();
333
								$savemsg = gettext("The configuration area has been restored. The firewall may need to be rebooted.");
334
							}
335
						}
336
					} elseif (!$input_errors) {
337
						if (!stristr($data, "<" . $g['xml_rootobj'] . ">")) {
338
							$input_errors[] = sprintf(gettext("A full configuration restore was selected but a %s tag could not be located."), $g['xml_rootobj']);
339
						} else {
340
							/* restore the entire configuration */
341
							file_put_contents($postfiles['conffile']['tmp_name'], $data);
342
							if (config_install($postfiles['conffile']['tmp_name']) == 0) {
343
								/* Save current pkg repo to re-add on new config */
344
								unset($pkg_repo_conf_path);
345
								if (isset($config['system']['pkg_repo_conf_path'])) {
346
									$pkg_repo_conf_path = $config['system']['pkg_repo_conf_path'];
347
								}
348

    
349
								/* this will be picked up by /index.php */
350
								mark_subsystem_dirty("restore");
351
								touch("/conf/needs_package_sync");
352
								/* remove cache, we will force a config reboot */
353
								if (file_exists("{$g['tmp_path']}/config.cache")) {
354
									unlink("{$g['tmp_path']}/config.cache");
355
								}
356
								$config = parse_config(true);
357

    
358
								/* Restore previously pkg repo configured */
359
								$pkg_repo_restored = false;
360
								if (isset($pkg_repo_conf_path)) {
361
									$config['system']['pkg_repo_conf_path'] =
362
									    $pkg_repo_conf_path;
363
									$pkg_repo_restored = true;
364
								} elseif (isset($config['system']['pkg_repo_conf_path'])) {
365
									unset($config['system']['pkg_repo_conf_path']);
366
									$pkg_repo_restored = true;
367
								}
368

    
369
								if ($pkg_repo_restored) {
370
									write_config(gettext("Removing pkg repository set after restoring full configuration"));
371
									pkg_update(true);
372
								}
373

    
374
								if (file_exists("/boot/loader.conf")) {
375
									$loaderconf = file_get_contents("/boot/loader.conf");
376
									if (strpos($loaderconf, "console=\"comconsole") ||
377
									    strpos($loaderconf, "boot_serial=\"YES")) {
378
										$config['system']['enableserial'] = true;
379
										write_config(gettext("Restore serial console enabling in configuration."));
380
									}
381
									unset($loaderconf);
382
								}
383
								if (file_exists("/boot/loader.conf.local")) {
384
									$loaderconf = file_get_contents("/boot/loader.conf.local");
385
									if (strpos($loaderconf, "console=\"comconsole") ||
386
									    strpos($loaderconf, "boot_serial=\"YES")) {
387
										$config['system']['enableserial'] = true;
388
										write_config(gettext("Restore serial console enabling in configuration."));
389
									}
390
									unset($loaderconf);
391
								}
392
								/* extract out rrd items, unset from $config when done */
393
								if ($config['rrddata'] || $config['voucher']['voucherdata'] ||
394
							            $config['captiveportal']['captiveportaldata']) {
395
									if ($config['rrddata']) {
396
										restore_rrddata();
397
										unset($config['rrddata']);
398
									}
399
									if ($config['voucher']['voucherdata']) {
400
										restore_xmldatafile('voucher');
401
										unset($config['voucher']['voucherdata']);
402
									}
403
									if ($config['captiveportal']['captiveportaldata']) {
404
										restore_xmldatafile('captiveportal');
405
										unset($config['captiveportal']['captiveportaldata']);
406
									}
407
									write_config(gettext("Unset RRD, Voucher, Captive Portal DB and Used MACs data from configuration after full restore."));
408
									unlink_if_exists("{$g['tmp_path']}/config.cache");
409
									convert_config();
410
								}
411
								if ($m0n0wall_upgrade == true) {
412
									if ($config['system']['gateway'] <> "") {
413
										$config['interfaces']['wan']['gateway'] = $config['system']['gateway'];
414
									}
415
									unset($config['shaper']);
416
									/* optional if list */
417
									$ifdescrs = get_configured_interface_list(true);
418
									/* remove special characters from interface descriptions */
419
									if (is_array($ifdescrs)) {
420
										foreach ($ifdescrs as $iface) {
421
											$config['interfaces'][$iface]['descr'] = preg_replace('/[^a-z_0-9]/i', '', $config['interfaces'][$iface]['descr']);
422
										}
423
									}
424
									/* check for interface names with an alias */
425
									if (is_array($ifdescrs)) {
426
										foreach ($ifdescrs as $iface) {
427
											if (is_alias($config['interfaces'][$iface]['descr'])) {
428
												$origname = $config['interfaces'][$iface]['descr'];
429
												update_alias_name($origname . "Alias", $origname);
430
											}
431
										}
432
									}
433
									unlink_if_exists("{$g['tmp_path']}/config.cache");
434
									// Reset configuration version to something low
435
									// in order to force the config upgrade code to
436
									// run through with all steps that are required.
437
									$config['system']['version'] = "1.0";
438
									// Deal with descriptions longer than 63 characters
439
									for ($i = 0; isset($config["filter"]["rule"][$i]); $i++) {
440
										if (count($config['filter']['rule'][$i]['descr']) > 63) {
441
											$config['filter']['rule'][$i]['descr'] = substr($config['filter']['rule'][$i]['descr'], 0, 63);
442
										}
443
									}
444
									// Move interface from ipsec to enc0
445
									for ($i = 0; isset($config["filter"]["rule"][$i]); $i++) {
446
										if ($config['filter']['rule'][$i]['interface'] == "ipsec") {
447
											$config['filter']['rule'][$i]['interface'] = "enc0";
448
										}
449
									}
450
									// Convert icmp types
451
									// http://www.openbsd.org/cgi-bin/man.cgi?query=icmp&sektion=4&arch=i386&apropos=0&manpath=OpenBSD+Current
452
									$convert = array('echo' => 'echoreq', 'timest' => 'timereq', 'timestrep' => 'timerep');
453
									foreach ($config["filter"]["rule"] as $ruleid => &$ruledata) {
454
										if ($convert[$ruledata['icmptype']]) {
455
											$ruledata['icmptype'] = $convert[$ruledata['icmptype']];
456
										}
457
									}
458
									$config['diag']['ipv6nat'] = true;
459
									write_config(gettext("Imported m0n0wall configuration"));
460
									convert_config();
461
									$savemsg = gettext("The m0n0wall configuration has been restored and upgraded to pfSense.");
462
									mark_subsystem_dirty("restore");
463
								}
464
								if (is_array($config['captiveportal'])) {
465
									foreach ($config['captiveportal'] as $cp) {
466
										if (isset($cp['enable'])) {
467
											/* for some reason ipfw doesn't init correctly except on bootup sequence */
468
											mark_subsystem_dirty("restore");
469
											break;
470
										}
471
									}
472
								}
473
								console_configure();
474
								if (is_interface_mismatch() == true) {
475
									touch("/var/run/interface_mismatch_reboot_needed");
476
									clear_subsystem_dirty("restore");
477
									convert_config();
478
									if ($ui) {
479
										header("Location: interfaces_assign.php");
480
									}
481
									exit;
482
								}
483
								if (is_interface_vlan_mismatch() == true) {
484
									touch("/var/run/interface_mismatch_reboot_needed");
485
									clear_subsystem_dirty("restore");
486
									convert_config();
487
									if ($ui) {
488
										header("Location: interfaces_assign.php");
489
									}
490
									exit;
491
								}
492
							} else {
493
								$input_errors[] = gettext("The configuration could not be restored.");
494
							}
495
						}
496
					}
497
				} else {
498
					$input_errors[] = gettext("The configuration could not be restored (file upload error).");
499
				}
500
			}
501
		}
502
	}
503

    
504
	return $input_errors;
505
}
506

    
507
// Compose a list of recent backups formatted as a JSON array
508
function listBackupsJSON() {
509
	global $g;
510

    
511
	$raw = unserialize(file_get_contents($g["cf_conf_path"] . "/backup/backup.cache"));
512

    
513
	$backups = array();
514
	foreach($raw as $key => $value) {
515
	    $backups[] = array("time" => $key, "desc" => $value['description'], "size" => $value['filesize'], "vers" => $value['version']);
516
	}
517

    
518
	return json_encode($backups);
519
}
520

    
521
?>
(2-2/2)