Beispiel #1
0
    def del_l2tp_ipsec_user(self, user, obj):
        userfound = False
        password = obj['password']
        userentry = "%s \* %s \*"%(user,password)

        logging.debug("Deleting the user %s " % user)
        file = CsFile(self.PPP_CHAP)
        file.deleteLine(userentry)
        file.commit()

        if not os.path.exists('/var/run/pppd2.tdb'):
            return

        logging.debug("kiing the PPPD process for the user %s " % user)

        fileContents = CsHelper.execute("tdbdump /var/run/pppd2.tdb")
        print fileContents

        for line in fileContents:
            if user in line:
                contentlist = line.split(';')
                for str in contentlist:
                    print 'in del_l2tp str = '+ str
                    pppd = str.split('=')[0]
                    if pppd == 'PPPD_PID':
                        pid = str.split('=')[1]
                        if pid:
                            logging.debug("killing process %s" %pid)
                            CsHelper.execute('kill -9 %s' % pid)
Beispiel #2
0
    def process(self):
        self.confips = []
        # collect a list of configured vpns
        for file in os.listdir(self.VPNCONFDIR):
            m = re.search("^ipsec.vpn-(.*).conf", file)
            if m:
                self.confips.append(m.group(1))

        for vpn in self.dbag:
            if vpn == "id":
                continue

            local_ip = self.dbag[vpn]['local_public_ip']
            dev = CsHelper.get_device(local_ip)

            if dev == "":
                logging.error("Request for ipsec to %s not possible because ip is not configured", local_ip)
                continue

            CsHelper.start_if_stopped("ipsec")
            self.configure_iptables(dev, self.dbag[vpn])
            self.configure_ipsec(self.dbag[vpn])

        # Delete vpns that are no longer in the configuration
        for ip in self.confips:
            self.deletevpn(ip)
Beispiel #3
0
    def process(self):
        self.confips = []
        # collect a list of configured vpns
        for file in os.listdir(self.VPNCONFDIR):
            m = re.search("^ipsec.vpn-(.*).conf", file)
            if m:
                self.confips.append(m.group(1))

        for vpn in self.dbag:
            if vpn == "id":
                continue

            local_ip = self.dbag[vpn]['local_public_ip']
            dev = CsHelper.get_device(local_ip)

            if dev == "":
                logging.error(
                    "Request for ipsec to %s not possible because ip is not configured",
                    local_ip)
                continue

            CsHelper.start_if_stopped("ipsec")
            self.configure_iptables(dev, self.dbag[vpn])
            self.configure_ipsec(self.dbag[vpn])

        # Delete vpns that are no longer in the configuration
        for ip in self.confips:
            self.deletevpn(ip)
Beispiel #4
0
 def flushAllowAllEgressRules(self):
     logging.debug("Flush allow 'all' egress firewall rule")
     # Ensure that FW_EGRESS_RULES chain exists
     CsHelper.execute("iptables-save | grep '^:FW_EGRESS_RULES' || iptables -t filter -N FW_EGRESS_RULES")
     CsHelper.execute(
         "iptables-save | grep '^-A FW_EGRESS_RULES -j ACCEPT$' | sed 's/^-A/iptables -t filter -D/g' | bash"
     )
Beispiel #5
0
    def del_l2tp_ipsec_user(self, user, obj):
        userfound = False
        password = obj['password']
        userentry = "%s \* %s \*" % (user, password)

        logging.debug("Deleting the user %s " % user)
        file = CsFile(self.PPP_CHAP)
        file.deleteLine(userentry)
        file.commit()

        if not os.path.exists('/var/run/pppd2.tdb'):
            return

        logging.debug("kiing the PPPD process for the user %s " % user)

        fileContents = CsHelper.execute("tdbdump /var/run/pppd2.tdb")
        print fileContents

        for line in fileContents:
            if user in line:
                contentlist = line.split(';')
                for str in contentlist:
                    print 'in del_l2tp str = ' + str
                    pppd = str.split('=')[0]
                    if pppd == 'PPPD_PID':
                        pid = str.split('=')[1]
                        if pid:
                            logging.debug("killing process %s" % pid)
                            CsHelper.execute('kill -9 %s' % pid)
Beispiel #6
0
 def flushAllowAllEgressRules(self):
     logging.debug("Flush allow 'all' egress firewall rule")
     # Ensure that FW_EGRESS_RULES chain exists
     CsHelper.execute("iptables-save | grep '^:FW_EGRESS_RULES' || iptables -t filter -N FW_EGRESS_RULES")
     CsHelper.execute("iptables-save | grep '^-A FW_EGRESS_RULES -j ACCEPT$' | sed 's/^-A/iptables -t filter -D/g' | bash")
     CsHelper.execute("iptables -F FW_EGRESS_RULES")
     CsHelper.execute("ipset -L | grep Name:  | awk {'print $2'} | ipset flush")
     CsHelper.execute("ipset -L | grep Name:  | awk {'print $2'} | ipset destroy")
Beispiel #7
0
    def __htaccess(self, ip, folder, file):
        entry = "RewriteRule ^" + file + "$  ../" + folder + "/%{REMOTE_ADDR}/" + file + " [L,NC,QSA]"
        htaccessFolder = "/var/www/html/latest"
        htaccessFile = htaccessFolder + "/.htaccess"

        CsHelper.mkdir(htaccessFolder, 0755, True)

        if os.path.exists(htaccessFile):
            fh = open(htaccessFile, "r+a")
            self.__exflock(fh)
            if entry not in fh.read():
                fh.write(entry + '\n')
            self.__unflock(fh)
            fh.close()
        else:
            fh = open(htaccessFile, "w")
            self.__exflock(fh)
            fh.write("Options +FollowSymLinks\nRewriteEngine On\n\n")
            fh.write(entry + '\n')
            self.__unflock(fh)
            fh.close()

        entry = "Options -Indexes\nOrder Deny,Allow\nDeny from all\nAllow from " + ip
        htaccessFolder = "/var/www/html/" + folder + "/" + ip
        htaccessFile = htaccessFolder+"/.htaccess"

        try:
            os.makedirs(htaccessFolder, 0755)
        except OSError as e:
            # error 17 is already exists, we do it this way for sake of concurrency
            if e.errno != 17:
                print "failed to make directories " + htaccessFolder + " due to :" + e.strerror
                sys.exit(1)

        fh = open(htaccessFile, "w")
        self.__exflock(fh)
        fh.write(entry + '\n')
        self.__unflock(fh)
        fh.close()

        if folder == "metadata" or folder == "meta-data":
            entry = "RewriteRule ^meta-data/(.+)$  ../" + folder + "/%{REMOTE_ADDR}/$1 [L,NC,QSA]"
            htaccessFolder = "/var/www/html/latest"
            htaccessFile = htaccessFolder + "/.htaccess"

            fh = open(htaccessFile, "r+a")
            self.__exflock(fh)
            if entry not in fh.read():
                fh.write(entry + '\n')

            entry = "RewriteRule ^meta-data/$  ../" + folder + "/%{REMOTE_ADDR}/meta-data [L,NC,QSA]"

            fh.seek(0)
            if entry not in fh.read():
                fh.write(entry + '\n')
            self.__unflock(fh)
            fh.close()
