488 lines
18 KiB
Python
Executable file
488 lines
18 KiB
Python
Executable file
#!/usr/bin/env python
|
|
# -*- coding: iso-8859-1 -*-
|
|
# The author of this code is Manuel Sabban <manu@feyd-rautha.org>
|
|
#
|
|
# Copyright (c) 2004 Manuel Sabban.
|
|
#
|
|
# Permission to use, copy, and modify this software with or without fee
|
|
# is hereby granted, provided that this entire notice is included in
|
|
# all source code copies of any software which is or includes a copy or
|
|
# modification of this software.
|
|
#
|
|
# THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR
|
|
# IMPLIED WARRANTY. IN PARTICULAR, NONE OF THE AUTHORS MAKES ANY
|
|
# REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE
|
|
# MERCHANTABILITY OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR
|
|
# PURPOSE.
|
|
""" classe Firewall de Komaz """
|
|
import commands,time
|
|
import sys,os
|
|
import iptools,config,fileinput
|
|
from ldap_crans import *
|
|
from config_firewall import *
|
|
from affich_tools import *
|
|
|
|
class ErrorArgument(Exception):
|
|
"""
|
|
User defined exception
|
|
Erreur sur les arguments d'appel du firewall
|
|
"""
|
|
pass
|
|
|
|
class ErrorIp(Exception):
|
|
"""
|
|
User defined exception
|
|
Erreur dans les fonctions Ips
|
|
"""
|
|
def __init__(self, ip):
|
|
self.ip=ip
|
|
|
|
class ErrorMoreThanOneIp(ErrorIp):
|
|
"""
|
|
User defined exception
|
|
Au moins deux utilisateurs ont la même ip
|
|
"""
|
|
pass
|
|
|
|
class ErrorIptables(Exception):
|
|
"""
|
|
User defined exception
|
|
Les erreurs d'iptables
|
|
"""
|
|
def __init__(self,cmd,err_code,output):
|
|
self.cmd=cmd
|
|
self.err_code=err_code
|
|
self.output=output
|
|
openlog(ident='syslog',logopt=0,facility=' LOG_USER')
|
|
syslog('LOG_ALERT',cmd,err,output)
|
|
|
|
class ErrorNoSuchIp(ErrorIp):
|
|
"""
|
|
User defined exception
|
|
Personne n'a cette ip
|
|
"""
|
|
pass
|
|
|
|
class firewall:
|
|
"""
|
|
Structure du firewall :
|
|
table nat :
|
|
PREROUTING (policy par defaut : DROP)
|
|
1) passage par TEST_VIRUS
|
|
2) passage dans RESEAUX_NON_ROUTABLES_DST
|
|
3) passage est paquets venant de l'extérieur dans RESEAUX_NON_ROUTABLES_SRC
|
|
4) on laisse passer vers filter les paquets suivants :
|
|
source ou destination les serveurs de serveurs_crans
|
|
ce qui vient de l'extérieur
|
|
7) passage par TEST_MAC-IP_FLOOD
|
|
8) passage par TEST_FLOOD
|
|
|
|
TEST_VIRUS droppe les paquets contenant des virus
|
|
RESEAUX_NON_ROUTABLES_DST droppe les paquets dont la destination est non routable
|
|
RESEAUX_NON_ROUTABLES_SRC droppe les paquets dont la source est non routable
|
|
TEST_MAC-IP_FLOOD envoi les bon paquets vers CRANS_VERS_EXT
|
|
CRANS_VERS_EXT
|
|
ACCEPT pour les paquets venant des machines du crans (test port-ip)
|
|
REJECT pour le reste
|
|
TEST_FLOOD log puis drop des paquests avec bonne mac-ip (donc les floods)
|
|
|
|
table filter :
|
|
FORWARD (policy par defaut : ACCEPT)
|
|
1) passage par BLACKLIST
|
|
2) ce qui a pour source les serveurs de serveurs_crans est dirigé vers SERVEURS_VERS_EXT
|
|
3) ce qui a pour destination les serveurs de serveurs_crans est dirigé EXT_VERS_SERVEURS
|
|
4) tout ce qui vient de l'interface externe est dirigé vers EXT_VERS_CRANS
|
|
5) ce qui a pour source les serveurs de serveurs_crans est dirigé vers EXT_VERS_CRANS
|
|
|
|
BLACKLIST fitre des ip blacklistées (reject)
|
|
EXT_VERS_CRANS
|
|
ACCEPT pour les paquets vers les machines du crans (test port-ip)
|
|
REJECT pour le reste
|
|
EXT_VERS_SERVEURS et SERVEURS_VERS_EXT
|
|
ACCEPT pour bon mac-ip-port
|
|
REJECT pour le reste
|
|
"""
|
|
zone_serveur="138.231.136.0/28"
|
|
eth_ext = "eth2"
|
|
ports_default = { 'tcp_input' : ['22','1024:'],
|
|
'tcp_output': [':79','81:134','136','140:444','446:'],
|
|
'udp_input' : [''],
|
|
'udp_output': [':136','140:'] }
|
|
mac_wifi = '00:0c:f1:fa:f1:4b'
|
|
limit = " -m limit --limit 10/s --limit-burst 10 "
|
|
|
|
|
|
def __init__(self):
|
|
self.file_log=open("/var/log/fw.log","a")
|
|
|
|
def __del__(self):
|
|
self.file_log.close()
|
|
|
|
def iptables(self,cmd):
|
|
status,output=getstatusoutput(cmd)
|
|
if status:
|
|
raise IptablesError(cmd,status,output)
|
|
self.file_log.write(time.time+": "+cmd)
|
|
return output
|
|
|
|
def __base(self) :
|
|
""" Construction de PREROUTING et FORWARD"""
|
|
anim('\t Construction base firewall')
|
|
# table nat
|
|
for chaine in [ 'TEST_VIRUS' , 'EXT_VERS_SERVEURS', 'SERVEURS_VERS_EXT' , 'EXT_VERS_CRANS', 'TESTS_MAC-IP_FLOOD' , 'RESEAUX_NON_ROUTABLES_SRC', 'RESEAUX_NON_ROUTABLES_DST', 'TEST_FLOOD'] :
|
|
iptables('-t nat -N %s' % chaine)
|
|
|
|
iptables("-t nat -P PREROUTING ACCEPT")
|
|
iptables("-t nat -A PREROUTING -j TEST_VIRUS")
|
|
iptables("-t nat -A PREROUTING -j RESEAUX_NON_ROUTABLES_DST")
|
|
iptables("-t nat -A PREROUTING -i %s -j RESEAUX_NON_ROUTABLES_SRC" % self.eth_ext )
|
|
iptables("-t nat -A PREROUTING -d %s -j ACCEPT" % self.zone_serveur )
|
|
iptables("-t nat -A PREROUTING -s %s -j ACCEPT" % self.zone_serveur )
|
|
iptables("-t nat -A PREROUTING -i %s -j ACCPET" % self.eth_ext )
|
|
iptables("-t nat -A PREROUTING -j TESTS_MAC-IP_FLOOD")
|
|
|
|
# table filter
|
|
for chaine in [ 'BLACKLIST_OUTPUT', 'BLACKLIST_INPUT' ] :
|
|
iptables('-N %s' % chaine)
|
|
|
|
for reseau in config.NETs['all'] :
|
|
iptables("-A FORWARD -s %s -j BLACKLIST_DST" % reseau )
|
|
iptables("-A FORWARD -d %s -j BLACKLIST_SRC" % reseau )
|
|
iptables("-A FORWARD -d %s -j EXT_VERS_SERVEURS" % self.zone_serveur )
|
|
iptables("-A FORWARD -s %s -j SERVEURS_VERS_EXT" % self.zone_serveur )
|
|
iptables("-A FORWARD -i %s -j EXT_VERS_CRANS" % self.eth_ext )
|
|
|
|
def log_chaines(self) :
|
|
""" Construction des chaines de log (LOG_VIRUS et LOG_FLOOD) """
|
|
for filtre in [ 'VIRUS', 'FLOOD' ] :
|
|
# Vidage de la chaîne
|
|
iptables('-F LOG_%s' % filtre)
|
|
iptables('-t nat -A LOG_%s %s %s:' % (filtre, self.log_template, filtre.capitalize()) )
|
|
iptables('-t nat -A LOG_%s -j DROP' % filtre )
|
|
|
|
def reseaux_non_routables(self) :
|
|
""" Construction de RESEAUX_NON_ROUTABLES_{DST,SRC} """
|
|
self.anim = anim('\t Filtrage ip non routables',len(self.reseaux_non_routables))
|
|
for reseau in self.reseaux_non_routables :
|
|
iptables("-t nat -A RESEAUX_NON_ROUTABLES_DST -d %s -j DROP" % reseau)
|
|
iptables("-t nat -A RESEAUX_NON_ROUTABLES_SRC -s %s -j DROP" % reseau)
|
|
self.anim.cycle()
|
|
self.anim.reinit()
|
|
print OK
|
|
|
|
def test_virus(self) :
|
|
""" Construction de la chaîne TEST_VIRUS """
|
|
iptables('-t nat -F TEST_VIRUS')
|
|
self.anim = anim('\t Filtrage virus',len(self.ports_virus))
|
|
for port in self.ports_virus :
|
|
iptables('-t nat -A TEST_VIRUS -p tcp --dport %s -j LOG_VIRUS' % port)
|
|
self.anim.cycle()
|
|
self.anim.reinit()
|
|
print OK
|
|
|
|
|
|
def start(self):
|
|
"""
|
|
Construit le firewall
|
|
Pas d'arguments
|
|
"""
|
|
self.filtrage_mac()
|
|
self.create_forward()
|
|
self.blacklist()
|
|
self.create_adherents()
|
|
|
|
def stop(self):
|
|
"""
|
|
Arrête le firewall
|
|
Pas d'arguments
|
|
"""
|
|
print "Arrêt du firewall"
|
|
iptables("iptables -F")
|
|
iptables("iptables -t nat -F")
|
|
iptables("iptables -X")
|
|
|
|
def add_machines(self,machine):
|
|
__test_mac_ip_flood(machine)
|
|
__test_flood(machine)
|
|
__serveurs_vers_ext__(machine)
|
|
__ext_vers_serveurs__(machine)
|
|
__crans_vers_ext__(machine)
|
|
__ext_vers_crans__(machine)
|
|
|
|
def __serveurs_vers_ext(self,machine):
|
|
ip=machine.ip()
|
|
if AddrInNet(ip,self.zone_serveur):
|
|
for i in machine.portTCPout().split():
|
|
iptables("-t filter -A SERVEURS_VERS_EXT -d "+\
|
|
"%s -p tcp --dport %s -j ACCEPT"\
|
|
%(ip,i))
|
|
for i in machine.portUDPout().split():
|
|
iptables("-t filter -A SERVEURS_VERS_EXT-d "+\
|
|
"%s -p udp --dport %s -j ACCEPT"\
|
|
%(ip,i))
|
|
|
|
def __ext_vers_serveurs__(self,machine):
|
|
ip=machine.ip()
|
|
if AddrInNet(ip,self.zone_serveur):
|
|
for i in machine.portTCPin().split():
|
|
iptables("-t filter -I EXT_VERS_SERVEURS "+\
|
|
"-s %s -p tcp --dport %s -j ACCEPT"\
|
|
%(ip,i))
|
|
for i in machine.portUDPin().split():
|
|
iptables("-t filter -I EXT_VERS_SERVEURS "+\
|
|
"-s %s -p udp --dport %s -j ACCEPT"\
|
|
%(ip,i))
|
|
|
|
def __crans_vers_ext__(self,machine):
|
|
ip=machine.ip()
|
|
if not AddrInNet(ip,self.zone_serveur):
|
|
if machine.portTCPin():
|
|
for i in machine.portTCPin().split():
|
|
iptables("-t filter -I CRANS_VERS_EXT -d "+\
|
|
"%s -p tcp --dport %s -j ACCEPT"\
|
|
%(ip,i))
|
|
else:
|
|
for i in self.ports_default["tcp_input"]:
|
|
iptables("-I CRANS_VERS_EXT -p tcp --dport "+\
|
|
"%s -j ACCEPT"%i)
|
|
if machine.portUDPin():
|
|
for i in machine.portUDPin().split():
|
|
iptables("-t filter -I CRANS_VERS_EXT -d "+\
|
|
"%s -p udp --dport %s -j ACCEPT"\
|
|
%(ip,i))
|
|
else:
|
|
for i in self.ports_default["udp_input"]:
|
|
iptables("-I CRANS_VERS_EXT -p udp --dport "+\
|
|
"%s -j ACCEPT"%i)
|
|
|
|
def __ext_vers_crans__(self,machine):
|
|
ip=machine.ip()
|
|
if not AddrInNet(ip,self.zone_serveur):
|
|
if machine.portTCPout():
|
|
for i in machine.portTCPout().split():
|
|
iptables("-t filter -I EXT_VERS_CRANS -d "+\
|
|
"%s -p tcp --dport %s -j ACCEPT"\
|
|
%(ip,i))
|
|
else:
|
|
for i in self.ports_default["tcp_output"]:
|
|
iptables("-I EXT_VERS_CRANS -p tcp --dport "+\
|
|
"%s -j ACCEPT"%i)
|
|
if machine.portUDPout():
|
|
for i in machine.portUDPout().split():
|
|
iptables("-t filter -I EXT_VERS_CRANS -d "+\
|
|
"%s -p udp --dport %s -j ACCEPT"\
|
|
%(ip,i))
|
|
else:
|
|
for i in self.ports_default["udp_output"]:
|
|
iptables("-I EXT_VERS_CRANS -p udp --dport "+\
|
|
"%s -j ACCEPT"%i)
|
|
|
|
|
|
def __test_mac_ip_flood(machine):
|
|
ip=machine.ip()
|
|
mac=machine.mac()
|
|
if machine.ipsec():
|
|
iptables("-t nat -A PREROUTING -s "+\
|
|
"%s -m mac --mac-source %s %s -j ACCEPT"%(ip,self.mac_wifi,self.limit))
|
|
else:
|
|
iptables("-t nat -A PREROUTING -s "+\
|
|
"%s -m mac --mac-source %s %s -j ACCEPT"%(ip,mac,self.limit))
|
|
|
|
|
|
def __test_flood(machine):
|
|
ip=machine.ip()
|
|
mac=machine.mac()
|
|
if machine.ipsec():
|
|
iptables("-t nat -A PREROUTING -s "+\
|
|
"%s -m mac --mac-source %s -j LOG_FLOOD"%(ip,self.mac_wifi))
|
|
else:
|
|
iptables("-t nat -A PREROUTING -s "+\
|
|
"%s -m mac --mac-source %s -j LOG_FLOOD"%(ip,mac))
|
|
|
|
def del_entree(self,ip):
|
|
"""
|
|
Détruit une entrée dans le firewall
|
|
Note: Il faut *os.systemer lourdement* cette fonction.
|
|
Ce serait pas mal de factoriser par ici, mais de toute façon la
|
|
méthode ne me plaît pas du tout.
|
|
"""
|
|
try:
|
|
os.system("iptables -L -n > /tmp/firewall")
|
|
except:
|
|
print "Impossible de créer le fichier d'états /tmp/firewall"
|
|
exit()
|
|
chaines=[]
|
|
count=0
|
|
for line in fileinput.input('/tmp/firewall'):
|
|
count=count+1
|
|
if "Chain" in line:
|
|
tmp=line.split(' ')
|
|
chaine=tmp[1]
|
|
count=0
|
|
if ip in line:
|
|
count=count-1
|
|
iptables("iptables -D %s %i"%(chaine,count))
|
|
os.system("rm -f /tmp/firewall")
|
|
try:
|
|
os.system("iptables -t nat -L -n > /tmp/firewall")
|
|
except:
|
|
print "Impossible de créer le fichier d'états /tmp/firewall"
|
|
exit()
|
|
chaines=[]
|
|
count=0
|
|
for line in fileinput.input('/tmp/firewall'):
|
|
count=count+1
|
|
if "Chain" in line:
|
|
tmp=line.split(' ')
|
|
chaine=tmp[1]
|
|
count=0
|
|
if ip in line:
|
|
count=count-1
|
|
iptables("iptables -t nat -D %s %i"%(chaine,count))
|
|
os.system("rm -f /tmp/firewall")
|
|
|
|
|
|
def filtrage_mac(self):
|
|
"""
|
|
Crée tout le routage sur la chaîne PREROUTING
|
|
"""
|
|
db=crans_ldap()
|
|
search=db.search('host!=*.wifi.crans.org')['machine']
|
|
barre=anim("Filtrage mac-ip des machines fixes.",len(search))
|
|
for i in range(0,len(search)):
|
|
self.paire_macip(search[i].ip(),search[i].mac())
|
|
barre.cycle()
|
|
barre.reinit()
|
|
print OK
|
|
search=db.search('host=*.wifi.crans.org')['machine']
|
|
|
|
barre=anim("Filtrage mac-ip des machines wifi.",len(search))
|
|
for i in range(0,len(search)):
|
|
self.paire_macip(search[i].ip(),'00:0c:f1:fa:f1:4b')
|
|
barre.cycle()
|
|
barre.reinit()
|
|
print OK
|
|
|
|
iptables("iptables -t nat -A PREROUTING -i %s -s \\!"%int_crans+\
|
|
" 138.231.136.0/21 -j ACCEPT")
|
|
iptables("iptables -t nat -A PREROUTING -i %s -s \\!"%int_crans+\
|
|
" 138.231.148.0/22 -j ACCEPT")
|
|
for i in reseaux_non_routables:
|
|
iptables("iptables -t nat -A PREROUTING -i %s -s %s"%(int_crans,i)+\
|
|
" -m limit --limit %s --limit-burst %s"%(loglimit,logburst)+\
|
|
" -j LOG --log-level %s --log-prefix %s"%\
|
|
(loglevel,logprefix_macip))
|
|
iptables("iptables -t nat -A PREROUTING -i %s -s %s -j DROP"%\
|
|
(int_crans,i))
|
|
iptables("iptables -t nat -A PREROUTING -i %s -d %s"%(int_crans,i)+\
|
|
" -m limit --limit %s --limit-burst %s"%(loglimit,logburst)+\
|
|
" -j LOG --log-level %s --log-prefix %s"%\
|
|
(loglevel,logprefix_macip))
|
|
iptables("iptables -t nat -A PREROUTING -i %s -d %s -j DROP"%\
|
|
(int_crans,i))
|
|
iptables("iptables -t nat -A PREROUTING -i %s -p tcp "%int_crans+\
|
|
" -m limit --limit %s --limit-burst %s"%(loglimit,logburst)+\
|
|
" -j LOG --log-level %s --log-prefix %s"%\
|
|
(loglevel,logprefix_macip))
|
|
iptables("iptables -t nat -A PREROUTING -i %s -p tcp"%int_crans+\
|
|
" -j DROP")
|
|
iptables("iptables -t nat -A PREROUTING -i %s -p udp"%int_crans+\
|
|
" -m limit --limit %s --limit-burst %s"%(loglimit,logburst)+\
|
|
" -j LOG --log-level %s --log-prefix %s"%\
|
|
(loglevel,logprefix_macip))
|
|
iptables("iptables -t nat -A PREROUTING -i %s -p udp"%int_crans+\
|
|
" -j DROP")
|
|
|
|
|
|
def blacklist(self):
|
|
"""
|
|
Bloque les adhérents blacklistés
|
|
"""
|
|
|
|
db=crans_ldap()
|
|
blacklist=[]
|
|
search=db.search('blacklist=*&paiement=%s'%ann_scol)
|
|
for entite in search['adherent']+\
|
|
search['club']+search['machine']:
|
|
if 'upload' in entite.blacklist_actif():
|
|
if search.__class__==machine:
|
|
blacklist+=[entite]
|
|
else:
|
|
blacklist+=entite.machines()
|
|
for instance_machine in blacklist:
|
|
iptables("iptables -A BLACKLIST_INPUT -d %s"%\
|
|
instance_machine.ip().encode("iso-8859-15")+\
|
|
"-m limit --limit %s --limit-burst %s"%(loglimit,logburst)+\
|
|
" -j LOG --log-level %s --log-prefix_macip %s"%\
|
|
(loglevel,logprefix_blacklist))
|
|
iptables("iptables -A BLACKLIST_INPUT -d %s -j REJECT"%\
|
|
instance_machine.ip())
|
|
iptables("iptables -A BLACKLIST_OUTPUT -s %s"%\
|
|
instance_machine.ip().encode("iso-8859-15")+\
|
|
"-m limit --limit %s --limit-burst %s"%(loglimit,logburst)+\
|
|
" -j LOG --log-level %s --log-prefix_macip %s"%\
|
|
(loglevel,logprefix_blacklist))
|
|
iptables("iptables -A BLACKLIST_OUTPUT -s %s -j REJECT"%\
|
|
instance_machine.ip())
|
|
iptables("iptables -A BLACKLIST_INPUT -j EXT_VERS_CRANS")
|
|
iptables("iptables -A BLACKLIST_OUTPUT -j CRANS_VERS_EXT")
|
|
|
|
|
|
def create_adherents(self):
|
|
"""
|
|
Crée toutes les règles relatives aux adhérents ayant des règles
|
|
spéciales
|
|
"""
|
|
iptables("iptables -N ADHERENTS_OUTPUT")
|
|
iptables("iptables -N ADHERENTS_INPUT")
|
|
|
|
iptables("iptables -A ADHERENTS_INPUT -m state --state "+\
|
|
"RELATED -j ACCEPT")
|
|
iptables("iptables -A ADHERENTS_OUTPUT -m state --state "+\
|
|
"RELATED -j ACCEPT")
|
|
iptables("iptables -A ADHERENTS_INPUT -m state --state "+\
|
|
"ESTABLISHED -m limit --limit-burst "+\
|
|
"%s -j ACCEPT"%limite_connexion)
|
|
iptables("iptables -A ADHERENTS_OUTPUT -m state --state "+\
|
|
"ESTABLISHED -m limit --limit-burst "+\
|
|
"%s -j ACCEPT"%limite_connexion)
|
|
iptables("iptables -A DEFAULT_INPUT -j ADHERENTS_INPUT")
|
|
iptables("iptables -A DEFAULT_OUTPUT -j ADHERENTS_OUTPUT")
|
|
|
|
db=crans_ldap()
|
|
search=db.search('host=*.crans.org & portTCPin=*')['machine']
|
|
for champ in search:
|
|
ports=champ.portTCPin()
|
|
for j in ports.split(' '):
|
|
iptables("iptables -A ADHERENTS_INPUT -d %s"%champ.ip()+\
|
|
" -p tcp --dport %s -j ACCEPT"%j)
|
|
search=db.search('host=*.crans.org & portTCPout=*')['machine']
|
|
for champ in search:
|
|
ports=champ.portTCPout()
|
|
for j in ports.split(' '):
|
|
iptables("iptables -A ADHERENTS_OUTPUT -d %s"%champ.ip()+\
|
|
" -p tcp --dport %s -j ACCEPT"%j)
|
|
search=db.search('host=*.crans.org & portUDPin=*')['machine']
|
|
for champ in search:
|
|
ports=champ.portUDPin()
|
|
for j in ports.split(' '):
|
|
iptables("iptables -A ADHERENTS_INPUT -d %s"%champ.ip()+\
|
|
" -p udp --dport %s -j ACCEPT"%j)
|
|
search=db.search('host=*.crans.org & portUDPin=*')['machine']
|
|
for champ in search:
|
|
ports=champ.portUDPout()
|
|
for j in ports.split(' '):
|
|
iptables("iptables -A ADHERENTS_OUTPUT -d %s"%champ.ip()+\
|
|
" -p udp --dport %s -j ACCEPT"%j)
|
|
iptables("iptables -A ADHERENTS_INPUT"+\
|
|
" -m limit --limit %s --limit-burst %s"%(loglimit,logburst)+\
|
|
" -j LOG --log-level %s --log-prefix %s"%\
|
|
(loglevel,logprefix_adherents))
|
|
iptables("iptables -A ADHERENTS_INPUT -j REJECT")
|
|
iptables("iptables -A ADHERENTS_OUTPUT"+\
|
|
" -m limit --limit %s --limit-burst %s"%(loglimit,logburst)+\
|
|
" -j LOG --log-level %s --log-prefix %s"%\
|
|
(loglevel,logprefix_adherents))
|
|
iptables("iptables -A ADHERENTS_OUTPUT -j REJECT")
|
|
|
|
|