komaz.py 34.4 KB
Newer Older
1
#!/usr/bin/env python
2
# -*- mode: python; coding: utf-8 -*-
3 4 5 6 7 8 9
import utils
import base

from utils import pretty_print, OK, anim
from base import dev

class firewall(base.firewall_routeur):
Valentin Samir's avatar
Docs  
Valentin Samir committed
10
    """Pare-feu du serveur komaz, routeur principal de l'association"""
11 12 13 14 15 16 17 18 19 20 21
    def __init__(self):
        super(self.__class__, self).__init__()

        self.reloadable.update({
            'log_all' : self.log_all,
            'admin_vlan' : self.admin_vlan,
            'clamp_mss' : self.clamp_mss,
            'ingress_filtering' : self.ingress_filtering,
            'ssh_on_https' : self.ssh_on_https,
            'connexion_secours' : self.connexion_secours,
            'connexion_appartement' : self.connexion_appartement,
22
            'connexion_wififederez' : self.connexion_wififederez,
23 24 25 26 27 28
            'blacklist_soft' : self.blacklist_soft,
            'blacklist_upload' : self.blacklist_upload,
            'reseaux_non_routable' : self.reseaux_non_routable,
            'filtrage_ports' : self.filtrage_ports,
            'limitation_debit' : self.limitation_debit,
            'limit_ssh_connexion' : self.limit_ssh_connexion,
29
            'limit_connexion' : self.limit_connexion,
30
            'tunnel_6in4' : self.tunnel_6in4,
31
            'challenge_letsencrypt': self.challenge_letsencrypt,
32 33 34 35 36 37
        })

        self.use_ipset.extend([self.blacklist_soft, self.blacklist_upload, self.reseaux_non_routable])
        self.use_tc.extend([self.limitation_debit])

        self.ipset['reseaux_non_routable'] = {
38 39
            'deny' : base.Ipset("RESEAUX-NON-ROUTABLE-DENY", "hash:net"),
            'allow' :  base.Ipset("RESEAUX-NON-ROUTABLE-ALLOW", "hash:net"),
40 41 42
        }

        self.ipset['blacklist'].update({
43 44
            'soft' : base.Ipset("BLACKLIST-SOFT", "hash:ip"),
            'upload' : base.Ipset("BLACKLIST-UPLOAD", "hash:ip"),
45 46
        })

47
        # Portail captif/blacklist soft: ipset des gens ayant cliqué pour continuer à naviguer
48
        self.ipset['confirmation'] = base.Ipset("CONFIRMATION", "hash:ip", "timeout 3600")
49

50 51 52
        # Ouvertures de ports temporaires
        self.ipset['ip_port_tmp'] = base.Ipset("IP-PORT-TMP", "hash:ip,port", "timeout 3600")

53
    def blacklist_maj(self, ips):
Valentin Samir's avatar
Docs  
Valentin Samir committed
54
        """Mise à jour des blacklistes"""
55 56 57 58
        self.blacklist_hard_maj(ips)
        self.blacklist_soft_maj(ips)
        self.blacklist_upload_maj(ips)

59 60 61 62 63
    def blacklists(self, table=None, fill_ipset=False, apply=False):
        self.blacklist_hard(table=table, fill_ipset=fill_ipset, apply=apply)
        self.blacklist_soft(table=table, fill_ipset=fill_ipset, apply=apply)
        self.blacklist_upload(table=table, fill_ipset=fill_ipset, apply=apply)

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
    def raw_table(self):
        """Génère les règles pour la table ``raw`` et remplis les chaines de la table"""
        table = 'raw'

        chain = 'PREROUTING'
        self.add(table, chain, '-d 225.0.0.50 -j DROP')
        return


    def mangle_table(self):
        table = 'mangle'
        super(self.__class__, self).mangle_table()

        chain = 'PREROUTING'
        self.add(table, chain, '-j %s' % self.connexion_secours(table))
        self.add(table, chain, '-p tcp -j CONNMARK --restore-mark')

        chain = 'POSTROUTING'
82
        self.add(table, chain, '-j %s' % self.log_all(table))
83
        self.add(table, chain, '-j %s' % self.clamp_mss(table))
84
        self.add(table,chain, '-j %s' % self.limitation_debit(table, run_tc=True))
85 86 87 88 89 90 91 92 93
        self.add(table, chain, '-j %s' % self.blacklist_upload(table, fill_ipset=True))
        return

    def filter_table(self):
        table = 'filter'
        super(self.__class__, self).filter_table()

        mac_ip_chain = self.test_mac_ip()
        blacklist_hard_chain = self.blacklist_hard()
94
        blacklist_soft_chain = self.blacklist_soft(table, fill_ipset=True)
95 96 97 98 99 100 101

        chain = 'INPUT'
        self.flush(table, chain)
        self.add(table, chain, '-i lo -j ACCEPT')
        self.add(table, chain, '-p icmp -j ACCEPT')
        self.add(table, chain, '-m state --state RELATED,ESTABLISHED -j ACCEPT')
        self.add(table, chain, '-j %s' % blacklist_soft_chain)
