config.lib.inc 14.2 KB
Newer Older
Ad Schellevis's avatar
Ad Schellevis committed
1 2
<?php

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
  Copyright (C) 2015-2016 Franco Fichtner <franco@opnsense.org>
  Ported from config.inc by Erik Kristensen
  Copyright (C) 2004-2010 Scott Ullrich
  Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
Ad Schellevis's avatar
Ad Schellevis committed
30 31
*/

32 33 34
openlog('opnsense', LOG_ODELAY, LOG_USER);
register_shutdown_function('closelog');

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
global $g;	/* XXX make this a getter function for traceability */

$g = array(
	"factory_shipped_username" => "root",
	"factory_shipped_password" => "opnsense",
	"dhcpd_chroot_path" => "/var/dhcpd",
	"unbound_chroot_path" => "/var/unbound",
	"product_name" => "OPNsense",
	"product_website" => "https://opnsense.org",
	"product_email" => "project@opnsense.org",
	"product_copyright_owner" => "Deciso B.V.",
	"product_copyright_years" => "2014-2016",
	"product_copyright_url" => "https://www.deciso.com/",
	"latest_config" => "11.2",
);

51 52
require_once("xmlparse.inc");
require_once("crypt.inc");
53 54
require_once("notices.inc");
require_once("legacy_bindings.inc");
55
require_once('upgrade_config.inc');
56
require_once("certs.inc");
57

58 59 60
/* make a global alias table (for faster lookups) */
function alias_make_table($config)
{
61
    global $aliastable;
62

63
    $aliastable = array();
64

65 66 67 68 69 70 71 72
    if (isset($config['aliases']['alias'])) {
        foreach ($config['aliases']['alias'] as $alias) {
            if ($alias['name']) {
                $aliastable[$alias['name']] = isset($alias['address']) ? $alias['address'] : null;
            }
        }
    }
  }
73

Ad Schellevis's avatar
Ad Schellevis committed
74 75
/****f* config/parse_config
 * NAME
76
 *   parse_config - Read in config.xml if needed and return $config array
Ad Schellevis's avatar
Ad Schellevis committed
77 78 79
 * RESULT
 *   $config      - array containing all configuration variables
 ******/
80
function parse_config()
81
{
82
    $cnf = OPNsense\Core\Config::getInstance();
Ad Schellevis's avatar
Ad Schellevis committed
83

84 85
    // return config data as array, use old "listags" construction to mark certain elements as array (even if they're not recurring)
    $config=$cnf->toArray(listtags());
86

87 88
    /* make alias table (for faster lookups) */
    alias_make_table($config);
89

90
    return $config;
91
}
Ad Schellevis's avatar
Ad Schellevis committed
92 93 94 95 96 97 98 99 100 101 102 103 104

/****f* config/convert_config
 * NAME
 *   convert_config - Attempt to update config.xml.
 * DESCRIPTION
 *   convert_config() reads the current global configuration
 *   and attempts to convert it to conform to the latest
 *   config.xml version. This allows major formatting changes
 *   to be made with a minimum of breakage.
 * RESULT
 *   null
 ******/
/* convert configuration, if necessary */
105 106
function convert_config()
{
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
    global $config, $g;

    if (!isset($config['revision'])) {
        /* force a revision tag for proper handling in config history */
        write_config('Factory configuration', false);
    }

    if ($config['version'] == $g['latest_config']) {
        /* already at latest version */
        return;
    }

    /* special case upgrades */
    /* fix every minute crontab bogons entry */
    if (is_array($config['cron'])) {
        $cron_item_count = count($config['cron']['item']);
        for($x=0; $x<$cron_item_count; $x++) {
            if(stristr($config['cron']['item'][$x]['command'], 'rc.update_bogons')) {
                if($config['cron']['item'][$x]['hour'] == "*" ) {
                    $config['cron']['item'][$x]['hour'] = "3";
                    write_config(gettext("Updated bogon update frequency to 3am"));
                    log_error(gettext("Updated bogon update frequency to 3am"));
                }
            }
        }
    }

    // Save off config version
    $prev_version = $config['version'];
    /* Loop and run upgrade_VER_to_VER() until we're at current version */
    while ($config['version'] < $g['latest_config']) {
        $cur = $config['version'] * 10;
        $next = $cur + 1;
        $migration_function = sprintf('upgrade_%03d_to_%03d', $cur, $next);
        if (function_exists($migration_function)) {
            $migration_function();
        }
        $config['version'] = sprintf('%.1f', $next / 10);
    }

    if ($prev_version != $config['version']) {
        write_config(sprintf(gettext('Upgraded config version level from %s to %s'), $prev_version, $config['version']));
    }
Ad Schellevis's avatar
Ad Schellevis committed
150 151 152 153 154 155 156 157 158 159
}