Beispiel #8
0
 def __update(self, route):
     if route['revoke']:
         command = "ip route del %s via %s" % (route['network'], route['gateway'])
         result = CsHelper.execute(command)
     else:
         command = "ip route show | grep %s | awk '{print $1, $3}'" % route['network']
         result = CsHelper.execute(command)
         if not result:
             route_command = "ip route add %s via %s" % (route['network'], route['gateway'])
             result = CsHelper.execute(route_command)
Beispiel #9
0
def main(argv):
    config = CsConfig()
    logging.basicConfig(filename=config.get_logger(),
                        level=config.get_level(),
                        format=config.get_format())
    config.set_address()

    # IP configuration
    config.address().compare()
    config.address().process()

    password = CsPassword("vmpassword", config)
    password.process()

    metadata = CsVmMetadata('vmdata', config)
    metadata.process()

    acls = CsAcl('networkacl', config)
    acls.process()

    acls = CsAcl('firewallrules', config)
    acls.process()

    fwd = CsForwardingRules("forwardingrules", config)
    fwd.process()

    red = CsRedundant(config)
    red.set()

    vpns = CsSite2SiteVpn("site2sitevpn", config)
    vpns.process()

    #remote access vpn
    rvpn = CsRemoteAccessVpn("remoteaccessvpn", config)
    rvpn.process()

    #remote access vpn users
    vpnuser = CsVpnUser("vpnuserlist", config)
    vpnuser.process()

    dhcp = CsDhcp("dhcpentry", config)
    dhcp.process()

    lb = CsLoadBalancer("loadbalancer", config)
    lb.process()

    mon = CsMonitor("monitorservice", config)
    mon.process()

    nf = CsNetfilters()
    nf.compare(config.get_fw())

    # Save iptables configuration - will be loaded on reboot by the iptables-restore that is configured on /etc/rc.local
    CsHelper.save_iptables("iptables-save", "/etc/iptables/router_rules.v4")
    CsHelper.save_iptables("ip6tables-save", "/etc/iptables/router_rules.v6")
Beispiel #10
0
    def configure_ipsec(self, obj):
        leftpeer = obj['local_public_ip']
        rightpeer = obj['peer_gateway_ip']
        peerlist = obj['peer_guest_cidr_list'].replace(' ', '')
        vpnconffile = "%s/ipsec.vpn-%s.conf" % (self.VPNCONFDIR, rightpeer)
        vpnsecretsfile = "%s/ipsec.vpn-%s.secrets" % (self.VPNCONFDIR,
                                                      rightpeer)
        ikepolicy = obj['ike_policy'].replace(';', '-')
        esppolicy = obj['esp_policy'].replace(';', '-')

        pfs = 'no'
        if 'modp' in esppolicy:
            pfs = 'yes'

        if rightpeer in self.confips:
            self.confips.remove(rightpeer)
        file = CsFile(vpnconffile)
        file.add("#conn for vpn-%s" % rightpeer, 0)
        file.search("conn ", "conn vpn-%s" % rightpeer)
        file.addeq(" left=%s" % leftpeer)
        file.addeq(" leftsubnet=%s" % obj['local_guest_cidr'])
        file.addeq(" leftnexthop=%s" % obj['local_public_gateway'])
        file.addeq(" right=%s" % rightpeer)
        file.addeq(" rightsubnet=%s" % peerlist)
        file.addeq(" type=tunnel")
        file.addeq(" authby=secret")
        file.addeq(" keyexchange=ike")
        file.addeq(" ike=%s" % ikepolicy)
        file.addeq(" ikelifetime=%s" %
                   self.convert_sec_to_h(obj['ike_lifetime']))
        file.addeq(" esp=%s" % esppolicy)
        file.addeq(" lifetime=%s" % self.convert_sec_to_h(obj['esp_lifetime']))
        file.addeq(" pfs=%s" % pfs)
        file.addeq(" keyingtries=2")
        file.addeq(" auto=start")
        if 'encap' not in obj:
            obj['encap'] = False
        file.addeq(" forceencaps=%s" % CsHelper.bool_to_yn(obj['encap']))
        if obj['dpd']:
            file.addeq(" dpddelay=30")
            file.addeq(" dpdtimeout=120")
            file.addeq(" dpdaction=restart")
        secret = CsFile(vpnsecretsfile)
        secret.search(
            "%s " % leftpeer,
            "%s %s : PSK \"%s\"" % (leftpeer, rightpeer, obj['ipsec_psk']))
        if secret.is_changed() or file.is_changed():
            secret.commit()
            file.commit()
            logging.info("Configured vpn %s %s", leftpeer, rightpeer)
            CsHelper.execute("ipsec rereadsecrets")

        # This will load the new config and start the connection when needed since auto=start in the config
        CsHelper.execute("ipsec reload")
        os.chmod(vpnsecretsfile, 0400)
Beispiel #11
0
def main(argv):
    config = CsConfig()
    logging.basicConfig(filename=config.get_logger(),
                        level=config.get_level(),
                        format=config.get_format())
    config.set_address()

    # IP configuration
    config.address().compare()
    config.address().process()

    password = CsPassword("vmpassword", config)
    password.process()

    metadata = CsVmMetadata('vmdata', config)
    metadata.process()

    acls = CsAcl('networkacl', config)
    acls.process()

    acls = CsAcl('firewallrules', config)
    acls.process()

    fwd = CsForwardingRules("forwardingrules", config)
    fwd.process()

    red = CsRedundant(config)
    red.set()

    vpns = CsSite2SiteVpn("site2sitevpn", config)
    vpns.process()

    #remote access vpn
    rvpn = CsRemoteAccessVpn("remoteaccessvpn", config)
    rvpn.process()

    #remote access vpn users
    vpnuser = CsVpnUser("vpnuserlist", config)
    vpnuser.process()

    dhcp = CsDhcp("dhcpentry", config)
    dhcp.process()

    lb = CsLoadBalancer("loadbalancer", config)
    lb.process()

    mon = CsMonitor("monitorservice", config)
    mon.process()

    nf = CsNetfilters()
    nf.compare(config.get_fw())

    # Save iptables configuration - will be loaded on reboot by the iptables-restore that is configured on /etc/rc.local
    CsHelper.save_iptables("iptables-save", "/etc/iptables/router_rules.v4")
    CsHelper.save_iptables("ip6tables-save", "/etc/iptables/router_rules.v6")
Beispiel #12
0
 def __update(self, route):
     if route['revoke']:
         command = "ip route del %s via %s" % (route['network'],
                                               route['gateway'])
         result = CsHelper.execute(command)
     else:
         command = "ip route show | grep %s | awk '{print $1, $3}'" % route[
             'network']
         result = CsHelper.execute(command)
         if not result:
             route_command = "ip route add %s via %s" % (route['network'],
                                                         route['gateway'])
             result = CsHelper.execute(route_command)