102
        self.add(table, chain, '-j %s' % self.limit_ssh_connexion(table))
103 104 105 106 107 108 109
        for net in base.config.NETs['all'] + base.config.NETs['adm'] + base.config.NETs['personnel-ens']:
            self.add(table, chain, '-s %s -j %s' % (net, mac_ip_chain))
        self.add(table, chain, '-j %s' % blacklist_hard_chain)

        chain = 'FORWARD'
        self.flush(table, chain)
        self.add(table, chain, '-i lo -j ACCEPT')
110
        self.add(table, chain, '-j %s' % self.reseaux_non_routable(table, fill_ipset=True))
111 112 113 114 115 116 117 118 119 120 121
        self.add(table, chain, '-p icmp -j ACCEPT')
        self.add(table, chain, '-j %s' % self.admin_vlan(table))
        self.add(table, chain, '-j %s' % blacklist_soft_chain)
        self.add(table, chain, '-i %s -j %s' % (dev['out'], blacklist_hard_chain))
        self.add(table, chain, '-o %s -j %s' % (dev['out'], blacklist_hard_chain))
        self.add(table, chain, '-m state --state RELATED,ESTABLISHED -j ACCEPT')
        self.add(table, chain, '-j %s' % self.tunnel_6in4(table))
        for net in base.config.NETs['all'] + base.config.NETs['adm'] + base.config.NETs['personnel-ens']:
            self.add(table, chain, '-s %s -j %s' % (net, mac_ip_chain))
        self.add(table, chain, '-j %s' % self.connexion_secours(table))
        self.add(table, chain, '-j %s' % self.connexion_appartement(table))
122
        self.add(table, chain, '-j %s' % self.connexion_wififederez(table))
123
        self.add(table, chain, '-j %s' % self.ingress_filtering(table))
124
        self.add(table, chain, '-j %s' % self.limit_ssh_connexion(table, ttl=30, counter_name="SSH2"))
125 126
        self.add(table, chain, '-o %s -j %s' % (dev['out'], self.limit_connexion(table, ip_track='srcip')))
	self.add(table, chain, '-i %s -d %s -j %s' % ( dev['out'], ','.join(base.config.NETs['adherents'] + base.config.NETs['wifi-adh'] + base.config.NETs['personnel-ens']), self.limit_connexion(table, ip_track='dstip')))
127 128 129 130 131 132 133 134 135 136
        self.add(table, chain, '-i %s -j %s' % (dev['out'], self.filtrage_ports(table)))
        self.add(table, chain, '-o %s -j %s' % (dev['out'], self.filtrage_ports(table)))
        return

    def nat_table(self):
        table = 'nat'
        super(self.__class__, self).nat_table()

        chain = 'PREROUTING'
        self.add(table, chain, '-j %s' % self.ssh_on_https(table))
137
        self.add(table, chain, '-j %s' % self.challenge_letsencrypt(table))
138 139
        self.add(table, chain, '-j %s' % self.connexion_secours(table))
        self.add(table, chain, '-j %s' % self.blacklist_soft(table))
140
        self.add(table, chain, '-j %s' % self.blacklist_hard(table))
141 142

        chain = 'POSTROUTING'
143
        self.add(table, chain, '-j %s' % self.connexion_wififederez(table))
144 145 146 147 148 149
        self.add(table, chain, '-j %s' % self.connexion_appartement(table))
        return

    def tunnel_6in4(self, table=None, apply=False):
        chain = 'TUNNEL_IPV6'

150
        tunnels_ipv6 = [ ('216.66.84.42', '138.231.136.12'), ('216.66.84.42','138.231.136.164'), ('185.132.72.1','138.231.141.10') ]
151 152 153 154 155 156 157 158 159 160 161 162

        if table == 'filter':
            pretty_print(table, chain)
            for sideA, sideB in tunnels_ipv6:
                self.add(table, chain, '--proto 41 -s %s -d %s -j ACCEPT' % (sideA, sideB))
                self.add(table, chain, '--proto 41 -s %s -d %s -j ACCEPT' % (sideB, sideA))
            print OK

        if apply:
            self.apply(table, chain)
        return chain

163
    def limit_ssh_connexion(self, table=None, apply=False, ttl=120, counter_name="SSH"):
164
        chain = 'LIMIT-%s-CONNEXION' % (counter_name,)
165 166 167

        if table == 'filter':
            pretty_print(table, chain)
168 169
            self.add(table, chain, '-i %s -p tcp --dport ssh -m state --state NEW -m recent --name %s --set' % (dev['out'], counter_name))
            self.add(table, chain, '-i %s -p tcp --dport ssh -m state --state NEW -m recent --name %s --update --seconds %s --hitcount 10 --rttl -j DROP' % (dev['out'], counter_name, ttl))
170 171 172 173 174 175
            print OK

        if apply:
            self.apply(table, chain)
        return chain

