Project

General

Profile

Download (18.3 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("config.lib.inc");
36
require_once("functions.inc");
37
require_once("filter.inc");
38
require_once("shaper.inc");
39
require_once("pkg-utils.inc");
40

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

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

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

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

    
117
function restore_xmldatafile($type='voucher') {
118
	global $config, $g;
119

    
120
	foreach ($config[$type]["{$type}data"]["xmldatafile"] as $file) {
121
		$basename = basename($file['filename']);
122
		$dirname = dirname($g['backuppath'][$type]);
123
		$xmldata_file = "{$dirname}/{$basename}";
124
		if (file_put_contents($xmldata_file, gzinflate(base64_decode($file['data']))) === false) {
125
			log_error(sprintf(gettext("Cannot write %s"), $xmldata_file));
126
			continue;
127
		}
128
	}
129
}
130

    
131
function backup_xmldatafile($tab=false, $type='voucher') {
132
	global $g;
133

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

    
152
	return $result;
153
}
154

    
155
function check_and_returnif_section_exists($section) {
156
	global $config;
157
	if (is_array($config[$section])) {
158
		return true;
159
	}
160
	return false;
161
}
162

    
163
function execPost($post, $postfiles, $ui = true) {
164
	global $config, $g;
165

    
166
	unset($input_errors);
167

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

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

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

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

    
220
				//unlock($lockbckp);
221

    
222
				/*
223
				 *	Backup RRD Data
224
				 */
225

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

    
232
				if (!$post['backuparea'] && $post['backupdata']) {
233
					foreach ($g['backuppath'] as $bk => $path) {
234
						if (!empty($config[$bk])) {
235
							$dataxml = backup_xmldatafile(true, $bk);
236
							$closing_tag = "\t</{$bk}>";
237
							$data = str_replace($closing_tag, $dataxml . $closing_tag, $data);
238
						}
239
					}
240
				}
241

    
242
				if ($post['backuparea'] !== "rrddata" && !$post['donotbackuprrd']) {
243
					$rrd_data_xml = rrd_data_xml();
244
					$closing_tag = "</" . $g['xml_rootobj'] . ">";
245
					$data = str_replace($closing_tag, $rrd_data_xml . $closing_tag, $data);
246
				}
247

    
248
				if ($post['encrypt']) {
249
					$data = encrypt_data($data, $post['encrypt_password']);
250
					tagfile_reformat($data, $data, "config.xml");
251
				}
252

    
253
				if ($ui) {
254
					send_user_download('data', $data, $name);
255
				} else {
256
					return json_encode(array("contents" => base64_encode($data), "name" => $name));
257
				}
258
			}
259
		}
260

    
261
		if ($mode == "restore") {
262
			if ($post['decrypt']) {
263
				if (!$post['decrypt_password']) {
264
					$input_errors[] = gettext("A password for decryption must be supplied and confirmed.");
265
				}
266
			}
267

    
268
			if (!$input_errors) {
269
				if (!$ui || is_uploaded_file($postfiles['conffile']['tmp_name'])) {
270

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

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

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

    
339
								/* this will be picked up by /index.php */
340
								mark_subsystem_dirty("restore");
341
								touch("/conf/needs_package_sync");
342
								/* remove cache, we will force a config reboot */
343
								if (file_exists("{$g['tmp_path']}/config.cache")) {
344
									unlink("{$g['tmp_path']}/config.cache");
345
								}
346
								$config = parse_config(true);
347

    
348
								/* Restore previously pkg repo configured */
349
								$pkg_repo_restored = false;
350
								if (isset($pkg_repo_conf_path)) {
351
									$config['system']['pkg_repo_conf_path'] =
352
									    $pkg_repo_conf_path;
353
									$pkg_repo_restored = true;
354
								} elseif (isset($config['system']['pkg_repo_conf_path'])) {
355
									unset($config['system']['pkg_repo_conf_path']);
356
									$pkg_repo_restored = true;
357
								}
358

    
359
								if ($pkg_repo_restored) {
360
									write_config(gettext("Removing pkg repository set after restoring full configuration"));
361
									pkg_update(true);
362
								}
363

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

    
494
	return array("input_errors" => $input_errors, "savemsg" => $savemsg);
495
}
496

    
497
// Compose a list of recent backups formatted as a JSON array
498
function listBackupsJSON() {
499
	global $g;
500

    
501
	cleanup_backupcache(false);
502

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

    
505
	$backups = array();
506
	foreach($raw as $key => $value) {
507
	    $backups[] = array("time" => $key, "desc" => $value['description'], "size" => $value['filesize'], "vers" => $value['version']);
508
	}
509

    
510
	return json_encode($backups);
511
}
512

    
513
?>
(2-2/2)