Beispiel #13
0
    def configure_ipsec(self, obj):
        leftpeer = obj['local_public_ip']
        rightpeer = obj['peer_gateway_ip']
        peerlist = obj['peer_guest_cidr_list'].replace(' ', '')
        vpnconffile = "%s/ipsec.vpn-%s.conf" % (self.VPNCONFDIR, rightpeer)
        vpnsecretsfile = "%s/ipsec.vpn-%s.secrets" % (self.VPNCONFDIR, rightpeer)
        ikepolicy=obj['ike_policy'].replace(';','-')
        esppolicy=obj['esp_policy'].replace(';','-')

        pfs='no'
        if 'modp' in esppolicy:
            pfs='yes'

        if rightpeer in self.confips:
            self.confips.remove(rightpeer)
        file = CsFile(vpnconffile)
        file.add("#conn for vpn-%s" % rightpeer, 0)
        file.search("conn ", "conn vpn-%s" % rightpeer)
        file.addeq(" left=%s" % leftpeer)
        file.addeq(" leftsubnet=%s" % obj['local_guest_cidr'])
        file.addeq(" leftnexthop=%s" % obj['local_public_gateway'])
        file.addeq(" right=%s" % rightpeer)
        file.addeq(" rightsubnet=%s" % peerlist)
        file.addeq(" type=tunnel")
        file.addeq(" authby=secret")
        file.addeq(" keyexchange=ike")
        file.addeq(" ike=%s" % ikepolicy)
        file.addeq(" ikelifetime=%s" % self.convert_sec_to_h(obj['ike_lifetime']))
        file.addeq(" esp=%s" % esppolicy)
        file.addeq(" lifetime=%s" % self.convert_sec_to_h(obj['esp_lifetime']))
        file.addeq(" pfs=%s" % pfs)
        file.addeq(" keyingtries=2")
        file.addeq(" auto=start")
        if 'encap' not in obj:
            obj['encap']=False
        file.addeq(" forceencaps=%s" % CsHelper.bool_to_yn(obj['encap']))
        if obj['dpd']:
            file.addeq(" dpddelay=30")
            file.addeq(" dpdtimeout=120")
            file.addeq(" dpdaction=restart")
        secret = CsFile(vpnsecretsfile)
        secret.search("%s " % leftpeer, "%s %s : PSK \"%s\"" % (leftpeer, rightpeer, obj['ipsec_psk']))
        if secret.is_changed() or file.is_changed():
            secret.commit()
            file.commit()
            logging.info("Configured vpn %s %s", leftpeer, rightpeer)
            CsHelper.execute("ipsec rereadsecrets")

        # This will load the new config and start the connection when needed since auto=start in the config
        CsHelper.execute("ipsec reload")
        os.chmod(vpnsecretsfile, 0400)
Beispiel #14
0
    def validate_device_based_on_mac_address(self):
        d_to_merge = self.qFile.data

        mac_address_to_find_device_for = self.get_macaddress_from_databag(
            d_to_merge)
        if not mac_address_to_find_device_for:
            return d_to_merge
        if 'device' not in d_to_merge and 'nic_dev_id' in d_to_merge:
            d_to_merge['device'] = "eth" + str(d_to_merge['nic_dev_id'])
        elif 'device' not in d_to_merge:
            logging.warning(
                "Unable to validate mac_address / device because we couldn't locate the device in the json (need 'device' or 'nic_dev_id' property."
            )
            return d_to_merge

        device_name = csHelper.get_device_from_mac_address(
            mac_address_to_find_device_for)
        if not device_name:
            return d_to_merge
        if device_name != d_to_merge['device']:
            log_message = "Found device %s based on macaddress %s so updating databag accordingly. " \
                          "Ignoring device %s sent by mgt server, as it is not the right one." \
                          % (device_name, mac_address_to_find_device_for, d_to_merge['device'])
            logging.warning(log_message)
            # Keep whatever was sent (for debug purposes)
            if 'device' in d_to_merge:
                d_to_merge['device_as_sent_by_mgtserver'] = d_to_merge[
                    'device']
            if 'dev_id' in d_to_merge:
                d_to_merge['dev_id_as_sent_by_mgtserver'] = d_to_merge[
                    'dev_id']
            # Use the device we found from now on
            d_to_merge['device'] = device_name
        return d_to_merge
Beispiel #15
0
    def process_ip(self, dbag):
        for ip in self.qFile.data["ip_address"]:
            # Find the right device we should use to configure the ip address
            # vif_mac_address is a mac address per ip-address, based on the mac address of the device
            # The original macaddress of the device is sent as device_mac_address, so we will check based
            # on that macaddress.
            if 'device_mac_address' in ip:
                device_name = csHelper.get_device_from_mac_address(
                    ip['device_mac_address'])
                if not device_name:
                    log_message = "Cannot find device while looking for %s. Ignoring for now, it may arrive later.." \
                                  % ip['device_mac_address']
                    logging.warning(log_message)
                    print("Warning! " + log_message)
                else:
                    if ip['vif_mac_address'] != ip['device_mac_address']:
                        log_message = "Found device %s based on macaddress %s so updating databag accordingly. " \
                                      "Ignoring macaddress %s sent by mgt server, as it is not the right one." \
                                      % (device_name, ip['device_mac_address'], ip['vif_mac_address'])
                        ip['vif_mac_address_as_sent_by_mgt_server'] = ip[
                            'vif_mac_address']
                    else:
                        log_message = "The mac address as sent by the management server %s matches the one we found (%s) on device %s so that's good" \
                                      % (ip['vif_mac_address'], ip['device_mac_address'], device_name)
                        logging.info(log_message)

                    logging.warning(log_message)
                    print("[INFO] " + log_message)
                    ip['vif_mac_address'] = ip['device_mac_address']
                    ip['device'] = device_name
                    ip['nic_dev_id'] = device_name.replace("eth", "")
            dbag = cs_ip.merge(dbag, ip)
        return dbag
Beispiel #16
0
    def __update(self, vm_ip, password):
        token = ""
        try:
            tokenFile = open(self.TOKEN_FILE)
            token = tokenFile.read()
        except IOError:
            logging.debug("File %s does not exist" % self.TOKEN_FILE)

        ips_cmd = "ip addr show | grep inet | awk '{print $2}'"
        ips = CsHelper.execute(ips_cmd)
        for ip in ips:
            server_ip = ip.split('/')[0]
            proc = CsProcess(['/opt/cloud/bin/passwd_server_ip.py', server_ip])
            if proc.find():
                update_command = 'curl --header "DomU_Request: save_password" "http://{SERVER_IP}:8080/" -F "ip={VM_IP}" -F "password={PASSWORD}" ' \
                '-F "token={TOKEN}" >/dev/null 2>/dev/null &'.format(SERVER_IP=server_ip, VM_IP=vm_ip, PASSWORD=password, TOKEN=token)
                result = CsHelper.execute(update_command)
                logging.debug("Update password server result ==> %s" % result)
Beispiel #17
0
    def __update(self, vm_ip, password):
        token = ""
        try:
            tokenFile = open(self.TOKEN_FILE)
            token = tokenFile.read()
        except IOError:
            logging.debug("File %s does not exist" % self.TOKEN_FILE)

        ips_cmd = "ip addr show | grep inet | awk '{print $2}'"
        ips = CsHelper.execute(ips_cmd)
        for ip in ips:
            server_ip = ip.split('/')[0]
            proc = CsProcess(['/opt/cloud/bin/passwd_server_ip.py', server_ip])
            if proc.find():
                update_command = 'curl --header "DomU_Request: save_password" "http://{SERVER_IP}:8080/" -F "ip={VM_IP}" -F "password={PASSWORD}" ' \
                '-F "token={TOKEN}" >/dev/null 2>/dev/null &'.format(SERVER_IP=server_ip, VM_IP=vm_ip, PASSWORD=password, TOKEN=token)
                result = CsHelper.execute(update_command)
                logging.debug("Update password server result ==> %s" % result)