176 177
    def limit_connexion(self, table=None, apply=False, ip_track='srcip'):
        chain = 'LIMIT-CONNEXION-%s' % ip_track.upper()
178 179 180

        if table == 'filter':
            pretty_print(table, chain)
181 182 183 184 185 186 187 188 189
            self.add(table, chain, '-m hashlimit -p udp --hashlimit-name LIMIT_UDP_%s_CONNEXION --hashlimit-mode %s --hashlimit-upto 400/sec --hashlimit-burst 800 -j RETURN' % (ip_track.upper(), ip_track))
            self.add(table, chain,'-m hashlimit -p udp --hashlimit-name LIMIT_UDP_%s_CONNEXION_LOG --hashlimit-mode %s --hashlimit-upto 5/hour -j LOG --log-prefix "CONNEXION_LIMIT_UDP_%s "' % (ip_track.upper(), ip_track, ip_track.upper()))
            self.add(table, chain, '-p udp -j REJECT')
            self.add(table, chain, '-m hashlimit -p tcp -m state --state NEW --hashlimit-name LIMIT_TCP_%s_CONNEXION --hashlimit-mode %s --hashlimit-upto 2000/min --hashlimit-burst 4000 -j RETURN' % (ip_track.upper(), ip_track))
            self.add(table, chain,'-m hashlimit -p tcp -m state --state NEW --hashlimit-name LIMIT_TCP_%s_CONNEXION_LOG --hashlimit-mode %s --hashlimit-upto 5/hour -j LOG --log-prefix "CONNEXION_LIMIT_TCP_%s "' % (ip_track.upper(), ip_track, ip_track.upper()))
            self.add(table, chain, '-p tcp -m state --state NEW -j REJECT')
            self.add(table, chain, '-m hashlimit --hashlimit-name LIMIT_OTHER_%s_CONNEXION --hashlimit-mode %s --hashlimit-upto 400/sec --hashlimit-burst 800 -j RETURN' % (ip_track.upper(), ip_track))
            self.add(table, chain,'-m hashlimit --hashlimit-name LIMIT_OTHER_%s_CONNEXION_LOG --hashlimit-mode %s --hashlimit-upto 5/hour -j LOG --log-prefix "CONNEXION_LIMIT "' % (ip_track.upper(), ip_track))
            self.add(table, chain, '-j REJECT')
190 191 192 193 194 195
            print OK

        if apply:
            self.apply(table, chain)
        return chain

196 197 198 199
    def test_mac_ip(self, table=None, fill_ipset=False, apply=False):
        chain = super(self.__class__, self).test_mac_ip()

        if table == 'filter':
Pierre-Elliott Bécue's avatar
Pierre-Elliott Bécue committed
200
            for key in ['out', 'tun-soyouz' ]:
201 202 203 204 205 206 207 208 209 210 211
                self.add(table, chain, '-i %s -j RETURN' % dev[key])

        return super(self.__class__, self).test_mac_ip(table, fill_ipset, apply)


    def log_all(self, table=None, apply=False):
        chain = 'LOG_ALL'

        if table == 'mangle':
            pretty_print(table, chain)
            for device in dev.values():
212
                self.add(table, chain, '-o %s -m state --state NEW -j LOG --log-prefix "LOG_ALL "' % device)
213 214 215 216 217 218 219 220 221 222 223 224
            print OK

        if apply:
            self.apply(table, chain)
        return chain

    def admin_vlan(self, table=None, apply=False):
        chain = 'VLAN-ADM'

        if table == 'filter':
            pretty_print(table, chain)
            for net in base.config.NETs['adm']:
Pierre-Elliott Bécue's avatar
Pierre-Elliott Bécue committed
225 226
                self.add(table, chain, '-o %s -s %s -j ACCEPT' % (dev['tun-soyouz'], net))
                self.add(table, chain, '-i %s -d %s -j ACCEPT' % (dev['tun-soyouz'], net))
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
                self.add(table, chain, '-d %s -j REJECT' % net)
            print OK

        if apply:
            self.apply(table, chain)
        return chain

    def qos(self, table=None, apply=False):
        return

    def clamp_mss(self, table=None, apply=False):
        """Force la MSS (Max Segment Size) TCP à rentrer dans la MTU (Max Transfert Unit)"""
        chain = 'CLAMP-MSS'
        if table == 'mangle':
            pretty_print(table, chain)