/****f* config/write_config
 * NAME
 *   write_config - Backup and write the firewall configuration.
 * DESCRIPTION
 *   write_config() handles backing up the current configuration,
 *   applying changes, and regenerating the configuration cache.
 * INPUTS
160 161
 *   $desc  - string containing the a description of configuration changes
 *   $backup  - boolean: do not back up current configuration if false.
Ad Schellevis's avatar
Ad Schellevis committed
162 163 164 165
 * RESULT
 *   null
 ******/
/* save the system configuration */
166
function write_config($desc = '', $backup = true)
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
    global $config;

    if (!empty($_SERVER['REMOTE_ADDR'])) {
        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }
        if (!empty($_SESSION['Username']) && ($_SESSION['Username'] != 'root')) {
            $user = getUserEntry($_SESSION['Username']);
            if (is_array($user) && userHasPrivilege($user, "user-config-readonly")) {
                session_write_close();
                // okay, it's not very nice to check permissions here, but let's make it explicit while we do...
                log_error(gettext("WARNING: User")." ".$_SESSION['Username']." ".gettext("may not write config (user-config-readonly set)"));
                return false;
            }
        }
        session_write_close();
    }

    if (!isset($config['version'])) {
        // Examine config.xml, if for some strange reason the content is unexpected : exit directly.
        log_error(gettext("WARNING: Corrupt config!"));
        return -1;
    }

    $cnf = OPNsense\Core\Config::getInstance();
    $cnf->fromArray($config);
    $revision_info = make_config_revision_entry($desc);
    try {
        $cnf->save($revision_info, $backup);
    } catch (OPNsense\Core\ConfigException $e) {
        // write failure
        syslog(LOG_ERR, gettext('WARNING: Config contents could not be saved. Could not open file!'));
        return -1;
    }

    /* sync carp entries to other firewalls */
    if ( isset($config['hasync']['synchronizetoip']) && trim($config['hasync']['synchronizetoip']) != "") {
        configd_run('filter sync load');
    }

    /* cleanup backups */
    cleanup_backups();

    // on succesfull save, serialize config back to global.
    $config = $cnf->toArray(listtags());
    return $config;
Ad Schellevis's avatar
Ad Schellevis committed
214 215 216 217 218 219
}

/****f* config/reset_factory_defaults
 * NAME
 *   reset_factory_defaults - Reset the system to its default configuration.
 ******/
220
function reset_factory_defaults($sync = true)
221
{
222 223 224 225 226 227 228 229 230 231 232
    mwexec('/bin/rm -r /conf/*');
    disable_security_checks();
    setup_serial_port(false);

    /* as we go through a special case directly reboot */
    $shutdown_cmd = '/sbin/shutdown -or now';
    if ($sync) {
        mwexec($shutdown_cmd);
    } else {
        mwexec_bg($shutdown_cmd);
    }
Ad Schellevis's avatar
Ad Schellevis committed
233 234
}

235 236
function config_restore($conffile)
{
237
    global $config;
Ad Schellevis's avatar
Ad Schellevis committed
238

239 240
    if (!file_exists($conffile))
      return 1;
Ad Schellevis's avatar
Ad Schellevis committed
241

242 243 244
    $cnf = OPNsense\Core\Config::getInstance();
    $cnf->backup();
    $cnf->restoreBackup($conffile);
Ad Schellevis's avatar
Ad Schellevis committed
245

246
    disable_security_checks();
Ad Schellevis's avatar
Ad Schellevis committed
247

248
    $config = parse_config();
Ad Schellevis's avatar
Ad Schellevis committed
249

250
    write_config(gettext("Reverted to") . " " . array_pop(explode("/", $conffile)) . ".", false);
Ad Schellevis's avatar
Ad Schellevis committed
251

252
    return 0;
Ad Schellevis's avatar
Ad Schellevis committed
253 254 255 256 257 258 259 260 261 262
}

/*
 * Disable security checks for DNS rebind and HTTP referrer until next time
 * they pass (or reboot), to aid in preventing accidental lockout when
 * restoring settings like hostname, domain, IP addresses, and settings
 * related to the DNS rebind and HTTP referrer checks.
 * Intended for use when restoring a configuration or directly
 * modifying config.xml without an unconditional reboot.
 */
263 264
function disable_security_checks()
{
265
    touch('/tmp/disable_security_checks');
Ad Schellevis's avatar
Ad Schellevis committed
266 267 268
}

/* Restores security checks.  Should be called after all succeed. */
269 270
function restore_security_checks()
{
271
    @unlink('/tmp/disable_security_checks');
Ad Schellevis's avatar
Ad Schellevis committed
272 273 274
}

/* Returns status of security check temporary disable. */
275 276
function security_checks_disabled()
{
277
    return file_exists('/tmp/disable_security_checks');
Ad Schellevis's avatar
Ad Schellevis committed
278 279
}

Ad Schellevis's avatar
Ad Schellevis committed
280 281 282
/**
 * remove old backups
 */