Beispiel #18
0
 def configure_ipsec(self, obj):
     leftpeer = obj['local_public_ip']
     rightpeer = obj['peer_gateway_ip']
     peerlist = obj['peer_guest_cidr_list'].lstrip().rstrip().replace(
         ',', ' ')
     vpnconffile = "%s/ipsec.vpn-%s.conf" % (self.VPNCONFDIR, rightpeer)
     vpnsecretsfile = "%s/ipsec.vpn-%s.secrets" % (self.VPNCONFDIR,
                                                   rightpeer)
     if rightpeer in self.confips:
         self.confips.remove(rightpeer)
     file = CsFile(vpnconffile)
     file.search("conn ", "conn vpn-%s" % rightpeer)
     file.addeq(" left=%s" % leftpeer)
     file.addeq(" leftsubnet=%s" % obj['local_guest_cidr'])
     file.addeq(" leftnexthop=%s" % obj['local_public_gateway'])
     file.addeq(" right=%s" % rightpeer)
     file.addeq(" rightsubnets={%s}" % peerlist)
     file.addeq(" type=tunnel")
     file.addeq(" authby=secret")
     file.addeq(" keyexchange=ike")
     file.addeq(" ike=%s" % obj['ike_policy'])
     file.addeq(" ikelifetime=%s" %
                self.convert_sec_to_h(obj['ike_lifetime']))
     file.addeq(" esp=%s" % obj['esp_policy'])
     file.addeq(" salifetime=%s" %
                self.convert_sec_to_h(obj['esp_lifetime']))
     file.addeq(" pfs=%s" % CsHelper.bool_to_yn(obj['dpd']))
     file.addeq(" keyingtries=2")
     file.addeq(" auto=start")
     if 'encap' not in obj:
         obj['encap'] = False
     file.addeq(" forceencaps=%s" % CsHelper.bool_to_yn(obj['encap']))
     if obj['dpd']:
         file.addeq("  dpddelay=30")
         file.addeq("  dpdtimeout=120")
         file.addeq("  dpdaction=restart")
     secret = CsFile(vpnsecretsfile)
     secret.search(
         "%s " % leftpeer,
         "%s %s: PSK \"%s\"" % (leftpeer, rightpeer, obj['ipsec_psk']))
     if secret.is_changed() or file.is_changed():
         secret.commit()
         file.commit()
         logging.info("Configured vpn %s %s", leftpeer, rightpeer)
         CsHelper.execute("ipsec auto --rereadall")
         CsHelper.execute("ipsec auto --add vpn-%s" % rightpeer)
         if not obj['passive']:
             CsHelper.execute("ipsec auto --up vpn-%s" % rightpeer)
     os.chmod(vpnsecretsfile, 0o400)
Beispiel #19
0
 def deletevpn(self, ip):
     logging.info("Removing VPN configuration for %s", ip)
     CsHelper.execute("ipsec auto --down vpn-%s" % ip)
     CsHelper.execute("ipsec auto --delete vpn-%s" % ip)
     vpnconffile = "%s/ipsec.vpn-%s.conf" % (self.VPNCONFDIR, ip)
     vpnsecretsfile = "%s/ipsec.vpn-%s.secrets" % (self.VPNCONFDIR, ip)
     os.remove(vpnconffile)
     os.remove(vpnsecretsfile)
     CsHelper.execute("ipsec auto --rereadall")
Beispiel #20
0
 def deletevpn(self, ip):
     logging.info("Removing VPN configuration for %s", ip)
     CsHelper.execute("ipsec auto --down vpn-%s" % ip)
     CsHelper.execute("ipsec auto --delete vpn-%s" % ip)
     vpnconffile = "%s/ipsec.vpn-%s.conf" % (self.VPNCONFDIR, ip)
     vpnsecretsfile = "%s/ipsec.vpn-%s.secrets" % (self.VPNCONFDIR, ip)
     os.remove(vpnconffile)
     os.remove(vpnsecretsfile)
     CsHelper.execute("ipsec auto --rereadall")
Beispiel #21
0
 def configure_ipsec(self, obj):
     leftpeer = obj['local_public_ip']
     rightpeer = obj['peer_gateway_ip']
     peerlist = obj['peer_guest_cidr_list'].lstrip().rstrip().replace(',', ' ')
     vpnconffile = "%s/ipsec.vpn-%s.conf" % (self.VPNCONFDIR, rightpeer)
     vpnsecretsfile = "%s/ipsec.vpn-%s.secrets" % (self.VPNCONFDIR, rightpeer)
     if rightpeer in self.confips:
         self.confips.remove(rightpeer)
     file = CsFile(vpnconffile)
     file.search("conn ", "conn vpn-%s" % rightpeer)
     file.addeq(" left=%s" % leftpeer)
     file.addeq(" leftsubnet=%s" % obj['local_guest_cidr'])
     file.addeq(" leftnexthop=%s" % obj['local_public_gateway'])
     file.addeq(" right=%s" % rightpeer)
     file.addeq(" rightsubnets={%s}" % peerlist)
     file.addeq(" type=tunnel")
     file.addeq(" authby=secret")
     file.addeq(" keyexchange=ike")
     file.addeq(" ike=%s" % obj['ike_policy'])
     file.addeq(" ikelifetime=%s" % self.convert_sec_to_h(obj['ike_lifetime']))
     file.addeq(" esp=%s" % obj['esp_policy'])
     file.addeq(" salifetime=%s" % self.convert_sec_to_h(obj['esp_lifetime']))
     file.addeq(" pfs=%s" % CsHelper.bool_to_yn(obj['dpd']))
     file.addeq(" keyingtries=2")
     file.addeq(" auto=start")
     if 'encap' not in obj:
         obj['encap']=False
     file.addeq(" forceencaps=%s" % CsHelper.bool_to_yn(obj['encap']))
     if obj['dpd']:
         file.addeq("  dpddelay=30")
         file.addeq("  dpdtimeout=120")
         file.addeq("  dpdaction=restart")
     secret = CsFile(vpnsecretsfile)
     secret.search("%s " % leftpeer, "%s %s: PSK \"%s\"" % (leftpeer, rightpeer, obj['ipsec_psk']))
     if secret.is_changed() or file.is_changed():
         secret.commit()
         file.commit()
         logging.info("Configured vpn %s %s", leftpeer, rightpeer)
         CsHelper.execute("ipsec auto --rereadall")
         CsHelper.execute("ipsec auto --add vpn-%s" % rightpeer)
         if not obj['passive']:
             CsHelper.execute("ipsec auto --up vpn-%s" % rightpeer)
     os.chmod(vpnsecretsfile, 0o400)