243 244 245 246 247
            # Problèmes de mss sur ratp.fr (1455 au lieu de 1456)
            # Cf mail nounou du 23/06/2016
            for ip in ['195.200.228.10', '195.200.228.170']: # ratp.fr
                self.add(table, chain, '-p tcp --dst %s --tcp-flags SYN,RST SYN -j TCPMSS --set-mss 1455' % ip)

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
            self.add(table, chain, '-p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu')
            print OK

        if apply:
            self.apply(table, chain)
        return chain

    def ingress_filtering(self, table=None, apply=False):
        """Pour ne pas router les paquêtes n'appartenant pas à notre plage ip voulant sortir de notre réseau
        et empêcher certain type de spoof (cf http://travaux.ovh.net/?do=details&id=5183)"""
        chain = 'INGRESS_FILTERING'
        if table == 'filter':
            pretty_print(table, chain)

            for net in base.config.NETs['all']:
                self.add(table, chain, '-o %s -s %s -j RETURN' % (dev['out'], net))
            self.add(table, chain, '-o %s -j LOG --log-prefix BAD_ROUTE' % dev['out'])
            self.add(table, chain, '-o %s -j DROP' % dev['out'])
            for net_d in base.config.NETs['all']:
                for net_s in base.config.NETs['all']:
                    self.add(table, chain,'-i %s ! -s %s -d %s -j RETURN' % (dev['out'], net_s, net_d))
            self.add(table, chain,'-i %s -j LOG --log-prefix BAD_SRC' % dev['out'])
            self.add(table, chain,'-i %s -j DROP' % dev['out'])
            print OK

        if apply:
            self.apply(table, chain)
        return chain

    def ssh_on_https(self, table=None, apply=False):
        """Pour faire fonctionner ssh2.crans.org"""
        chain = 'SSH2'

        if table == 'nat':
            pretty_print(table, chain)
            self.add(table, chain, '-p tcp -d 138.231.136.2 --dport 22 -j DNAT --to-destination 138.231.136.1:22')    # redirection du ssh vers zamok
284
            self.add(table, chain, '-p tcp -d 138.231.136.2 --dport 80 -j DNAT --to-destination 138.231.136.1:81')    # redirection du ssh vers zamok a travers httptunnel
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
            self.add(table, chain, '-p tcp -d 138.231.136.2 --dport 443 -j DNAT --to-destination 138.231.136.1:22')    # redirection du ssh vers zamok (pour passer dans un proxy, avec corkscrew)
            print OK

        if apply:
            self.apply(table, chain)
        return chain

    def connexion_secours(self, table=None, apply=False):
        """Redirige les paquets vers un proxy lorsqu'on est en connexion de secours"""
        chain = 'CONNEXION-SECOURS'

        if table == 'mangle':
            pretty_print(table, chain)
            self.add(table, chain, '-p tcp -s 138.231.136.0/16 ! -d 138.231.136.0/16 --destination-port 80 -m condition --condition secours -j MARK --set-mark %s' % (base.config.firewall.mark['secours']))
            self.add(table, chain, '-m mark --mark %s -j ACCEPT' % base.config.firewall.mark['secours'])
            print OK

        if table == 'nat':
            pretty_print(table, chain)
            self.add(table, chain, '-p tcp -m mark --mark %s -j DNAT --to-destination 10.231.136.4:3129' % base.config.firewall.mark['secours'] )
            print OK

        if table == 'filter':
            pretty_print(table, chain)
            self.add(table, chain, '-p tcp -s 138.231.136.0/16 ! -d 138.231.136.0/16 --destination-port 443 -m condition --condition secours -j REJECT')
            self.add(table, chain, '-m mark --mark %s -j ACCEPT' % base.config.firewall.mark['secours'])
            print OK

        if apply:
            self.apply(table, chain)
        return chain

317
    def challenge_letsencrypt(self, table=None, apply=False):
Pierre-Elliott Bécue's avatar
Pierre-Elliott Bécue committed
318
        """PNAT des request de challenge letsencrypt vers bakdaur ou frontdaur"""
319 320 321 322 323 324 325 326 327
        chain = "CHALLENGE-LESENCRYPT"

        if table == 'nat':
            pretty_print(table, chain)

            bakdaur = self.conn.search(u"host=bakdaur.crans.org")[0]
            frontdaur = self.conn.search(u"host=frontdaur.crans.org")[0]

            self.add(table, chain, '-m condition ! --condition challenge-letsencrypt -j RETURN')
328
            for net in (base.config.NETs['serveurs'] + base.config.NETs['wifi-serveurs']):
329 330
                self.add(table, chain, '-p tcp -d %s --dport 80 -m condition --condition challenge-letsencrypt-bakdaur -j DNAT --to-destination %s:81' % (net, bakdaur['ipHostNumber'][0]))
                self.add(table, chain, '-p tcp -d %s --dport 80 -m condition ! --condition challenge-letsencrypt-bakdaur -j DNAT --to-destination %s:81' % (net, frontdaur['ipHostNumber'][0]))
331 332 333 334 335 336
            print OK

        if apply:
            self.apply(table, chain)
        return chain

337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
    def connexion_appartement(self, table=None, apply=False):
        """PNAT les appartements derrière appartement.crans.org"""
        chain = 'CONNEXION-APPARTEMENT'

        if table == 'nat':
            pretty_print(table, chain)
            for dev_key in ['out', 'fil', 'wifi']:
                for net in base.config.NETs['personnel-ens']:
                    self.add(table, chain, '-o %s -s %s -j SNAT --to 138.231.136.44' % (dev[dev_key], net))
            print OK

        if table == 'filter':
            pretty_print(table, chain)
            for net in base.config.NETs['personnel-ens']:
                self.add(table, chain, '-s %s -j ACCEPT' % net)
                self.add(table, chain, '-d %s -j ACCEPT' % net)
            print OK

        if apply:
            self.apply(table, chain)
        return chain

