rc.filter_synchronize 13.2 KB
Newer Older
1
#!/usr/local/bin/php
Ad Schellevis's avatar
Ad Schellevis committed
2
<?php
3

Ad Schellevis's avatar
Ad Schellevis committed
4
/*
5
    Copyright (C) 2016 Deciso B.V.
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
    Copyright (C) 2004-2006 Scott Ullrich
    Copyright (C) 2005 Bill Marquette
    Copyright (C) 2006 Peter Allgeyer
    Copyright (C) 2008 Ermal Luci
    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
33 34 35 36
*/

require_once("config.inc");
require_once("filter.inc");
37
require_once("util.inc");
Ad Schellevis's avatar
Ad Schellevis committed
38
require_once("interfaces.inc");
39
require_once("XMLRPC_Client.inc") ;
40
require_once("util.inc");
Ad Schellevis's avatar
Ad Schellevis committed
41

42 43 44
/**
 * fetch carp vips from config with modified advskew for the backup host to use
 * @return array
Ad Schellevis's avatar
Ad Schellevis committed
45
 */
46 47
function get_vip_config_section()
{
48 49
    global $config;

50
    if (!isset($config['virtualip']['vip'])) {
51 52 53 54 55 56 57 58
        return;
    }
    $temp = array();
    $temp['vip'] = array();
    foreach($config['virtualip']['vip'] as $section) {
        if ($section['mode'] != "carp") {
            continue;
        }
59 60 61 62
        if (isset($section['advskew']) && $section['advskew'] <> "") {
            $advskew = intval($section['advskew'])+100;
            if ($advskew > 254) {
                $advskew = 254;
63
            }
64
            $section['advskew'] = $advskew;
65 66 67 68
        }
        $temp['vip'][] = $section;
    }
    return $temp;
Ad Schellevis's avatar
Ad Schellevis committed
69 70
}

71 72 73 74 75 76 77 78
/**
 *  validate remote config version
 * @param string $url backup url
 * @param string $username remote username
 * @param string $password remote password
 * @param string $method xmlrpc method to call
 * @return boolean
 */
79 80 81
function carp_check_version($url, $username, $password, $method = 'opnsense.firmware_version')
{
    global $config;
82

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    $client = new SimpleXMLRPC_Client($url,240);
    $client->setCredentials($username, $password);
    if ($client->query($method)) {
        $remote_version = $client->getResponse();
    } else {
        // propagate error to log
        $error = "An error occurred while attempting XMLRPC sync with username {$username} and {$url} " .  $client->error ;
        log_error($error);
        file_notice("sync_settings", $error, "Settings Sync", "");
        // print communication details on failure
        echo $client->getDetails();
        return false ;
    }

    if (!is_array($remote_version) && trim($remote_version) == "Authentication failed") {
        $error = "An authentication failure occurred while trying to access {$url} ({$method}).";
        log_error($error);
        file_notice("sync_settings", $error, "Settings Sync", "");
101
        return false;
102 103 104 105
    }

    if (!isset($remote_version['config_version']) ||
        $remote_version['config_version'] < $config['version']) {
106 107
        update_filter_reload_status("The other member is on older configuration version. Sync will not be done to prevent problems!");
        log_error("The other member is on older configuration version. Sync will not be done to prevent problems!");
108 109 110 111
        return false;
    } else {
        return true;
    }
Ad Schellevis's avatar
Ad Schellevis committed
112 113
}

114 115 116 117 118 119 120 121 122 123 124 125 126 127
/**
 * traverse config structure and remove (unset) all "nosync" items
 * @param array $cnf_structure pointer to config data
 */
function remove_nosync(&$cnf_structure)
{
    if (!is_array($cnf_structure)) {
        return false;
    } else {
        foreach ($cnf_structure as $cnf_key => &$cnf_data) {
            if (is_array($cnf_data) && isset($cnf_data['nosync'])) {
                unset($cnf_structure[$cnf_key]);
            } else {
                remove_nosync($cnf_data);
128 129 130
            }
        }
    }
131 132 133 134 135 136 137
}

/**
 * find config section by reference (dot notation)
 * for example system.user.0 points to the first enty in <system><user> xml config section
 * @param array $cnf_structure pointer to config data
 * @param string $reference reference pointer (system.user for example)
138
 * @return null
139 140 141 142 143 144 145 146 147 148 149
 */