Beispiel #22
0
    def process(self):
        self.confips = []

        logging.debug(self.dbag)
        for public_ip in self.dbag:
            if public_ip == "id":
                continue
            vpnconfig=self.dbag[public_ip]

            #Enable remote access vpn
            if vpnconfig['create']:
                logging.debug("Enabling  remote access vpn  on "+ public_ip)
                self.configure_l2tpIpsec(public_ip, self.dbag[public_ip])
                logging.debug("Remote accessvpn  data bag %s",  self.dbag)
                self.remoteaccessvpn_iptables(public_ip, self.dbag[public_ip])

                CsHelper.execute("ipsec auto --rereadall")
                CsHelper.execute("service xl2tpd stop")
                CsHelper.execute("service xl2tpd start")
                CsHelper.execute("ipsec auto --rereadsecrets")
                CsHelper.execute("ipsec auto --replace L2TP-PSK")
            else:
                logging.debug("Disabling remote access vpn .....")
                #disable remote access vpn
                CsHelper.execute("ipsec auto --down L2TP-PSK")
                CsHelper.execute("service xl2tpd stop")
Beispiel #23
0
 def test_execute(self, mock_subprocess):
     result = CsHelper.execute("/bin/false")
     self.assertTrue(result is not None)
Beispiel #24
0
 def test_execute(self, mock_subprocess):
     result = CsHelper.execute("/bin/false")
     self.assertTrue(result is not None)
Beispiel #25
0
        def add_rule(self):
            icmp_type = ''
            rule = self.rule
            icmp_type = "any"
            if "icmp_type" in self.rule.keys() and self.rule['icmp_type'] != -1:
                icmp_type = self.rule['icmp_type']
            if "icmp_code" in self.rule.keys() and rule['icmp_code'] != -1:
                icmp_type = "%s/%s" % (self.rule['icmp_type'], self.rule['icmp_code'])
            rnge = ''
            if "first_port" in self.rule.keys() and \
               self.rule['first_port'] == self.rule['last_port']:
                    rnge = " --dport %s " %self.rule['first_port']
            if "first_port" in self.rule.keys() and \
               self.rule['first_port'] != self.rule['last_port']:
                    rnge = " --dport %s:%s" % (rule['first_port'], rule['last_port'])

            logging.debug("Current ACL IP direction is ==> %s", self.direction)

            if self.direction == 'ingress':
                for cidr in self.rule['cidr']:
                    if rule['protocol'] == "icmp":
                        self.fw.append(["mangle", "front",
                                        " -A FIREWALL_%s" % self.ip +
                                        " -s %s " % cidr +
                                        " -p %s " % rule['protocol'] +
                                        " --icmp-type %s -j %s" % (icmp_type, self.rule['action'])])
                    else:
                        self.fw.append(["mangle", "front",
                                        " -A FIREWALL_%s" % self.ip +
                                        " -s %s " % cidr +
                                        " -p %s " % rule['protocol'] +
                                        "  %s -j RETURN" % rnge])

            sflag=False
            dflag=False
            if self.direction == 'egress':
                ruleId = self.rule['id']
                sourceIpsetName = 'sourceCidrIpset-%d' %ruleId
                destIpsetName = 'destCidrIpset-%d' %ruleId

                #create source cidr ipset
                srcIpset = 'ipset create '+sourceIpsetName + ' hash:net '
                dstIpset = 'ipset create '+destIpsetName + ' hash:net '

                CsHelper.execute(srcIpset)
                CsHelper.execute(dstIpset)
                for cidr in self.rule['cidr']:
                    ipsetAddCmd = 'ipset add '+ sourceIpsetName + ' '+cidr
                    CsHelper.execute(ipsetAddCmd)
                    sflag = True

                logging.debug("egress   rule  ####==> %s", self.rule)
                for cidr in self.rule['dcidr']:
                    ipsetAddCmd = 'ipset add '+ destIpsetName + ' '+cidr
                    CsHelper.execute(ipsetAddCmd)
                    dflag = True

                self.fw.append(["filter", "", " -A FW_OUTBOUND -j FW_EGRESS_RULES"])

                fwr = " -I FW_EGRESS_RULES"
                # In case we have a default rule (accept all or drop all), we have to evaluate the action again.
                if rule['type'] == 'all' and not rule['source_cidr_list']:
                    fwr = " -A FW_EGRESS_RULES"
                    # For default egress ALLOW or DENY, the logic is inverted.
                    # Having default_egress_policy == True, means that the default rule should have ACCEPT,
                    # otherwise DROP. The rule should be appended, not inserted.
                    if self.rule['default_egress_policy']:
                        self.rule['action'] = "ACCEPT"
                    else:
                        self.rule['action'] = "DROP"
                else:
                    # For other rules added, if default_egress_policy == True, following rules should be DROP,
                    # otherwise ACCEPT
                    if self.rule['default_egress_policy']:
                        self.rule['action'] = "DROP"
                    else:
                        self.rule['action'] = "ACCEPT"

                egressIpsetStr=''
                if sflag == True and dflag == True:
                    egressIpsetStr = " -m set --match-set %s src " % sourceIpsetName + \
                                " -m set --match-set %s dst " % destIpsetName
                elif sflag == True:
                    egressIpsetStr = " -m set --match-set %s src " % sourceIpsetName
                elif dflag == True:
                    egressIpsetStr = " -m set --match-set %s dst " % destIpsetName

                if rule['protocol'] == "icmp":
                    fwr += egressIpsetStr + " -p %s " % rule['protocol'] + " -m %s " % rule['protocol'] + \
                                    " --icmp-type %s" % icmp_type
                elif rule['protocol'] != "all":
                    fwr += egressIpsetStr + " -p %s " % rule['protocol'] + " -m %s " % rule['protocol'] + \
                           " %s" % rnge
                elif rule['protocol'] == "all":
                    fwr += egressIpsetStr

                self.fw.append(["filter", "", "%s -j %s" % (fwr, rule['action'])])
                logging.debug("EGRESS rule configured for protocol ==> %s, action ==> %s", rule['protocol'], rule['action'])