359 360 361
    def connexion_wififederez(self, table=None, apply=False):
        """PNAT le vlan wififederez derrière wififederez.crans.org"""
        chain = 'CONNEXION-WIFIFEDEREZ'
362 363

        if table == 'nat':
364 365 366 367 368
            pretty_print(table, chain)
            for dev_key in ['out', 'fil', 'wifi']:
                for net in base.config.NETs['federez']:
                    self.add(table, chain, '-o %s -s %s -j SNAT --to 138.231.136.77' % (dev[dev_key], net))
            print OK
369

370
        if table == 'filter':
371
            pretty_print(table, chain)
372 373 374 375
            for net in base.config.NETs['federez']:
                self.add(table, chain, '-s %s -j ACCEPT' % net)
                self.add(table, chain, '-d %s -j ACCEPT' % net)
            print OK
376

377 378 379 380 381
        if apply:
            self.apply(table, chain)
        return chain


382 383 384 385 386
    def blacklist_soft_maj(self, ip_list):
        self.blacklist_soft(fill_ipset=True)
#        for ip in ip_list:
#            machine = self.conn.search(u"ipHostNumber=%s" % ip)
#            # Est-ce qu'il y a des blacklists soft parmis les blacklists de la machine
387
#            if machine and set([bl['type'] for bl in machine[0].blacklist_actif() ]).intersection(base.config.blacklist_sanctions_soft):
388 389 390 391 392 393 394 395 396 397 398 399
#                try: self.ipset['blacklist']['soft'].add(ip)
#                except IpsetError: pass
#            else:
#                try: self.ipset['blacklist']['soft'].delete(ip)
#                except IpsetError: pass

    def blacklist_soft(self, table=None, fill_ipset=False, apply=False):
        """Redirige les gens blacklisté vers le portail captif"""
        chain = 'BLACKLIST_SOFT'

        if fill_ipset:
            # On récupère la liste de toutes les ips blacklistés soft
400
            bl_soft_ips = self.blacklisted_ips(base.config.blacklist_sanctions_soft)
401
            anim('\tRestoration de l\'ipset %s' % self.ipset['blacklist']['soft'])
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
            self.ipset['blacklist']['soft'].restore(bl_soft_ips)
            print OK

        if table == 'filter':
            pretty_print(table, chain)
            self.add(table, chain, '-p tcp --dport 80 -m set --match-set %s src -j ACCEPT' % self.ipset['blacklist']['soft'] )
            self.add(table, chain, '-p tcp --sport 80 -m set --match-set %s dst -j ACCEPT' % self.ipset['blacklist']['soft'] )
            self.add(table, chain, '-p tcp -d 10.231.136.4 --dport 3128 -m set --match-set %s src -j ACCEPT' % self.ipset['blacklist']['soft'] )
            self.add(table, chain, '-p tcp -s 10.231.136.4 --sport 3128 -m set --match-set %s dst -j ACCEPT' % self.ipset['blacklist']['soft'] )
            print OK

        if table == 'nat':
            pretty_print(table, chain)
            for net in base.config.NETs['all']:
                self.add(table, chain, '-d %s -j RETURN' % net)
417
            self.add(table, chain, '-p tcp --dport 80 -m set --match-set %s src -j RETURN' % self.ipset['confirmation'] ) # Les gens qui ont cliqué -> fine !
418 419 420 421 422 423 424
            self.add(table, chain, '-p tcp --dport 80 -m set --match-set %s src -j DNAT --to-destination 10.231.136.4:3128' % self.ipset['blacklist']['soft'] )
            print OK

        if apply:
            self.apply(table, chain)
        return chain

425 426 427 428 429 430
    def blacklist_hard(self, table=None, fill_ipset=False, apply=False):
        """Bloque tout, sauf le 80 pour afficher le portail captif"""
        chain = 'BLACKLIST_HARD'

        if fill_ipset:
            # On récupère la liste de toutes les ips blacklistés hard
