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")
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) 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")
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)
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")
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" )
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)
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")
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)
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)
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)
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)
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)
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")
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'])) if "modp" in obj['esp_policy']: file.addeq(" pfs=yes") else: file.addeq(" pfs=no") 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)
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'])) if "modp" in obj['esp_policy']: file.addeq(" pfs=yes") else: file.addeq(" pfs=no") 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)
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'])
def test_execute(self, mock_subprocess): result = CsHelper.execute("/bin/false") self.assertTrue(result is not None)
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'])
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")