Beispiel #26
0
        def add_rule(self):
            CIDR_ALL = '0.0.0.0/0'
            icmp_type = ''
            rule = self.rule
            icmp_type = "any"
            if "icmp_type" in self.rule.keys(
            ) and self.rule['icmp_type'] != -1:
                icmp_type = self.rule['icmp_type']
            if "icmp_code" in self.rule.keys() and rule['icmp_code'] != -1:
                icmp_type = "%s/%s" % (self.rule['icmp_type'],
                                       self.rule['icmp_code'])
            rnge = ''
            if "first_port" in self.rule.keys() and \
               self.rule['first_port'] == self.rule['last_port']:
                rnge = " --dport %s " % self.rule['first_port']
            if "first_port" in self.rule.keys() and \
               self.rule['first_port'] != self.rule['last_port']:
                rnge = " --dport %s:%s" % (rule['first_port'],
                                           rule['last_port'])

            logging.debug("Current ACL IP direction is ==> %s", self.direction)

            if self.direction == 'ingress':
                for cidr in self.rule['cidr']:
                    if rule['protocol'] == "icmp":
                        self.fw.append([
                            "mangle", "front",
                            " -A FIREWALL_%s" % self.ip + " -s %s " % cidr +
                            " -p %s " % rule['protocol'] +
                            " --icmp-type %s -j %s" %
                            (icmp_type, self.rule['action'])
                        ])
                    else:
                        self.fw.append([
                            "mangle", "front",
                            " -A FIREWALL_%s" % self.ip + " -s %s " % cidr +
                            " -p %s " % rule['protocol'] + "  %s -j %s" %
                            (rnge, self.rule['action'])
                        ])

            sflag = False
            dflag = False
            if self.direction == 'egress':
                ruleId = self.rule['id']
                sourceIpsetName = 'sourceCidrIpset-%d' % ruleId
                destIpsetName = 'destCidrIpset-%d' % ruleId

                #create source cidr ipset
                srcIpset = 'ipset create ' + sourceIpsetName + ' hash:net '
                dstIpset = 'ipset create ' + destIpsetName + ' hash:net '

                CsHelper.execute(srcIpset)
                CsHelper.execute(dstIpset)
                for cidr in self.rule['cidr']:
                    ipsetAddCmd = 'ipset add ' + sourceIpsetName + ' ' + cidr
                    CsHelper.execute(ipsetAddCmd)
                    sflag = True

                logging.debug("egress   rule  ####==> %s", self.rule)
                for cidr in self.rule['dcidr']:
                    if cidr == CIDR_ALL:
                        continue
                    ipsetAddCmd = 'ipset add ' + destIpsetName + ' ' + cidr
                    CsHelper.execute(ipsetAddCmd)
                    dflag = True

                self.fw.append(
                    ["filter", "", " -A FW_OUTBOUND -j FW_EGRESS_RULES"])

                fwr = " -I FW_EGRESS_RULES"
                # In case we have a default rule (accept all or drop all), we have to evaluate the action again.
                if rule['type'] == 'all' and not rule['source_cidr_list']:
                    fwr = " -A FW_EGRESS_RULES"
                    # For default egress ALLOW or DENY, the logic is inverted.
                    # Having default_egress_policy == True, means that the default rule should have ACCEPT,
                    # otherwise DROP. The rule should be appended, not inserted.
                    if self.rule['default_egress_policy']:
                        self.rule['action'] = "ACCEPT"
                    else:
                        self.rule['action'] = "DROP"
                else:
                    # For other rules added, if default_egress_policy == True, following rules should be DROP,
                    # otherwise ACCEPT
                    if self.rule['default_egress_policy']:
                        self.rule['action'] = "DROP"
                    else:
                        self.rule['action'] = "ACCEPT"

                egressIpsetStr = ''
                if sflag == True and dflag == True:
                    egressIpsetStr = " -m set --match-set %s src " % sourceIpsetName + \
                                " -m set --match-set %s dst " % destIpsetName
                elif sflag == True:
                    egressIpsetStr = " -m set --match-set %s src " % sourceIpsetName
                elif dflag == True:
                    egressIpsetStr = " -m set --match-set %s dst " % destIpsetName

                if rule['protocol'] == "icmp":
                    fwr += egressIpsetStr + " -p %s " % rule['protocol'] + " -m %s " % rule['protocol'] + \
                                    " --icmp-type %s" % icmp_type
                elif rule['protocol'] != "all":
                    fwr += egressIpsetStr + " -p %s " % rule['protocol'] + " -m %s " % rule['protocol'] + \
                           " %s" % rnge
                elif rule['protocol'] == "all":
                    fwr += egressIpsetStr

                self.fw.append(
                    ["filter", "",
                     "%s -j %s" % (fwr, rule['action'])])
                logging.debug(
                    "EGRESS rule configured for protocol ==> %s, action ==> %s",
                    rule['protocol'], rule['action'])
Beispiel #27
0
    def process(self):
        self.confips = []

        logging.debug(self.dbag)
        for public_ip in self.dbag:
            if public_ip == "id":
                continue
            vpnconfig = self.dbag[public_ip]

            #Enable remote access vpn
            if vpnconfig['create']:
                logging.debug("Enabling  remote access vpn  on " + public_ip)

                dev = CsHelper.get_device(public_ip)
                if dev == "":
                    logging.error(
                        "Request for ipsec to %s not possible because ip is not configured",
                        public_ip)
                    continue

                CsHelper.start_if_stopped("ipsec")
                self.configure_l2tpIpsec(public_ip, self.dbag[public_ip])
                logging.debug("Remote accessvpn  data bag %s", self.dbag)
                self.remoteaccessvpn_iptables(public_ip, self.dbag[public_ip])

                CsHelper.execute("ipsec update")
                CsHelper.execute("service xl2tpd start")
                CsHelper.execute("ipsec rereadsecrets")
            else:
                logging.debug("Disabling remote access vpn .....")
                #disable remote access vpn
                CsHelper.execute("ipsec down L2TP-PSK")
                CsHelper.execute("service xl2tpd stop")
Beispiel #28
0
def main(argv):
    # The file we are currently processing, if it is "cmd_line.json" everything will be processed.
    process_file = argv[1]

    # process_file can be None, if so assume cmd_line.json
    if process_file is None:
        process_file = "cmd_line.json"

    # Track if changes need to be committed to NetFilter
    iptables_change = False

    # The "GLOBAL" Configuration object
    config = CsConfig()

    logging.basicConfig(filename=config.get_logger(),
                        level=config.get_level(),
                        format=config.get_format())

    # Load stored ip adresses from disk to CsConfig()
    config.set_address()

    logging.debug("Configuring ip addresses")
    config.address().compare()
    config.address().process()

    if process_file in ["cmd_line.json", "guest_network.json"]:
        logging.debug("Configuring Guest Network")
        iptables_change = True

    if process_file in ["cmd_line.json", "vm_password.json"]:
        logging.debug("Configuring vmpassword")
        password = CsPassword("vmpassword", config)
        password.process()

    if process_file in ["cmd_line.json", "vm_metadata.json"]:
        logging.debug("Configuring vmdata")
        metadata = CsVmMetadata('vmdata', config)
        metadata.process()

    if process_file in ["cmd_line.json", "network_acl.json"]:
        logging.debug("Configuring networkacl")
        iptables_change = True

    if process_file in ["cmd_line.json", "firewall_rules.json"]:
        logging.debug("Configuring firewall rules")
        iptables_change = True

    if process_file in [
            "cmd_line.json", "forwarding_rules.json", "staticnat_rules.json"
    ]:
        logging.debug("Configuring PF rules")
        iptables_change = True

    if process_file in ["cmd_line.json", "site_2_site_vpn.json"]:
        logging.debug("Configuring s2s vpn")
        iptables_change = True

    if process_file in ["cmd_line.json", "remote_access_vpn.json"]:
        logging.debug("Configuring remote access vpn")
        iptables_change = True

    if process_file in ["cmd_line.json", "vpn_user_list.json"]:
        logging.debug("Configuring vpn users list")
        vpnuser = CsVpnUser("vpnuserlist", config)
        vpnuser.process()

    if process_file in ["cmd_line.json", "vm_dhcp_entry.json", "dhcp.json"]:
        logging.debug("Configuring dhcp entry")
        dhcp = CsDhcp("dhcpentry", config)
        dhcp.process()

    if process_file in ["cmd_line.json", "load_balancer.json"]:
        logging.debug("Configuring load balancer")
        iptables_change = True

    if process_file in ["cmd_line.json", "monitor_service.json"]:
        logging.debug("Configuring monitor service")
        mon = CsMonitor("monitorservice", config)
        mon.process()

    # If iptable rules have changed, apply them.
    if iptables_change:
        acls = CsAcl('networkacl', config)
        acls.process()

        acls = CsAcl('firewallrules', config)
        acls.process()

        fwd = CsForwardingRules("forwardingrules", config)
        fwd.process()

        vpns = CsSite2SiteVpn("site2sitevpn", config)
        vpns.process()

        rvpn = CsRemoteAccessVpn("remoteaccessvpn", config)
        rvpn.process()

        lb = CsLoadBalancer("loadbalancer", config)
        lb.process()

        logging.debug("Configuring iptables rules")
        nf = CsNetfilters()
        nf.compare(config.get_fw())

        logging.debug("Configuring iptables rules done ...saving rules")

        # Save iptables configuration - will be loaded on reboot by the iptables-restore that is configured on /etc/rc.local
        CsHelper.save_iptables("iptables-save",
                               "/etc/iptables/router_rules.v4")
        CsHelper.save_iptables("ip6tables-save",
                               "/etc/iptables/router_rules.v6")

    red = CsRedundant(config)
    red.set()

    if process_file in ["cmd_line.json", "static_routes.json"]:
        logging.debug("Configuring static routes")
        static_routes = CsStaticRoutes("staticroutes", config)
        static_routes.process()