431
            bl_hard_ips = self.blacklisted_ips(base.config.blacklist_sanctions)
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
            anim('\tRestoration de l\'ipset %s' % self.ipset['blacklist']['hard'])
            self.ipset['blacklist']['hard'].restore(bl_hard_ips)
            print OK

        if table == 'filter':
            pretty_print(table, chain)
            # Same as blacklist_soft: autorise le port 80 et 3128 vers soi-même
            self.add(table, chain, '-p tcp --dport 80 -m set --match-set %s src -j ACCEPT' % self.ipset['blacklist']['hard'] )
            self.add(table, chain, '-p tcp --sport 80 -m set --match-set %s dst -j ACCEPT' % self.ipset['blacklist']['hard'] )
            self.add(table, chain, '-p tcp -d 10.231.136.4 --dport 3128 -m set --match-set %s src -j ACCEPT' % self.ipset['blacklist']['hard'] )
            self.add(table, chain, '-p tcp -s 10.231.136.4 --sport 3128 -m set --match-set %s dst -j ACCEPT' % self.ipset['blacklist']['hard'] )
            # Mais on continue en refusant le reste
            self.add(table, chain, '-m set --match-set %s src -j REJECT' % self.ipset['blacklist']['hard'] )
            self.add(table, chain, '-m set --match-set %s dst -j REJECT' % self.ipset['blacklist']['hard'] )
            print OK

        if table == 'nat':
            pretty_print(table, chain)
            for net in base.config.NETs['all']:
                self.add(table, chain, '-d %s -j RETURN' % net)
            self.add(table, chain, '-p tcp --dport 80 -m set --match-set %s src -j RETURN' % self.ipset['confirmation'] ) # Les gens qui ont cliqué -> fine !
            self.add(table, chain, '-p tcp --dport 80 -m set --match-set %s src -j DNAT --to-destination 10.231.136.4:3128' % self.ipset['blacklist']['hard'] )
            print OK

        if apply:
            self.apply(table, chain)
        return chain

460 461 462 463 464
    def blacklist_upload_maj(self, ip_list):
        self.blacklist_upload(fill_ipset=True)
#        for ip in ip_list:
#            machine = self.conn.search(u"ipHostNumber=%s" % ip)
#            # Est-ce qu'il y a des blacklists pour upload parmis les blacklists de la machine
465
#            if machine and set([bl['type'] for bl in machine[0].blacklist_actif() ]).intersection(blacklist_bridage_upload):
466 467 468 469 470 471 472 473 474 475 476 477
#                try: self.ipset['blacklist']['upload'].add(ip)
#                except IpsetError: pass
#            else:
#                try: self.ipset['blacklist']['upload'].delete(ip)
#                except IpsetError: pass

    def blacklist_upload(self, table=None, fill_ipset=False, apply=False):
        """Les gens blacklistés ne sont plus prioritaires (classe de qos commune)"""
        chain = 'BLACKLIST_UPLOAD'

        if fill_ipset:
            # On récupère la liste de toutes les ips blacklistés pour upload
478
            bl_upload_ips = self.blacklisted_ips(base.config.blacklist_bridage_upload)
479
            anim('\tRestoration de l\'ipset %s' % self.ipset['blacklist']['upload'])
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
            self.ipset['blacklist']['upload'].restore(bl_upload_ips)
            print OK

        if table == 'mangle':
            pretty_print(table, chain)
            # Classification pour les blacklists upload
            self.add(table, chain, '-o %s -m set --match-set %s src -j CLASSIFY --set-class 1:11' % (dev['out'], self.ipset['blacklist']['upload']))

            print OK

        if apply:
            self.apply(table, chain)
        return chain

    def reseaux_non_routable(self, table=None, fill_ipset=False, apply=False):
        """Bloque les réseaux non routables autres que ceux utilisés par le crans"""
        chain = 'RESEAUX_NON_ROUTABLES'

        if fill_ipset:
            anim('\tRestoration de l\'ipset reseaux_non_routable')
            allowed = [ net for nets in base.config.NETs.values() for net in nets if utils.NetInNets(net, base.config.firewall.reseaux_non_routables) ]
            self.ipset['reseaux_non_routable']['allow'].restore(allowed)
            self.ipset['reseaux_non_routable']['deny'].restore(base.config.firewall.reseaux_non_routables)
            print OK

        if table == 'filter':
            pretty_print(table, chain)
            self.add(table, chain, '-m set --match-set %s src -j RETURN' %  self.ipset['reseaux_non_routable']['allow'])
            self.add(table, chain, '-m set --match-set %s dst -j RETURN' %  self.ipset['reseaux_non_routable']['allow'])
            self.add(table, chain, '-m set --match-set %s src -j DROP' %  self.ipset['reseaux_non_routable']['deny'])
            self.add(table, chain, '-m set --match-set %s dst -j DROP' %  self.ipset['reseaux_non_routable']['deny'])
            print OK

        if apply:
            self.apply(table, chain)
        return chain

    def filtrage_ports_maj(self, ip_lists):
        self.filtrage_ports('filter', apply=True)

    def filtrage_ports(self, table=None, apply=False):
        """Ouvre les ports vers et depuis les machines du réseau crans"""
        chain = 'FILTRAGE-PORTS'

        def format_port(port):
            port = str(port)
            if port.endswith(':'):
                port = '%s65535' % port
            if port.startswith(':'):
                port = '0%s' % port
            return port

        def add_ports(ip, machine, proto, sens):
            self.add(
                table,
                chain,
                '-p %s -%s %s -m multiport --dports %s -j RETURN' % (
                        proto,
                        (sens=='out' and 's') or (sens == 'in' and 'd'),
                        ip,
                        ','.join( format_port(port) for port in machine['port%s%s' % (proto.upper(), sens)])
                )
            )

        if table == 'filter':
            pretty_print(table, chain)