Franco Fichtner's avatar
Franco Fichtner committed
283 284
function cleanup_backups()
{
285 286 287 288 289 290 291 292 293 294 295 296 297 298
    global $config;
    $i = false;

    if (isset($config['system']['backupcount']) && is_numeric($config['system']['backupcount']) && ($config['system']['backupcount'] >= 0)) {
        $revisions = intval($config['system']['backupcount']);
    } else {
        $revisions = 30;
    }

    $cnf = OPNsense\Core\Config::getInstance();

    $cnt=1;
    foreach ($cnf->getBackups() as $filename) {
        if ($cnt > $revisions ) {
299
            @unlink($filename);
300 301 302
        }
        ++$cnt ;
    }
Ad Schellevis's avatar
Ad Schellevis committed
303 304 305 306
}


function set_device_perms() {
307 308 309 310 311 312 313 314 315 316 317 318 319 320
    $devices = array(
      'pf'  => array(  'user'  => 'root',
            'group'  => 'proxy',
            'mode'  => 0660),
      );

    foreach ($devices as $name => $attr) {
        $path = "/dev/$name";
        if (file_exists($path)) {
            chown($path, $attr['user']);
            chgrp($path, $attr['group']);
            chmod($path, $attr['mode']);
        }
    }
Ad Schellevis's avatar
Ad Schellevis committed
321 322 323
}


324
function make_config_revision_entry($desc = '')
325
{
326 327
    global $config;

328 329
    if (!empty($_SESSION['Username'])) {
        $username = $_SESSION['Username'];
330
    } else {
331
        $username = '(' . trim(shell_exec('/usr/bin/whoami')) . ')';
332 333 334 335 336 337
    }

    if (!empty($_SERVER['REMOTE_ADDR'])) {
        $username .= '@' . $_SERVER['REMOTE_ADDR'];
    }

338
    if (empty($desc)) {
339
        $desc = sprintf(gettext('%s made changes'), $_SERVER['SCRIPT_NAME']);
340 341 342 343 344
    }

    $revision = array();
    $revision['username'] = $username;
    $revision['time'] = microtime(true);
345
    $revision['description'] = $desc;
346 347

    return $revision;
Ad Schellevis's avatar
Ad Schellevis committed
348 349
}

350
/**
351
 * backup config to google drive and return current file list (/ info)
352 353
 *
 */
354 355
function backup_to_google_drive()
{
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
    $cnf = OPNsense\Core\Config::getInstance();
    if ($cnf->isValid()) {
        $config = $cnf->object();
        if (isset($config->system->remotebackup) && isset($config->system->remotebackup->GDriveEnabled) && $config->system->remotebackup->GDriveEnabled == "on") {
            try {
                $client = new Google\API\Drive();
                $client->login($config->system->remotebackup->GDriveEmail->__toString(),
                $config->system->remotebackup->GDriveP12key->__toString());
            } catch (Exception $e) {
                log_error("error connecting to Google Drive");
                return array();
            }

            // backup source data to local strings (plain/encrypted)
            $confdata = file_get_contents('/conf/config.xml');
            $confdata_enc = encrypt_data($confdata, $config->system->remotebackup->GDrivePassword->__toString());
            tagfile_reformat($confdata_enc, $confdata_enc, "config.xml");


            // read filelist (config-*.xml)
            try {
                $files = $client->listFiles($config->system->remotebackup->GDriveFolderID->__toString());
            } catch (Exception $e) {
                log_error("error while fetching filelist from Google Drive");
                return array();
            }

            $configfiles = array();
            foreach ($files as $file) {
                if (fnmatch("config-*.xml", $file['title'])) {
                    $configfiles[$file['title']] = $file;
                }
            }
            krsort($configfiles);


            // backup new file if changed (or if first in backup)
            $target_filename = "config-" . time() . ".xml";
            if (count($configfiles) > 1) {
                // compare last backup with current, only save new
                $bck_data_enc_in = $client->download($configfiles[array_keys($configfiles)[0]]);
                $bck_data_enc = "";
                tagfile_deformat($bck_data_enc_in, $bck_data_enc, "config.xml");
                $bck_data = decrypt_data($bck_data_enc, $config->system->remotebackup->GDrivePassword->__toString());
                if ($bck_data == $confdata) {
                    $target_filename = null;
                }
            }
            if (!is_null($target_filename)) {
                log_error("backup configuration as " . $target_filename);
                $configfiles[$target_filename] = $client->upload($config->system->remotebackup->GDriveFolderID->__toString(),
                $target_filename, $confdata_enc);
                krsort($configfiles);
            }

            // cleanup old files
            if (isset($config->system->remotebackup->GDriveBackupCount) && is_numeric($config->system->remotebackup->GDriveBackupCount->__toString())) {
                $fcount = 0;
                foreach ($configfiles as $filename => $file) {
                    if ($fcount >= $config->system->remotebackup->GDriveBackupCount->__toString()) {
                        log_error("remove " . $filename . " from Google Drive");
                        try {
                            $client->delete($file);
                        } catch (Google_Service_Exception $e) {
                            log_error("unable to remove " . $filename . " from Google Drive");
                        }
                    }
                    $fcount++;
                }
            }

            // return filelist
            return $configfiles;
        }
    }

    // not configured / issue, return empty list
    return array();
434
}