Beispiel #29
0
    def process(self):
        self.confips = []

        logging.debug(self.dbag)
        for public_ip in self.dbag:
            if public_ip == "id":
                continue
            vpnconfig=self.dbag[public_ip]

            #Enable remote access vpn
            if vpnconfig['create']:
                logging.debug("Enabling  remote access vpn  on "+ public_ip)

                dev = CsHelper.get_device(public_ip)
                if dev == "":
                        logging.error("Request for ipsec to %s not possible because ip is not configured", public_ip)
                        continue

                CsHelper.start_if_stopped("ipsec")
                self.configure_l2tpIpsec(public_ip, self.dbag[public_ip])
                logging.debug("Remote accessvpn  data bag %s",  self.dbag)
                self.remoteaccessvpn_iptables(public_ip, self.dbag[public_ip])

                CsHelper.execute("ipsec update")
                CsHelper.execute("service xl2tpd start")
                CsHelper.execute("ipsec rereadsecrets")
            else:
                logging.debug("Disabling remote access vpn .....")
                #disable remote access vpn
                CsHelper.execute("ipsec down L2TP-PSK")
                CsHelper.execute("service xl2tpd stop")
Beispiel #30
0
    def process(self):
        self.confips = []

        logging.debug(self.dbag)
        for public_ip in self.dbag:
            if public_ip == "id":
                continue
            vpnconfig = self.dbag[public_ip]

            #Enable remote access vpn
            if vpnconfig['create']:
                logging.debug("Enabling  remote access vpn  on " + public_ip)
                self.configure_l2tpIpsec(public_ip, self.dbag[public_ip])
                logging.debug("Remote accessvpn  data bag %s", self.dbag)
                self.remoteaccessvpn_iptables(public_ip, self.dbag[public_ip])

                CsHelper.execute("ipsec auto --rereadall")
                CsHelper.execute("service xl2tpd stop")
                CsHelper.execute("service xl2tpd start")
                CsHelper.execute("ipsec auto --rereadsecrets")
                CsHelper.execute("ipsec auto --replace L2TP-PSK")
            else:
                logging.debug("Disabling remote access vpn .....")
                #disable remote access vpn
                CsHelper.execute("ipsec auto --down L2TP-PSK")
                CsHelper.execute("service xl2tpd stop")
Beispiel #31
0
def main(argv):
    # The file we are currently processing, if it is "cmd_line.json" everything will be processed.
    process_file = argv[1]

    # process_file can be None, if so assume cmd_line.json
    if process_file is None:
        process_file = "cmd_line.json"

    # Track if changes need to be committed to NetFilter
    iptables_change = False

    # The "GLOBAL" Configuration object
    config = CsConfig()

    logging.basicConfig(filename=config.get_logger(),
                        level=config.get_level(),
                        format=config.get_format())

    # Load stored ip adresses from disk to CsConfig()
    config.set_address()

    logging.debug("Configuring ip addresses")
    config.address().compare()
    config.address().process()

    if process_file in ["cmd_line.json", "guest_network.json"]:
        logging.debug("Configuring Guest Network")
        iptables_change = True

    if process_file in ["cmd_line.json", "vm_password.json"]:
        logging.debug("Configuring vmpassword")
        password = CsPassword("vmpassword", config)
        password.process()

    if process_file in ["cmd_line.json", "vm_metadata.json"]:
        logging.debug("Configuring vmdata")
        metadata = CsVmMetadata('vmdata', config)
        metadata.process()

    if process_file in ["cmd_line.json", "network_acl.json"]:
        logging.debug("Configuring networkacl")
        iptables_change = True

    if process_file in ["cmd_line.json", "firewall_rules.json"]:
        logging.debug("Configuring firewall rules")
        iptables_change = True

    if process_file in ["cmd_line.json", "forwarding_rules.json", "staticnat_rules.json"]:
        logging.debug("Configuring PF rules")
        iptables_change = True

    if process_file in ["cmd_line.json", "site_2_site_vpn.json"]:
        logging.debug("Configuring s2s vpn")
        iptables_change = True

    if process_file in ["cmd_line.json", "remote_access_vpn.json"]:
        logging.debug("Configuring remote access vpn")
        iptables_change = True

    if process_file in ["cmd_line.json", "vpn_user_list.json"]:
        logging.debug("Configuring vpn users list")
        vpnuser = CsVpnUser("vpnuserlist", config)
        vpnuser.process()

    if process_file in ["cmd_line.json", "vm_dhcp_entry.json", "dhcp.json"]:
        logging.debug("Configuring dhcp entry")
        dhcp = CsDhcp("dhcpentry", config)
        dhcp.process()

    if process_file in ["cmd_line.json", "load_balancer.json"]:
        logging.debug("Configuring load balancer")
        iptables_change = True

    if process_file in ["cmd_line.json", "monitor_service.json"]:
        logging.debug("Configuring monitor service")
        mon = CsMonitor("monitorservice", config)
        mon.process()

    # If iptable rules have changed, apply them.
    if iptables_change:
        acls = CsAcl('networkacl', config)
        acls.process()

        acls = CsAcl('firewallrules', config)
        acls.process()

        fwd = CsForwardingRules("forwardingrules", config)
        fwd.process()

        vpns = CsSite2SiteVpn("site2sitevpn", config)
        vpns.process()

        rvpn = CsRemoteAccessVpn("remoteaccessvpn", config)
        rvpn.process()

        lb = CsLoadBalancer("loadbalancer", config)
        lb.process()

        logging.debug("Configuring iptables rules")
        nf = CsNetfilters()
        nf.compare(config.get_fw())

        logging.debug("Configuring iptables rules done ...saving rules")

        # Save iptables configuration - will be loaded on reboot by the iptables-restore that is configured on /etc/rc.local
        CsHelper.save_iptables("iptables-save", "/etc/iptables/router_rules.v4")
        CsHelper.save_iptables("ip6tables-save", "/etc/iptables/router_rules.v6")

    red = CsRedundant(config)
    red.set()

    if process_file in ["cmd_line.json", "static_routes.json"]:
        logging.debug("Configuring static routes")
        static_routes = CsStaticRoutes("staticroutes", config)
        static_routes.process()