546
            self.add(table, chain, '-m set --match-set %s dst,dst -j ACCEPT' % self.ipset['ip_port_tmp'] )
547 548 549 550 551 552
            for net in base.config.NETs['serveurs']:
                for proto in base.config.firewall.srv_ports_default.keys():
                    if base.config.firewall.srv_ports_default[proto]['output']:
                        self.add(table, chain, '-p %s -s %s -m multiport --dports %s -j RETURN' % (proto, net, ','.join( format_port(port) for port in base.config.firewall.ports_default[proto]['output'])))
                    if base.config.firewall.srv_ports_default[proto]['input']:
                        self.add(table, chain, '-p %s -d %s -m multiport --dports %s -j RETURN' % (proto, net, ','.join( format_port(port) for port in base.config.firewall.ports_default[proto]['input'])))
553 554 555 556 557 558 559 560 561
            for net in base.config.NETs['adherents'] + base.config.NETs['wifi-adh'] + base.config.NETs['personnel-ens']:
                for proto in base.config.firewall.ports_default.keys():
                    if base.config.firewall.ports_default[proto]['output']:
                        self.add(table, chain, '-p %s -s %s -m multiport --dports %s -j RETURN' % (proto, net, ','.join( format_port(port) for port in base.config.firewall.ports_default[proto]['output'])))
                    if base.config.firewall.ports_default[proto]['input']:
                        self.add(table, chain, '-p %s -d %s -m multiport --dports %s -j RETURN' % (proto, net, ','.join( format_port(port) for port in base.config.firewall.ports_default[proto]['input'])))

            for machine in self.machines():
                for ip in machine['ipHostNumber']:
562
                    if 'portTCPout' in machine:
563
                        add_ports(ip, machine, 'tcp', 'out')
564
                    if 'portUDPout' in machine:
565
                        add_ports(ip, machine, 'udp', 'out')
566
                    if 'portTCPin' in machine:
567
                        add_ports(ip, machine, 'tcp', 'in')
568
                    if 'portUDPin' in machine:
569 570 571 572 573 574 575 576 577 578 579 580 581 582
                        add_ports(ip, machine, 'udp', 'in')

            self.add(table, chain, '-j REJECT')
            print OK

        if apply:
            self.apply(table, chain)
        return chain

    def limitation_debit(self, table=None, run_tc=False, apply=False):
        """Limite le débit de la connexion selon l'agréement avec l'ENS"""
        chain = 'LIMITATION-DEBIT'

        debit_max = base.config.firewall.debit_max
583
        bl_upload_debit_max = base.config.firewall.bl_upload_debit_max
584
        appt_upload_max = base.config.firewall.appt_upload_max
585
        federez_upload_max = base.config.firewall.federez_upload_max
586 587
        uplink_speed = '1024mbit'

588

589 590 591 592 593 594
        if table == 'mangle':
            pretty_print(table, chain)
            # Pas de QoS vers/depuis la zone ENS
            self.add(table, chain, '-d 138.231.0.0/16 -s 138.231.0.0/16 -j RETURN')

            # Idem pour le ftp
Valentin Samir's avatar
Valentin Samir committed
595 596
            self.add(table, chain, '-d ftp.crans.org -j RETURN')
            self.add(table, chain, '-s ftp.crans.org -j RETURN')
597

Valentin Samir's avatar
Valentin Samir committed
598 599 600 601 602 603
            self.add(table, chain, '-d tv.crans.org -j RETURN')
            self.add(table, chain, '-s tv.crans.org -j RETURN')

            # Idem vers soyouz pour le test de la connection de secours
            self.add(table, chain, '-d soyouz.crans.org -j RETURN')
            self.add(table, chain, '-s soyouz.crans.org -j RETURN')
604 605 606 607 608 609 610 611 612 613 614 615

            # Classification par defaut pour tous les paquets
            for net in base.config.NETs['all']:
                self.add(table, chain, '-o %s -s %s -j CLASSIFY --set-class 1:10' % (dev['out'], net))
                self.add(table, chain, '-o %s -d %s -j CLASSIFY --set-class 1:10' % (dev['fil'], net))
                self.add(table, chain, '-o %s -d %s -j CLASSIFY --set-class 1:10' % (dev['wifi'], net))

            # Classification pour les appartements
            for net in base.config.NETs['personnel-ens']:
                self.add(table, chain, '-o %s -d %s -j CLASSIFY --set-class 1:3' % (dev['app'], net))
                self.add(table, chain, '-o %s -s %s -j CLASSIFY --set-class 1:2' % (dev['out'], net))