function copy_conf_section(&$cnf_structure_in, &$cnf_structure_out,  $reference)
{
    $cnf_path = explode('.', $reference);
    $cnf_path_depth = 1;
    foreach ($cnf_path as $cnf_section) {
        if (isset($cnf_structure_in[$cnf_section])) {
            // reference found, create output structure when the data to copy lies deeper.
            // for example wireless.clone.0 would only copy the first wireless clone, returns false on not found
            $cnf_structure_in = &$cnf_structure_in[$cnf_section];
            if ($cnf_path_depth < count($cnf_path)) {
150 151
                if (!isset($cnf_structure_out[$cnf_section])) {
                    $cnf_structure_out[$cnf_section] = array();
152
                }
153
                $cnf_structure_out = &$cnf_structure_out[$cnf_section];
154
            } else {
155
              $cnf_structure_out[$cnf_section] = $cnf_structure_in;
156
            }
157 158 159 160 161 162 163
        } else {
            // if source entry doesn't exist, make sure we copy an empty entry to the remote side
            // otherwise there's no way to know data has been removed
            if (!isset($cnf_structure_out[$cnf_section])) {
                $cnf_structure_out[$cnf_section] = array();
            }
            $cnf_structure_out = &$cnf_structure_out[$cnf_section];
164
        }
165
        $cnf_path_depth++;
166
    }
167 168 169 170 171 172 173 174 175 176 177
}

/**
 * traverse config structure and remove (unset) all "nosync" items
 * @param string $url backup url
 * @param string $username remote username
 * @param string $password remote password
 * @param array $sections sections to transfer
 * @param string $method xmlrpc method to call
 * @return boolean
 */
178 179 180
function carp_sync_xml($url, $username, $password, $sections, $method = 'opnsense.restore_config_section')
{
    global $config;
181 182 183 184 185 186 187 188 189 190 191 192

    update_filter_reload_status("Syncing CARP data to {$url}");

    $transport_data = array();
    foreach ($sections as $section) {
        switch ($section) {
            case 'virtualip':
                // only carp type VIP's may be transfered to the backup host
                $transport_data[$section] = get_vip_config_section();
                break;
            default:
                copy_conf_section($config, $transport_data, $section);
193 194 195
        }
    }

196 197 198 199 200 201 202 203
    // remove items which may not be synced
    remove_nosync($transport_data);

    // ***** post proccessing *****
    // dhcpd, unchanged from legacy code (may need some inspection later)
    if (is_array($transport_data['dhcpd'])) {
        foreach($transport_data['dhcpd'] as $dhcpif => $dhcpifconf) {
            if(isset($dhcpifconf['failover_peerip']) && $dhcpifconf['failover_peerip'] <> "") {
204 205
                $int = guess_interface_from_ip($dhcpifconf['failover_peerip']);
                $intip = find_interface_ip($int);
206
                $transport_data['dhcpd'][$dhcpif]['failover_peerip'] = $intip;
207 208 209 210
            }
        }
    }

211
    // when syncing users, send last used uid/gid over
212
    if (in_array('system.user', $sections)) {
Ad Schellevis's avatar
Ad Schellevis committed
213
        if (!isset($transport_data['system'])) {
214
            $transport_data['system'] = array();
215
        }
216 217
        $transport_data['system']['nextuid'] = $config['system']['nextuid'];
        $transport_data['system']['nextgid'] = $config['system']['nextgid'];
218 219 220 221
    }

    $client = new SimpleXMLRPC_Client($url,240);
    $client->setCredentials($username, $password);
222
    if ($client->query($method, $transport_data)) {
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        $response = $client->getResponse();
    } else {
        // propagate error to log
        $error = "An error occurred while attempting XMLRPC sync with username {$username} and {$url} " .  $client->error ;
        log_error($error);
        file_notice("sync_settings", $error, "Settings Sync", "");
        // print communication details on failure
        echo $client->getDetails();
        return false ;
    }

    if (!is_array($response) && trim($response) == "Authentication failed") {
        $error = "An authentication failure occurred while trying to access {$url} ({$method}).";
        log_error($error);
        file_notice("sync_settings", $error, "Settings Sync", "");
        exit;
    }

    return true;
Ad Schellevis's avatar
Ad Schellevis committed
242 243
}

244
if (file_exists('/var/run/booting')) {
245
    return;
Ad Schellevis's avatar
Ad Schellevis committed
246 247
}