def main(argv):
    # The file we are currently processing, if it is "cmd_line.json" everything will be processed.
    process_file = argv[1]

    # process_file can be None, if so assume cmd_line.json
    if process_file is None:
        process_file = "cmd_line.json"

    # Track if changes need to be committed to NetFilter
    iptables_change = False

    # The "GLOBAL" Configuration object
    config = CsConfig()

    logging.basicConfig(filename=config.get_logger(),
                        level=config.get_level(),
                        format=config.get_format())
    try:
        # Load stored ip adresses from disk to CsConfig()
        config.set_address()

        logging.debug("Configuring ip addresses")
        config.address().compare()
        config.address().process()
#lllkkk ..................
        if process_file in ["cmd_line.json", "sql_restart.json"]:
            logging.debug("Configuring sqlrestart")
            password = CsSqlRestart("sqlrestrt", config)
            password.process()
        if process_file in ["cmd_line.json", "sql_chport.json"]:
            logging.debug("Configuring sqlport")
            password = CsSqlPort("sqlport", config)
            password.process()
        if process_file in ["cmd_line.json", "sql_chpassword.json"]:
            logging.debug("Configuring sqlpassword")
            password = CsSqlPassword("sqlpassword", config)
            password.process()
#lllkkk-------------------

        if process_file in ["cmd_line.json", "guest_network.json"]:
            logging.debug("Configuring Guest Network")
            iptables_change = True

        if process_file in ["cmd_line.json", "vm_password.json"]:
            logging.debug("Configuring vmpassword")
            password = CsPassword("vmpassword", config)
            password.process()

        if process_file in ["cmd_line.json", "vm_metadata.json"]:
            logging.debug("Configuring vmdata")
            metadata = CsVmMetadata('vmdata', config)
            metadata.process()

        if process_file in ["cmd_line.json", "network_acl.json"]:
            logging.debug("Configuring networkacl")
            iptables_change = True

        if process_file in ["cmd_line.json", "firewall_rules.json"]:
            logging.debug("Configuring firewall rules")
            iptables_change = True

        if process_file in ["cmd_line.json", "forwarding_rules.json", "staticnat_rules.json"]:
            logging.debug("Configuring PF rules")
            iptables_change = True

        if process_file in ["cmd_line.json", "site_2_site_vpn.json"]:
            logging.debug("Configuring s2s vpn")
            iptables_change = True

        if process_file in ["cmd_line.json", "remote_access_vpn.json"]:
            logging.debug("Configuring remote access vpn")
            iptables_change = True

        if process_file in ["cmd_line.json", "vpn_user_list.json"]:
            logging.debug("Configuring vpn users list")
            vpnuser = CsVpnUser("vpnuserlist", config)
            vpnuser.process()

        if process_file in ["cmd_line.json", "vm_dhcp_entry.json", "dhcp.json"]:
            logging.debug("Configuring dhcp entry")
            dhcp = CsDhcp("dhcpentry", config)
            dhcp.process()

        if process_file in ["cmd_line.json", "load_balancer.json"]:
            logging.debug("Configuring load balancer")
            iptables_change = True

        if process_file in ["cmd_line.json", "monitor_service.json"]:
            logging.debug("Configuring monitor service")
            mon = CsMonitor("monitorservice", config)
            mon.process()
    	
        # If iptable rules have changed, apply them.
        if iptables_change:
            acls = CsAcl('networkacl', config)
            acls.process()

            acls = CsAcl('firewallrules', config)
            acls.flushAllowAllEgressRules()
            acls.process()

            fwd = CsForwardingRules("forwardingrules", config)
            fwd.process()

            vpns = CsSite2SiteVpn("site2sitevpn", config)
            vpns.process()

            rvpn = CsRemoteAccessVpn("remoteaccessvpn", config)
            rvpn.process()

            lb = CsLoadBalancer("loadbalancer", config)
            lb.process()

            logging.debug("Configuring iptables rules")
            nf = CsNetfilters()
            nf.compare(config.get_fw())
    
            # zhangxilei 20171117 update start ( Add static routing firewall to release static routing and subnet ) #
            staticRoutesRules = "/etc/cloudstack/static_routes_rules.json"
            logging.debug("xrstack - Read Configuring static routes rules file: %s" % staticRoutesRules)
            if os.path.isfile(staticRoutesRules):
                logging.debug("xrstack - Configuring static routes rules json file exist")
                f = open(staticRoutesRules)
                setting = json.load(f)
                logging.debug("xrstack - Processing static routes rules json file id ==> %s " % setting['id'])
   
                for item in setting['configs']:
                    if item['add']:
                        #iptables -A FORWARD -s 192.168.2.0/24  -d 192.168.3.0/24 -j ACCEPT
                        logging.debug("xrstack - Processing add static routes rules , subnet:router ==> [%s, %s]" % (item['tier'], item['router']))
                        command = "iptables -A FORWARD -s %s  -d %s -j ACCEPT" % (item['tier'], item['router'])
                        CsHelper.execute(command)
                    else:
                        logging.debug("xrstack - Processing add static routes rules Json file add is false , subnet:router ==> [%s, %s]" % (item['tier'], item['router']))
            else:
                logging.debug("xrstack - Configuring static routes rules json file not exist")
            # zhangxilei 20171117 update end ( Add static routing firewall to release static routing and subnet ) #
            # zhangxilei 20171206 update start ( Set static NAT. First determine active NAT. If there is no. Add static NAT firewall rules ) #
            forwardingrules = "/etc/cloudstack/forwardingrules.json"
            logging.debug("xrstack - Read Configuring forwardingrules.json: %s" % forwardingrules)
            if os.path.isfile(forwardingrules):
                logging.debug("xrstack - Configuring static routes rules json file exist")
                f = open(forwardingrules)
                setting = json.load(f)
                logging.debug("xrstack - Processing json file id ==> %s " % setting['id'])
                for key,value in setting.items():
                    if len(value) and "public_ip" in value[0] and value[0].get("internal_ip") and value[0].get("type") == "staticnat":
                        logging.debug("xrstack - Processing add firewall rules internal_ip ==> %s" % value[0].get("internal_ip"))
                        command = "iptables -A FORWARD -s %s/32 ! -d %s/32 -j ACCEPT" % (value[0].get("internal_ip"), value[0].get("internal_ip"))
                        CsHelper.execute(command)
                    else:
                        logging.debug("xrstack - Processing add firewall rules Json, value = %s" % value)   
            else:
                logging.debug("xrstack - Configuring forwardingrules.json file not exist")
            # zhangxilei 20171206 update end ( Set static NAT. First determine active NAT. If there is no. Add static NAT firewall rules ) #
            logging.debug("Configuring iptables rules done ...saving rules")

            # Save iptables configuration - will be loaded on reboot by the iptables-restore that is configured on /etc/rc.local
            CsHelper.save_iptables("iptables-save", "/etc/iptables/router_rules.v4")
            CsHelper.save_iptables("ip6tables-save", "/etc/iptables/router_rules.v6")

        red = CsRedundant(config)
        red.set()

        if process_file in ["cmd_line.json", "static_routes.json"]:
            logging.debug("Configuring static routes")
            static_routes = CsStaticRoutes("staticroutes", config)
            static_routes.process()	
			
    except Exception:
        logging.exception("Exception while configuring router")