616 617 618 619 620
            # Classification pour federez wifi
            for net in base.config.NETs['federez']:
                self.add(table, chain, '-o %s -d %s -j CLASSIFY --set-class 1:5' % (dev['federez'], net))
                self.add(table, chain, '-o %s -s %s -j CLASSIFY --set-class 1:4' % (dev['out'], net))

621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
            # Classification pour la voip
            self.add(table, chain, '-d sip.crans.org -j CLASSIFY --set-class 1:12')
            self.add(table, chain, '-s sip.crans.org -j CLASSIFY --set-class 1:12')
            print OK

        if run_tc:
            anim('\tApplication des commandes tc')
            for int_key in ['out', 'fil', 'wifi']:
                try:
                    utils.tc('qdisc del dev %s root' % dev[int_key])
                except utils.TcError:
                    pass
                utils.tc('qdisc add dev %s root handle 1: htb r2q 1' % dev[int_key])
                utils.tc("class add dev %s parent 1: classid 1:1 "
                   "htb rate %s ceil %s" % (dev[int_key], uplink_speed, uplink_speed))
                utils.tc("class add dev %s parent 1:1 classid 1:2 "
637
                   "htb rate %smbit ceil %smbit" % (dev[int_key], debit_max[int_key], debit_max[int_key]))
638 639 640

                # Classe par defaut
                utils.tc('class add dev %s parent 1:2 classid 1:10 '
641
                       'htb rate %smbit ceil %smbit prio 1' % (dev[int_key], debit_max[int_key], debit_max[int_key]))
642 643 644 645 646
                utils.tc('qdisc add dev %s parent 1:10 '
                       'handle 10: sfq perturb 10' % dev[int_key])

                # Classe par pour la voip
                utils.tc('class add dev %s parent 1:2 classid 1:12 '
647
                       'htb rate %smbit ceil %smbit prio 0' % (dev[int_key], debit_max[int_key], debit_max[int_key]))
648 649 650 651 652
                utils.tc('qdisc add dev %s parent 1:12 '
                       'handle 12: sfq perturb 10' % dev[int_key])

            #Classe des decos upload
            utils.tc('class add dev %s parent 1:2 classid 1:11 '
653
                    'htb rate %skbps ceil %skbps prio 1' % (dev['out'], bl_upload_debit_max, bl_upload_debit_max))
654 655 656 657 658 659
            utils.tc('qdisc add dev %s parent 1:11 '
                    'handle 11: sfq perturb 10' % dev['out'])

            for int_key in ['app']:
                try:
                    utils.tc('qdisc del dev %s root' % dev[int_key])
Daniel STAN's avatar
Daniel STAN committed
660
                except utils.TcError:
661 662 663 664
                    pass
                utils.tc('qdisc add dev %s root handle 1: htb r2q 1' % dev[int_key])

                utils.tc("class add dev %s parent 1: classid 1:1 "
665
                   "htb rate %smbps ceil %smbps" % (dev[int_key], appt_upload_max, appt_upload_max))
666 667 668

                # Classe pour l'upload des appartements
                utils.tc("class add dev %s parent 1:1 classid 1:2 "
669
                   "htb rate %smbps ceil %smbps" % (dev[int_key], appt_upload_max, appt_upload_max))
670 671 672 673 674
                utils.tc('qdisc add dev %s parent 1:2 '
                   'handle 2: sfq perturb 10' % dev[int_key])

                # Classe pour le download des apparetments
                utils.tc("class add dev %s parent 1: classid 1:3 "
675
                   "htb rate %smbit ceil %smbit" % (dev[int_key], debit_max['total']/10, debit_max['total']/2))
676 677 678
                utils.tc('qdisc add dev %s parent 1:3 '
                   'handle 3: sfq perturb 10' % dev[int_key])

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
            # Class du vlan wifi federez, on bride l'upload/download, à 10 mbytes/sec

            for int_key in ['federez']:
                try:
                    utils.tc('qdisc del dev %s root' % dev[int_key])
                except utils.TcError:
                    pass
                utils.tc('qdisc add dev %s root handle 1: htb r2q 1' % dev[int_key])

                utils.tc("class add dev %s parent 1: classid 1:1 "
                   "htb rate %smbps ceil %smbps" % (dev[int_key], federez_upload_max, federez_upload_max))

                # Classe pour l'upload wifi federez
                utils.tc("class add dev %s parent 1:1 classid 1:4 "
                   "htb rate %smbps ceil %smbps" % (dev[int_key], federez_upload_max, federez_upload_max))
                utils.tc('qdisc add dev %s parent 1:4 '
                   'handle 2: sfq perturb 10' % dev[int_key])

                # Classe pour le download wifi federez
                utils.tc("class add dev %s parent 1: classid 1:5 "
699
                   "htb rate %smbit ceil %smbit" % (dev[int_key], debit_max['total']/10, debit_max['total']/2))
700 701 702
                utils.tc('qdisc add dev %s parent 1:5 '
                   'handle 3: sfq perturb 10' % dev[int_key])

703 704 705 706 707 708 709
            print OK

        if apply:
            self.apply(table, chain)
        return chain