248
if (isset($config['hasync']) && is_array($config['hasync'])) {
249 250 251 252 253 254 255
    update_filter_reload_status("Building high availability information");
    $hasync = $config['hasync'];

    if (empty($hasync['synchronizetoip'])) {
        log_error("Config sync not being done because of missing sync IP (this is normal on secondary systems).");
        exit;
    }
256
    if (is_ipaddrv6($hasync['synchronizetoip'])) {
257 258 259
        $hasync['synchronizetoip'] = "[{$hasync['synchronizetoip']}]";
    }

260 261 262 263 264 265 266 267 268 269
    // determine target url
    if (substr($hasync['synchronizetoip'],0, 4) == 'http') {
        // URL provided
        if (substr($hasync['synchronizetoip'], strlen($hasync['synchronizetoip'])-1, 1) == '/') {
            $synchronizeto = $hasync['synchronizetoip']."xmlrpc.php";
        } else {
            $synchronizeto = $hasync['synchronizetoip']."/xmlrpc.php";
        }
    } elseif (!empty($config['system']['webgui']['protocol'])) {
        // no url provided, assume the backup is using the same settings as our box.
270 271 272 273 274 275 276 277
        $port = $config['system']['webgui']['port'];
        if (!empty($port)) {
            $synchronizeto =  $config['system']['webgui']['protocol'] . '://'.$hasync['synchronizetoip'].':'.$port."/xmlrpc.php";
        } else {
            $synchronizeto =  $config['system']['webgui']['protocol'] . '://'.$hasync['synchronizetoip']."/xmlrpc.php" ;
        }
    }

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
    // map configuration directives to config sections
    $section_cnf = array();
    $section_cnf['synchronizerules'] = 'filter';
    $section_cnf['synchronizenat'] = 'nat';
    $section_cnf['synchronizealiases'] = 'aliases';
    $section_cnf['synchronizedhcpd'] = 'dhcpd';
    $section_cnf['synchronizewol'] = 'wol';
    $section_cnf['synchronizestaticroutes'] = 'staticroutes,gateways';
    $section_cnf['synchronizevirtualip'] = 'virtualip';
    $section_cnf['synchronizelb'] = 'load_balancer';
    $section_cnf['synchronizeipsec'] = 'ipsec';
    $section_cnf['synchronizeopenvpn'] = 'openvpn';
    $section_cnf['synchronizecerts'] = 'cert,ca,crl';
    $section_cnf['synchronizeusers'] = 'system.user,system.group';
    $section_cnf['synchronizeauthservers'] = 'system.authserver';
    $section_cnf['synchronizednsforwarder'] = 'dnsmasq';
    $section_cnf['synchronizeschedules'] = 'schedules';
295 296
    $section_cnf['synchronizeshaper'] = 'OPNsense.TrafficShaper';
    $section_cnf['synchronizecaptiveportal'] = 'OPNsense.captiveportal';
297

298 299 300 301 302 303
    $sections = array();
    foreach ($section_cnf as $cnf_key => $cnf_sections) {
        if (isset($hasync[$cnf_key])) {
            foreach (explode(',', $cnf_sections) as $section) {
                $sections[] = $section;
            }
304 305 306 307 308 309 310 311 312
        }
    }

    if (count($sections) <= 0) {
        log_error("Nothing has been configured to be synched. Skipping....");
        exit;
    }


313
    $username = empty($hasync['username']) ? "root" : $hasync['username'];
314 315 316 317 318 319 320 321 322 323 324 325 326
    if (!carp_check_version($synchronizeto, $username, $hasync['password'])) {
        exit;
    }

    update_filter_reload_status("Signaling CARP reload signal...");
    carp_sync_xml($synchronizeto, $username, $hasync['password'], $sections);

    if (count($argv) <= 1 || $argv[1] != 'restart' ) {
        // only sync data, no reload
        // TODO: config sync probably needs more thinking, but when we always force a reload
        // TODO: the machine tends to get sloppy
        exit;
    }
327
    $client = new SimpleXMLRPC_Client($synchronizeto, 240);
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    $client->setCredentials($username, $hasync['password']);
    if ($client->query("opnsense.filter_configure")) {
        $response = $client->getResponse();
    } else {
        // propagate error to log
        $error = "An error occurred while attempting XMLRPC sync with username {$username} and {$url} " .  $client->error ;
        log_error($error);
        file_notice("sync_settings", $error, "Settings Sync", "");
        // print communication details on failure
        echo $client->getDetails();
        return false ;
    }

    if (!is_array($response) && trim($response) == "Authentication failed") {
        $error = "An authentication failure occurred while trying to access {$url} ({$method}).";
        log_error($error);
        file_notice("sync_settings", $error, "Settings Sync", "");
        exit;
    }

348
    log_error("Filter sync successfully completed with {$synchronizeto}.");
Ad Schellevis's avatar
Ad Schellevis committed
349
}