Esempio n. 1
0
function build()
{
    $unix = new unix();
    $users = new usersMenus();
    $q = new mysql();
    $nohup = $unix->find_program("nohup");
    $hostname_bin = $unix->find_program("hostname");
    $php5 = $unix->LOCATE_PHP5_BIN();
    $sock = new sockets();
    $Myhostname = $sock->GET_INFO("myhostname");
    $oom_kill_allocating_task = $sock->GET_INFO("oom_kill_allocating_task");
    if (!is_numeric($oom_kill_allocating_task)) {
        $oom_kill_allocating_task = 1;
    }
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".pid";
    $pid = @file_get_contents($pidfile);
    $sysctl = $unix->find_program("sysctl");
    $ifconfig = $unix->find_program("ifconfig");
    $GLOBALS["ipbin"] = $unix->find_program("ip");
    $GLOBALS["SCRIPTS_DOWN"] = array();
    if ($unix->process_exists($pid, basename(__FILE__))) {
        event("Building networks already executed PID: {$pid}", __FUNCTION__, __LINE__);
        echo "Starting......: " . date("H:i:s") . " Building networks already executed PID: {$pid}\n";
        die;
    }
    $fqdn = @file_get_contents("/etc/artica-postfix/FULL_HOSTNAME");
    if (is_file("/etc/init.d/hostname.sh")) {
        if (is_file("/usr/sbin/update-rc.d")) {
            shell_exec("/usr/sbin/update-rc.d -f hostname remove >/dev/null 2>&1");
            @unlink("/etc/init.d/hostname.sh");
        }
    }
    if ($oom_kill_allocating_task == 1) {
        echo "Starting......: " . date("H:i:s") . " Kernel oom_kill_allocating_task is enabled\n";
        shell_exec("{$sysctl} -w \"vm.oom_dump_tasks=1\" >/dev/null 2>&1");
        shell_exec("{$sysctl} -w \"vm.oom_kill_allocating_task=1\" >/dev/null 2>&1");
    } else {
        echo "Starting......: " . date("H:i:s") . " Kernel oom_kill_allocating_task is disabled\n";
        shell_exec("{$sysctl} -w \"vm.oom_dump_tasks=0\" >/dev/null 2>&1");
        shell_exec("{$sysctl} -w \"vm.oom_kill_allocating_task=0\" >/dev/null 2>&1");
    }
    if ($GLOBALS["VERBOSE"]) {
        echo "Line:" . __LINE__ . " persistent_net_rules()\n";
    }
    persistent_net_rules();
    if ($GLOBALS["VERBOSE"]) {
        echo "Line:" . __LINE__ . " dev_shm()\n";
    }
    dev_shm();
    $ip = $unix->find_program("ip");
    $echobin = $unix->find_program("echo");
    $logger = $unix->find_program("logger");
    $IPROUTEFOUND = false;
    exec("{$ip} route", $results);
    events("IP route -> " . count($results) . " lines", __FUNCTION__, __LINE__);
    while (list($index, $line) = each($results)) {
        events("IP route -> {$line}", __FUNCTION__, __LINE__);
        if (preg_match("#default via#", $line)) {
            events("IP route found default via -> {$line}", __FUNCTION__, __LINE__);
            $IPROUTEFOUND = true;
        }
    }
    if (!$IPROUTEFOUND) {
        @unlink("/etc/artica-postfix/MEM_INTERFACES");
    }
    if (is_file("/etc/artica-postfix/MEM_INTERFACES")) {
        $MEM_INTERFACES = unserialize(@file_get_contents("/etc/artica-postfix/MEM_INTERFACES"));
    }
    if ($GLOBALS["VERBOSE"]) {
        echo "Line:" . __LINE__ . " MEM_INTERFACES()\n";
    }
    $EXECUTE_CMDS = true;
    if (is_array($MEM_INTERFACES)) {
        $EXECUTE_CMDS = false;
        if ($GLOBALS["VERBOSE"]) {
            echo "Line:" . __LINE__ . " NETWORK_ALL_INTERFACES()\n";
        }
        $array = $unix->NETWORK_ALL_INTERFACES();
        while (list($Interface, $ipaddr) = each($MEM_INTERFACES)) {
            if ($ipaddr == null) {
                continue;
            }
            if ($GLOBALS["VERBOSE"]) {
                echo "Line:" . __LINE__ . " {$Interface} Must be {$ipaddr} -> {$array[$Interface]["IPADDR"]}\n";
            }
            events("{$Interface} Must be {$ipaddr} -> {$array[$Interface]["IPADDR"]}", __FUNCTION__, __LINE__);
            if ($ipaddr != $array[$Interface]["IPADDR"]) {
                events("Must rebuilded....", __FUNCTION__, __LINE__);
                $EXECUTE_CMDS = true;
                break;
            }
        }
    }
    if ($q->mysql_server == "127.0.0.1") {
        if (!$unix->is_socket("/var/run/mysqld/mysqld.sock")) {
            event("/var/run/mysqld/mysqld.sock no such socket", __FUNCTION__, __LINE__);
            echo "Starting......: " . date("H:i:s") . " Building networks MySQL database not available starting MySQL service...\n";
            shell_exec("{$nohup} {$php5} /usr/share/artica-postfix/exec.initd-mysql.php >/dev/null 2>&1 &");
            shell_exec("{$nohup} /etc/init.d/mysql start >/dev/null 2>&1 &");
            sleep(1);
            for ($i = 0; $i < 5; $i++) {
                $q = new mysql();
                if (!is_file("/var/run/mysqld/mysqld.sock")) {
                    echo "Starting......: " . date("H:i:s") . " Building networks waiting MySQL database to start...{$i}/4\n";
                    sleep(1);
                } else {
                    break;
                }
            }
            if (!$unix->is_socket("/var/run/mysqld/mysqld.sock")) {
                event("/var/run/mysqld/mysqld.sock no such socket", __FUNCTION__, __LINE__);
                echo "Starting......: " . date("H:i:s") . " Building networks MySQL database not available...\n";
                die;
            }
        }
    }
    shell_exec("{$nohup} {$php5} /usr/share/artica-postfix/exec.initd-mysql.php >/dev/null 2>&1 &");
    if (!$q->BD_CONNECT()) {
        sleep(1);
        event("Building networks MySQL database not available starting MySQL service", __FUNCTION__, __LINE__);
        echo "Starting......: " . date("H:i:s") . " Building networks MySQL database not available starting MySQL service...\n";
        shell_exec("{$nohup} /etc/init.d/mysql start >/dev/null 2>&1 &");
        for ($i = 0; $i < 5; $i++) {
            $q = new mysql();
            if (!$q->BD_CONNECT()) {
                echo "Starting......: " . date("H:i:s") . " Building networks waiting MySQL database to start...{$i}/4\n";
                sleep(1);
            } else {
                break;
            }
        }
        $q = new mysql();
        if (!$q->BD_CONNECT()) {
            event("Building networks MySQL database not available...", __FUNCTION__, __LINE__);
            echo "Starting......: " . date("H:i:s") . " Building networks MySQL database not available...\n";
            die;
        }
    }
    if (!$q->TABLE_EXISTS("nics", "artica_backup", true)) {
        echo "Starting......: " . date("H:i:s") . " Building networks MySQL table is not yet builded..\n";
        die;
    }
    $GLOBALS["SAVED_INTERFACES"] = array();
    Checkipv6();
    @file_put_contents($pidfile, getmypid());
    echo "Starting......: " . date("H:i:s") . " Building networks checking bridge\n";
    bridges_build();
    echo "Starting......: " . date("H:i:s") . " Building networks checking IPV6\n";
    Checkipv6();
    $nic = new system_nic();
    $datas = $nic->root_build_debian_config();
    echo "Starting......: " . date("H:i:s") . " Building networks Reloading " . count($GLOBALS["SAVED_INTERFACES"]) . " interface(s)\n";
    if (count($GLOBALS["SAVED_INTERFACES"]) == 0) {
        echo "Starting......: " . date("H:i:s") . " Building networks Building Ipv6 virtuals IP...\n";
        Checkipv6Virts();
    }
    $EXECUTE_CMDS = false;
    if (is_file("/etc/init.d/hostname.sh")) {
        if (is_file("/usr/sbin/update-rc.d")) {
            shell_exec("/usr/sbin/update-rc.d -f hostname remove >/dev/null 2>&1");
            @unlink("/etc/init.d/hostname.sh");
        }
    }
    LoadProcNetDev();
    $GLOBALS["SCRIPTS_TOP"][] = "# [" . __LINE__ . "]";
    $GLOBALS["SCRIPTS_TOP"][] = "# [" . __LINE__ . "] *******************************";
    $GLOBALS["SCRIPTS_TOP"][] = "# [" . __LINE__ . "] **** SETTINGS for LOOP BACK ***";
    $GLOBALS["SCRIPTS_TOP"][] = "# [" . __LINE__ . "] *******************************";
    $GLOBALS["SCRIPTS_TOP"][] = "# [" . __LINE__ . "]";
    $ModeProbeAlx = intval($sock->GET_INFO("ModeProbeAlx"));
    $GLOBALS["SCRIPTS_TOP"][] = "# [" . __LINE__ . "] ALX driver: {$ModeProbeAlx}";
    if ($ModeProbeAlx == 1) {
        $modprobe = $unix->find_program("modprobe");
        $GLOBALS["SCRIPTS_TOP"][] = "{$modprobe} alx";
    }
    $GLOBALS["SCRIPTS_TOP"][] = "{$ifconfig} lo 127.0.0.1 up";
    if ($Myhostname != null) {
        $GLOBALS["SCRIPTS_TOP"][] = "{$hostname_bin} \"{$Myhostname}\"";
    }
    $GLOBALS["SCRIPTS_TOP"][] = "# [" . __LINE__ . "]";
    $datas = $nic->networks_disabled();
    $sh = array();
    $sh[] = "#!/bin/sh -e";
    $sh[] = "### BEGIN INIT INFO";
    $sh[] = "# Builded on " . date("Y-m-d H:i:s");
    $sh[] = "# Provides:          artica-ifup";
    $sh[] = "# Required-Start:    mountkernfs \$local_fs";
    $sh[] = "# Required-Stop:     \$local_fs";
    $sh[] = "# Should-Start:\t\tifupdown";
    $sh[] = "# Should-Stop:\t\tifupdown";
    $sh[] = "# Default-Start:     S";
    $sh[] = "# Default-Stop:      0 6";
    $sh[] = "# Short-Description: start and stop the network";
    $sh[] = "# Description:       Artica ifup service Raise network interfaces";
    $sh[] = "### END INIT INFO";
    $sh[] = "case \"\$1\" in";
    $sh[] = "start)";
    $sh[] = "{$logger} \"kernel: [  Artica-Net] Artica network Script executed (start)\" || true";
    $mkdir = $unix->find_program("mkdir");
    $sh[] = "mkdir -p /run/network >/dev/null 2>&1";
    $sh[] = "{$php5} /usr/share/artica-postfix/exec.virtuals-ip-notify.php --start \$2 \$3 || true";
    etc_hosts();
    routes_main();
    ucarp_build(true);
    bridges_build();
    IPTABLES_NETWORK_BRIDGES();
    $sh[] = "{$echobin} \"\" > /var/log/net-start.log";
    $sh[] = "{$echobin} \"  **** Apply Network configuration, please wait... ****\"";
    while (list($index, $line) = each($GLOBALS["SCRIPTS_TOP"])) {
        $line = trim($line);
        if ($line == null) {
            continue;
        }
        if (substr($line, 0, 1) == "#") {
            $sh[] = ScriptInfo($line);
            continue;
        }
        $md = md5($line);
        if (isset($AL[$md])) {
            echo "Starting......: " . date("H:i:s") . " SKIPING `{$line}`\n";
            continue;
        }
        $AL[$md] = true;
        echo "Starting......: " . date("H:i:s") . " `{$line}`\n";
        if (strpos($line, "/etc/hosts") > 0) {
            $sh[] = "{$line}";
            continue;
        }
        if (preg_match("#ifconfig\\s+(.+?)\\s+(.+?)netmask(.+?)\\s+#", $line, $re)) {
            $sh[] = "{$echobin} \"adding {$re[2]}/{$re[3]} in {$re[1]} interface\"";
        }
        $sh[] = "{$echobin} \"{$line}\" >>/var/log/net-start.log 2>&1";
        $sh[] = "{$line} >>/var/log/net-start.log 2>&1 || true";
    }
    while (list($index, $line) = each($GLOBALS["SCRIPTS"])) {
        $line = trim($line);
        if ($line == null) {
            continue;
        }
        if (substr($line, 0, 1) == "#") {
            $sh[] = ScriptInfo($line);
            continue;
        }
        if (preg_match("#^OUTPUT\\s+(.+)#", $line, $re)) {
            $line = str_replace('"', "'", $line);
            $sh[] = "{$echobin} \"{$re[1]}\"";
            continue;
        }
        $md = md5($line);
        if (isset($AL[$md])) {
            echo "Starting......: " . date("H:i:s") . " SKIPING `{$line}`\n";
            continue;
        }
        $AL[$md] = true;
        echo "Starting......: " . date("H:i:s") . " `{$line}`\n";
        if (strpos($line, "/etc/hosts") > 0) {
            $sh[] = "{$line}";
            continue;
        }
        if (preg_match("#ifconfig\\s+(.+?)\\s+(.+?)netmask(.+?)\\s+#", $line, $re)) {
            $sh[] = "{$echobin} \"adding {$re[2]}/{$re[3]} in {$re[1]} interface\"";
        }
        if (strpos('echo "', $line) == 0) {
            $sh[] = "{$echobin} \"{$line}\" >>/var/log/net-start.log 2>&1";
        }
        $sh[] = "{$line} >>/var/log/net-start.log 2>&1 || true";
    }
    if (count($GLOBALS["SCRIPTS_ROUTES"]) > 0) {
        $GLOBALS["START_ROUTES"][] = "{$echobin} \"Apply network routes, please wait...\"";
        $sh[] = "";
        $sh[] = "# [" . __LINE__ . "]";
        $sh[] = "# [" . __LINE__ . "] *******************************";
        $sh[] = "# [" . __LINE__ . "] ****     NETWORK ROUTES    ****";
        $sh[] = "# [" . __LINE__ . "] *******************************";
        $sh[] = "# [" . __LINE__ . "]";
        while (list($index, $line) = each($GLOBALS["SCRIPTS_ROUTES"])) {
            $line = trim($line);
            if ($line == null) {
                continue;
            }
            if (substr($line, 0, 1) == "#") {
                $ScriptInfo = ScriptInfo($line);
                $sh[] = $ScriptInfo;
                $GLOBALS["START_ROUTES"][] = $ScriptInfo;
                continue;
            }
            $md = md5($line);
            if (isset($AL[$md])) {
                if (!preg_match("#^force#", $line)) {
                    echo "Starting......: " . date("H:i:s") . " SKIPING `{$line}`\n";
                    continue;
                }
            }
            if (preg_match("#^force:(.+)#", $line, $re)) {
                $line = $re[1];
                $md = md5($line);
            }
            $AL[$md] = true;
            if (preg_match("#ip route add (.+?)\\s+.*?src\\s+(.+)#", $line, $re)) {
                $GLOBALS["START_ROUTES"][] = "{$echobin} \"Create route for network {$re[1]} for local address {$re[2]}\"";
                $sh[] = "{$echobin} \"Create route for network {$re[1]} for local address {$re[2]}\"";
            }
            if (preg_match("#ip route add (.+?)\\s+via(.+?)\\s+src\\s+([0-9\\.]+)#", $line, $re)) {
                $GLOBALS["START_ROUTES"][] = "{$echobin} \"Create route for network {$re[1]} using gateway {$re[2]} for local address {$re[3]}\"";
                $sh[] = "{$echobin} \"Create route for network {$re[1]} using gateway {$re[2]} for local address {$re[3]}\"";
            }
            $GLOBALS["START_ROUTES"][] = "{$echobin} \"{$line}\" >>/var/log/net-start.log 2>&1";
            $sh[] = "{$echobin} \"{$line}\" >>/var/log/net-start.log 2>&1";
            if (preg_match("#\\/echo\\s+#", $line)) {
                $sh[] = $line;
                continue;
            }
            $sh[] = "{$line} >>/var/log/net-start.log 2>&1 || true";
            $GLOBALS["START_ROUTES"][] = "{$line} >>/var/log/net-start.log 2>&1 || true";
        }
    }
    $sh[] = "if [ -x /etc/init.d/artica-ifup-content.sh ] ; then";
    $sh[] = "\t/etc/init.d/artica-ifup-content.sh || true";
    $sh[] = "fi";
    $sh[] = nics_vde_build();
    $EnablePDNS = $sock->GET_INFO("EnablePDNS");
    if (!is_numeric($EnablePDNS)) {
        $EnablePDNS = 0;
    }
    $unix = new unix();
    $squid = $unix->LOCATE_SQUID_BIN();
    $ip = $unix->find_program("ip");
    $echo = $unix->find_program("echo");
    $nohup = $unix->find_program("nohup");
    $monit = $unix->find_program("monit");
    $ifconfig = $unix->find_program("ifconfig");
    $php = $unix->LOCATE_PHP5_BIN();
    if (is_file($squid)) {
        $sh[] = "# [" . __LINE__ . "] Reloading squid";
        $sh[] = "{$echo} \"Reloading squid ( if exists )\"";
        $sh[] = "{$nohup} {$php} /usr/share/artica-postfix/exec.squid.php --kreconfigure 2>&1 >>/var/log/net-start.log 2>&1 &";
    }
    $sh[] = "# [" . __LINE__ . "] Flushing ARP cache";
    $sh[] = "{$echo} \"Flushing ARP cache...\"";
    $sh[] = "ip -s -s neigh flush all >>/var/log/net-start.log 2>&1 || true";
    $sh[] = "# [" . __LINE__ . "] Tune the kernel";
    $sh[] = "{$echo} \"Tuning the kernel...\"";
    $sh[] = "{$php5} /usr/share/artica-postfix/exec.sysctl.php --build >>/var/log/net-start.log 2>&1 || true";
    $sh[] = "if [ -x /bin/artica-firewall.sh ] ; then";
    $sh[] = "\t/bin/artica-firewall.sh || true";
    $sh[] = "fi";
    if (is_file("/etc/init.d/ssh")) {
        $sh[] = "# [" . __LINE__ . "] Starting sshd";
        $sh[] = "{$echo} \"Starting sshd\"";
        $sh[] = "/etc/init.d/ssh start 2>&1 || true";
    }
    $sh[] = "# [" . __LINE__ . "] Starting FrameWork";
    $sh[] = "{$echo} \"Starting FrameWork\"";
    $sh[] = "{$nohup} {$php5} /usr/share/artica-postfix/exec.framework.php --start >/dev/null 2>&1 &";
    $sh[] = "# [" . __LINE__ . "] Starting Meta Server Client";
    $sh[] = "{$echo} \"Starting FrameWork\"";
    $sh[] = "{$nohup} {$php5} /usr/share/artica-postfix/exec.artica-meta-client.php --ping --force >/dev/null 2>&1 &";
    if ($EnablePDNS == 1) {
        $sh[] = "# [" . __LINE__ . "] Reloading PowerDNS...";
        $sh[] = "{$echo} \"Reloading PowerDNS\"";
        $sh[] = "{$php5} /usr/share/artica-postfix/exec.pdns.php --reload 2>&1 || true";
    }
    if (is_file($monit)) {
        $sh[] = "# [" . __LINE__ . "] Starting Monit in background";
        $sh[] = "{$echo} \"Starting Monit in background\"";
        $sh[] = "{$nohup} {$monit} -c /etc/monit/monitrc -p /var/run/monit/monit.pid -s /var/run/monit/monit.state >/dev/null 2>&1 &";
    }
    $mount = $unix->find_program("mount");
    if (is_file($mount)) {
        $sh[] = "# [" . __LINE__ . "] Mount all system after network set";
        $sh[] = "{$echo} \"Starting mount in background\"";
        $sh[] = "{$nohup} {$mount} -a >/dev/null 2>&1 &";
    }
    $sh[] = "# [" . __LINE__ . "] Reloading DHCPD (if exists)";
    $sh[] = "{$echo} \"Reloading DHCP server ( if exists )\"";
    $sh[] = "{$php5} /usr/share/artica-postfix/exec.dhcpd.compile.php --reload-if-run 2>&1 || true";
    $sh[] = "{$echo} \"  ****      Apply Network configuration, done      ****\"";
    $sh[] = ";;";
    $sh[] = "  stop)";
    $sh[] = "{$logger} \"* * * * * * * * * * * * * * SUSPECTED STOPPED SERVER !!! * * * * * * * * * * * * * *\" || true";
    $sh[] = "{$logger} \"kernel: [  Artica-Net] Artica network Script executed (stop)\" || true";
    if (is_array($GLOBALS["SCRIPTS_DOWN"])) {
        while (list($index, $line) = each($GLOBALS["SCRIPTS_DOWN"])) {
            if (substr($line, 0, 1) == "#") {
                $sh[] = ScriptInfo($line);
                continue;
            }
            $sh[] = "{$line} >>/var/log/net-stop.log 2>&1 || true";
        }
    }
    $php = $unix->LOCATE_PHP5_BIN();
    $sh[] = ";;";
    $sh[] = "reconfigure)";
    $sh[] = "{$logger} \"kernel: [  Artica-Net] Artica network Script Executed (reconfigure)\" || true";
    $sh[] = "{$php} " . __FILE__ . " --build --force \$2 \$3";
    $sh[] = "/etc/init.d/artica-ifup start";
    $sh[] = ";;";
    $sh[] = "routes)";
    $sh[] = "{$logger} \"kernel: [  Artica-Net] Artica network Script Executed (routes)\" || true";
    $sh[] = "# Array of " . count($GLOBALS["START_ROUTES"]);
    $sh[] = "{$echobin} \"Flushing routes tables...\"";
    $sh[] = "{$GLOBALS["ipbin"]} route flush table all";
    $sh[] = "{$echobin} \"{$ifconfig} lo 127.0.0.1 down\"";
    $sh[] = "{$ifconfig} lo 127.0.0.1 down || true";
    $sh[] = "{$echobin} \"{$ifconfig} lo 127.0.0.1 up\"";
    $sh[] = "{$ifconfig} lo 127.0.0.1 up || true";
    $sh[] = "{$echobin} \"Apply routes to the system\"";
    $sh[] = "{$echobin} \"Running routes\" > /var/log/net-start.log 2>&1";
    $sh[] = @implode("\n", $GLOBALS["START_ROUTES"]);
    $sh[] = "{$echobin} \"Routes applied to the system\"";
    $sh[] = ";;";
    $sh[] = "*)";
    $sh[] = "{$logger} \"kernel: [  Artica-Net] Artica network Script executed (unknown)\" || true";
    $sh[] = " echo \"Usage: \$0 {start or reconfigure only}\"";
    $sh[] = "exit 1";
    $sh[] = ";;";
    $sh[] = "esac";
    $sh[] = "exit 0\n";
    @file_put_contents("/etc/init.d/artica-ifup", @implode("\n", $sh));
    @chmod("/etc/init.d/artica-ifup", 0755);
    if (is_file('/usr/sbin/update-rc.d')) {
        shell_exec("/usr/sbin/update-rc.d -f artica-ifup defaults >/dev/null 2>&1");
        if (is_file('/etc/init.d/networking')) {
            shell_exec("/usr/sbin/update-rc.d -f networking disable  >/dev/null 2>&1");
            @copy("/etc/init.d/networking", "/etc/init.d/networking.back");
            @unlink("/etc/init.d/networking");
        }
    }
    if (is_file('/sbin/chkconfig')) {
        shell_exec("/sbin/chkconfig --add artica-ifup >/dev/null 2>&1");
        shell_exec("/sbin/chkconfig --level 1234 artica-ifup on >/dev/null 2>&1");
    }
    $inter[] = "# This file describes the network interfaces available on your system";
    $inter[] = "## and how to activate them. For more information, see interfaces(5).";
    $inter[] = "";
    $inter[] = "## The loopback network interface";
    $inter[] = "auto lo";
    $inter[] = "iface lo inet loopback";
    $inter[] = "";
    $inter[] = "";
    if (is_file("/etc/network/interfaces")) {
        @file_put_contents("/etc/network/interfaces", @implode("\n", $inter));
    }
    squid_admin_mysql(1, "Network script was rebuilded", null, __FILE__, __LINE__);
    echo "Starting......: " . date("H:i:s") . " Building FireWall rules.\n";
    system("{$php5} /usr/share/artica-postfix/exec.firehol.php --build");
    echo "Starting......: " . date("H:i:s") . " done...\n";
}
function ACTION_NETWORK()
{
    $unix = new unix();
    $clear = $unix->find_program("clear");
    if (is_file($clear)) {
        system("{$clear}");
    }
    $users = new usersMenus();
    $q = new mysql();
    if (!$q->BD_CONNECT(true)) {
        echo "There is an issue while connecting to MySQL\n{$q->mysql_error}\nPress Key to exit.\n";
        $line = fgets(STDIN);
        return;
    }
    $DEFAULT = null;
    $net = new networking();
    $interfaces = $net->Local_interfaces();
    unset($interfaces["lo"]);
    if (isset($interfaces["eth0"])) {
        $DEFAULT = "eth0";
    }
    while (list($num, $letter) = each($interfaces)) {
        $int[] = "\"{$num}\"";
    }
    if ($DEFAULT == null) {
        $DEFAULT = $int[0];
    }
    $q->BuildTables();
    echo "This wizard will help to configure network.\n";
    echo "Press q letter to exit or any key to continue:";
    $answer = trim(strtolower(fgets(STDIN)));
    if ($answer == "q") {
        return;
    }
    if (is_file($clear)) {
        system("{$clear}");
    }
    echo "Give here the interface name of the network interface\n";
    echo "you need to setup.\n\n";
    echo "Should be one of :" . @implode(", ", $int) . "\n";
    echo "Default: [{$DEFAULT}]\n";
    $NIC = trim(strtolower(fgets(STDIN)));
    if ($NIC == null) {
        $NIC = $DEFAULT;
    }
    if (!preg_match("#([a-z])([0-9+)\$#", $NIC)) {
        $NIC = $DEFAULT;
    }
    $ETH_IP = trim(ASK_ETH_IP($NIC));
    $GATEWAY = trim(ASK_GATEWAY($NIC));
    $NETMASK = trim(ASK_NETMASK($NIC));
    $DNS = trim(ASK_DNS1($NIC));
    if (is_file($clear)) {
        system("{$clear}");
    }
    echo "Your Settings:\n";
    echo "Interface.........: \"{$NIC}\"\n";
    echo "IP address........: \"{$ETH_IP}\"\n";
    echo "Gateway...........: \"{$GATEWAY}\"\n";
    echo "Netmask...........: \"{$NETMASK}\"\n";
    echo "DNS server 1......: \"{$DNS}\"\n";
    echo "\n";
    //ini_set('display_errors', 1);ini_set('error_reporting', E_ALL);ini_set('error_prepend_string',null);ini_set('error_append_string',null);
    echo "If your are agree with these settings\n";
    echo "Press any key to apply settings or press \"q\" to return to menu.\n";
    $answer = trim(strtolower(fgets(STDIN)));
    if ($answer == "q") {
        return;
    }
    echo "5%] Please Wait, saving configuration...\n";
    $nics = new system_nic($NIC);
    $nics->eth = $NIC;
    $nics->IPADDR = $ETH_IP;
    $nics->NETMASK = $NETMASK;
    $nics->GATEWAY = $GATEWAY;
    $nics->DNS1 = $DNS;
    $nics->dhcp = 0;
    $nics->metric = 1;
    $nics->defaultroute = 1;
    $nics->enabled = 1;
    echo "7%] Please Wait, saving Networks parameters to MySQL DB...\n";
    if (!$nics->SaveNic()) {
        echo "There is an issue while saving your settings\n";
        echo "Press any key to exit.\n";
        $answer = trim(strtolower(fgets(STDIN)));
        return;
    }
    echo "10%] Please Wait, building configuration....\n";
    $php = $unix->LOCATE_PHP5_BIN();
    $nohup = $unix->find_program("nohup");
    $php5 = $php;
    shell_exec2("{$php5} " . dirname(__FILE__) . " /exec.virtuals-ip.php --build --force >/dev/null 2>&1");
    echo "20%] Please Wait, apply network configuration....\n";
    shell_exec2("{$php5} /usr/share/artica-postfix/exec.initslapd.php");
    shell_exec2("/etc/init.d/artica-ifup start");
    echo "30%] Please Wait, restarting services....\n";
    $unix->THREAD_COMMAND_SET("{$php5} /usr/share/artica-postfix/exec.postfix.maincf.php --reconfigure");
    $unix->THREAD_COMMAND_SET("/usr/share/artica-postfix/bin/artica-install --reconfigure-cyrus");
    shell_exec2("{$nohup} /etc/init.d/artica-status reload >/dev/null 2>&1 &");
    shell_exec2("{$nohup} /etc/init.d/nginx restart >/dev/null 2>&1 &");
    shell_exec2("{$nohup} /etc/init.d/monit restart >/dev/null 2>&1 &");
    echo "30%] Please Wait, Changing IP address to {$NIC}....\n";
    $ifconfig = $unix->find_program("ifconfig");
    shell_exec2("{$ifconfig} {$NIC} down");
    shell_exec2("{$ifconfig} {$NIC} {$ETH_IP} netmask {$NETMASK} up");
    shell_exec2("/bin/ip route add 127.0.0.1 dev lo");
    if ($GATEWAY != "0.0.0.0") {
        echo "31%] Please Wait, Define default gateway to {$GATEWAY}....\n";
        shell_exec2("/sbin/route add {$GATEWAY} dev {$NIC}");
        $route = $unix->find_program("route");
        shell_exec("{$route} add -net 0.0.0.0 gw {$GATEWAY} dev {$NIC} metric 1");
    }
    echo "80%] Please Wait, Changing DNS to {$DNS}....\n";
    echo "81%] Please Wait, Loading DNS library\n";
    $GLOBALS["PROGRESS"] = true;
    $resolv = new resolv_conf();
    echo "92%] Set DNS1 to {$DNS}\n";
    $resolv->MainArray["DNS1"] = $DNS;
    $resolv->output = true;
    echo "93%] Saving config\n";
    $resolvDatas = $resolv->build();
    echo "94%] Saving /etc/resolv.conf\n";
    @file_put_contents("/etc/resolv.conf", $resolvDatas);
    echo "95%] Restarting Web Console\n";
    shell_exec2("{$nohup} /etc/init.d/artica-webconsole restart");
    echo "100%] Configuration done.\n";
    echo "Press any key to return to menu.";
    $answer = trim(strtolower(fgets(STDIN)));
    MAIN_MENU();
}
Esempio n. 3
0
function start($nopid = false)
{
    $users = new usersMenus();
    $unix = new unix();
    $ettercap_bin = $unix->find_program("ettercap");
    if (!$users->ETTERCAP_INSTALLED) {
        echo "ArpSpoofing.........: [START]: Ettercap, not installed...\n";
        return;
    }
    if (!is_file($ettercap_bin)) {
        echo "ArpSpoofing.........: [START]: Ettercap, not such binary...\n";
        return;
    }
    $sock = new sockets();
    $ArpSpoofEnabled = $sock->GET_INFO("ArpSpoofEnabled");
    if (!is_numeric($ArpSpoofEnabled)) {
        $ArpSpoofEnabled = 0;
    }
    if (!$nopid) {
        $me = basename(__FILE__);
        $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".pid";
        $pid = $unix->get_pid_from_file($pidfile);
        if ($unix->process_exists($pid, $me)) {
            $time = $unix->PROCCESS_TIME_MIN($pid);
            echo "ArpSpoofing.........: [START]: Ettercap, Already start instance executed PID {$pid} since {$time}Mn...\n";
            return;
        }
        @file_put_contents($pidfile, getmypid());
    }
    if ($ArpSpoofEnabled == 0) {
        echo "ArpSpoofing.........: [START]: Ettercap, not enabled\n";
        stop(true);
    }
    $nohup = $unix->find_program("nohup");
    $q = new mysql();
    if (!$q->BD_CONNECT()) {
        echo "ArpSpoofing.........: [START]: unable to connect to MySQL database...\n";
        return;
    }
    if (!$unix->SystemUserExists("nobody")) {
        echo "ArpSpoofing.........: [START]: Creating nobody user...\n";
        $unix->CreateUnixUser("nobody", "nogroup");
    }
    if (!$unix->SystemGroupExists("nogroup")) {
        $unix->SystemCreateGroup("nogroup");
        $unix->CreateUnixUser("nobody", "nogroup");
    }
    $uid = $unix->SystemUserGetuid("nobody");
    $guid = $unix->SystemGroupUid("nogroup");
    init_debian();
    $sql = "SELECT * FROM arpspoof_rules WHERE enabled=1";
    $results = $q->QUERY_SQL($sql, "artica_backup");
    while ($ligne = mysql_fetch_assoc($results)) {
        $rulename = $ligne["rulename"];
        $pid = get_rule_pid($ligne["ID"]);
        if ($unix->process_exists($pid)) {
            echo "ArpSpoofing.........: [START]: `{$rulename}` already running pid {$pid}\n";
            continue;
        }
        $sources = getobjects($ligne["ID"]);
        $gateway = $ligne["gateway"];
        if ($sources == null) {
            echo "ArpSpoofing.........: [START]: `{$rulename}` no item set...\n";
            continue;
        }
        if ($sources == "all") {
            $sources = null;
        }
        $f = array();
        $f[] = "[privs]";
        $f[] = "ec_uid = {$uid} # nobody is the default";
        $f[] = "ec_gid = {$guid} # nobody is the default";
        $f[] = "[mitm]";
        $f[] = "arp_storm_delay = 10";
        $f[] = "arp_poison_warm_up = 1";
        $f[] = "arp_poison_delay = 10";
        $f[] = "arp_poison_equal_mac= 1";
        $f[] = "arp_poison_reply=1";
        $f[] = "arp_poison_icmp = 1";
        $f[] = "dhcp_lease_time = 600";
        $f[] = "port_steal_delay = 10         # milliseconds";
        $f[] = "port_steal_send_delay = 2000  # microseconds";
        $f[] = "[connections]";
        $f[] = "connection_timeout = 300 # seconds";
        $f[] = "connection_idle = 5 # seconds";
        $f[] = "connection_buffer = 10000 # bytes";
        $f[] = "connect_timeout = 5 # seconds";
        $f[] = "";
        $f[] = "[stats]";
        $f[] = "sampling_rate = 50 # number of packets";
        $f[] = "";
        $f[] = "[misc]";
        $f[] = "close_on_eof = 1 # boolean value";
        $f[] = "store_profiles = 1 # 0 = disabled; 1 = all; 2 = local; 3 = remote";
        $f[] = "aggressive_dissectors = 1 # boolean value";
        $f[] = "skip_forwarded_pcks = 1 # boolean value";
        $f[] = "checksum_check = 0 # boolean value";
        $f[] = "checksum_warning = 0 # boolean value (valid only if checksum_check is 1)";
        $f[] = "";
        @mkdir("/etc/ettercap", 0755, true);
        @file_put_contents("/etc/ettercap/{$ligne["ID"]}.conf", @implode("\n", $f));
        $unix->chown_func("nobody", "nogroup", '/etc/ettercap/*');
        echo "ArpSpoofing.........: [START]: `{$rulename}`:uid:{$uid}...\n";
        $cmdline = "{$nohup} {$ettercap_bin} --daemon --superquiet --config /etc/ettercap/{$ligne["ID"]}.conf --log-msg /etc/ettercap/{$ligne["ID"]}.log --iface {$ligne["iface"]} --only-mitm --mitm arp:remote /{$sources}/ /{$gateway}/ >/dev/null 2>&1 &";
        shell_exec($cmdline);
        for ($i = 0; $i < 6; $i++) {
            $pid = get_rule_pid($ligne["ID"]);
            if ($unix->process_exists($pid)) {
                echo "ArpSpoofing.........: [START]: `{$rulename}` success running pid {$pid}\n";
                break;
            }
            echo "ArpSpoofing.........: [START]: `{$rulename}` waiting to start... {$i}/5\n";
            sleep(1);
        }
        $pid = get_rule_pid($ligne["ID"]);
        if (!$unix->process_exists($pid)) {
            echo "ArpSpoofing.........: [START]: `{$rulename}` failed with commandline:`{$cmdline}`\n";
        }
    }
    echo "ArpSpoofing.........: [START]: done...\n";
}
Esempio n. 4
0
function system_admin_events_checks($nopid = false)
{
    $f = array();
    $unix = new unix();
    $TRW = array();
    if ($nopid) {
        $unix = new unix();
        $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
        $pid = @file_get_contents($pidfile);
        if ($unix->process_exists($pid)) {
            writelogs("Already running pid {$pid}", __FUNCTION__, __FILE__, __LINE__);
            return;
        }
        $t = 0;
        @file_put_contents($pidfile, getmypid());
    }
    // removed : foreach (glob("{$GLOBALS["ARTICALOGDIR"]}/system_admin_events/*") as $filename) {
    $BaseWorkDir = "{$GLOBALS["ARTICALOGDIR"]}/system_admin_events";
    $FILES = $unix->COUNT_FILES($BaseWorkDir);
    if ($FILES > 5000) {
        if (!($handle = opendir($BaseWorkDir))) {
            echo "Failed open {$BaseWorkDir}\n";
            return;
        }
        while (false !== ($filename = readdir($handle))) {
            if ($filename == ".") {
                continue;
            }
            if ($filename == "..") {
                continue;
            }
            $targetFile = "{$BaseWorkDir}/{$filename}";
            if (is_dir($targetFile)) {
                continue;
            }
            @unlink($targetFile);
        }
        return;
    }
    if (!($handle = opendir($BaseWorkDir))) {
        echo "Failed open {$BaseWorkDir}\n";
        return;
    }
    $q = new mysql();
    if (!$q->BD_CONNECT(true, "called by " . basename(__FILE__) . " (" . __FUNCTION__ . ") line: " . __LINE__)) {
        return;
    }
    $sql = "CREATE TABLE IF NOT EXISTS `artica_events`.`system_admin_events` (\n\t`zDate` TIMESTAMP NOT NULL ,\n\t`description` MEDIUMTEXT NOT NULL ,\n\t`function` VARCHAR( 60 ) NOT NULL ,\n\t`filename` VARCHAR( 50 ) NOT NULL ,\n\t`line` INT( 10 ) NOT NULL ,\n\t`category` VARCHAR( 50 ) NOT NULL ,\n\t`TASKID` INT(10) NOT NULL,\n\tKEY  `zDate` ( `zDate`),\n\tKEY `function` (`function`),\n\tKEY `filename` (`filename`),\n\tKEY `line` (`line`),\n\tKEY `TASKID` (`TASKID`),\n\tKEY `category` (`category`)\n\t) ENGINE=MYISAM;";
    $q->QUERY_SQL($sql, "artica_events");
    if (!$q->ok) {
        return;
    }
    $prefix = "INSERT IGNORE INTO system_admin_events (`zDate`,`function`,`filename`,`line`,`description`,`category`,`TASKID`) VALUES ";
    while (false !== ($filename = readdir($handle))) {
        if ($filename == ".") {
            continue;
        }
        if ($filename == "..") {
            continue;
        }
        $targetFile = "{$BaseWorkDir}/{$filename}";
        $array = unserialize(@file_get_contents($targetFile));
        @unlink($targetFile);
        if (!is_array($array)) {
            $array["text"] = basename($filename) . " is not an array, skip event \n" . @file_get_contents($targetFile);
            $array["zdate"] = date('Y-m-d H:i:s');
            $array["pid"] = getmypid();
            $array["function"] = __FUNCTION__;
            $array["category"] = "parser";
            $array["file"] = basename(__FILE__);
            $array["line"] = __LINE__;
        }
        if (!is_numeric($array["TASKID"])) {
            $array["TASKID"] = 0;
        }
        $tableName = "Taskev{$array["TASKID"]}";
        $chkTables[$tableName] = true;
        WriteMyLogs(substr($array["text"], 0, 128), __FUNCTION__, __FILE__, __LINE__);
        while (list($key, $val) = each($array)) {
            $val = mysql_escape_string2($val);
            $array[$key] = str_replace("'", "`", $val);
        }
        $rom2 = "('{$array["zdate"]}','{$array["function"]}','{$array["file"]}','{$array["line"]}','{$array["text"]}','{$array["category"]}','{$array["TASKID"]}')";
        $rom = "('{$array["zdate"]}','{$array["function"]}','{$array["file"]}','{$array["line"]}','{$array["text"]}','{$array["category"]}')";
        $TRW[] = $rom2;
        $f[$tableName][] = $rom;
        if (count($f[$tableName]) > 1500) {
            system_admin_events_inject($f, true);
            $f = array();
        }
        if (count($f) > 10) {
            system_admin_events_inject($f, true);
            $f = array();
        }
        @unlink($targetFile);
    }
    $q = new mysql();
    if (count($TRW) > 0) {
        $q->QUERY_SQL("{$prefix}" . @implode(",", $TRW), "artica_events");
    }
    system_admin_events_inject($f);
    loadavg_logs();
    if ($GLOBALS["VERBOSE"]) {
        echo __FUNCTION__ . "::" . __LINE__ . " ->END\n";
    }
}
Esempio n. 5
0
function sys_mem()
{
    $f = array();
    $q = new mysql();
    if (!$q->TABLE_EXISTS('sys_mem', 'artica_events')) {
        $sql = "CREATE TABLE IF NOT EXISTS `sys_mem` (\n\t\t\t \t`zDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\t\t\tmemory_used BIGINT UNSIGNED,\n\t\t\t\tPRIMARY KEY (`zDate`),\n\t\t\t\tKEY `memory_used` (`memory_used`)\n\t\t\t) ENGINE=MYISAM;\n\t\t\t";
        $q->QUERY_SQL($sql, 'artica_events');
        if (!$q->ok) {
            return;
        }
    }
    if (!$q->BD_CONNECT()) {
        return;
    }
    $prefix = "INSERT IGNORE INTO sys_mem (zDate,memory_used) VALUES ";
    if (system_is_overloaded()) {
        return;
    }
    $DirPath = "{$GLOBALS["ARTICALOGDIR"]}/sys_mem";
    if (!is_dir($DirPath)) {
        @mkdir($DirPath, 0755, true);
    }
    if (!($handle = opendir($DirPath))) {
        return;
    }
    while (false !== ($file = readdir($handle))) {
        if ($file == ".") {
            continue;
        }
        if ($file == "..") {
            continue;
        }
        $filename = "{$DirPath}/{$file}";
        if (is_dir($filename)) {
            continue;
        }
        $time = basename($filename);
        $zdate = date("Y-m-d H:i:s", $time);
        $load = trim(@file_get_contents($filename));
        $f[] = "('{$zdate}','{$load}')";
        @unlink($filename);
    }
    if (count($f) > 0) {
        $sql = $prefix . @implode(",", $f);
        $q->QUERY_SQL($sql, "artica_events");
    }
}