firewall4.py 48.4 KB
Newer Older
1
2
3
4
5
#!/usr/bin/env python
# -*- coding: utf-8 -*-


import os
6
import sys
7
8
9
sys.path.append('/usr/scripts/gestion')
sys.path.append('/usr/scripts/lc_ldap')

10
from config import NETs, blacklist_sanctions, blacklist_sanctions_soft, blacklist_bridage_upload, mac_komaz, mac_titanic, adm_users, accueil_route
11

12
import pwd
13
14
15
16
17
18
import config.firewall
import lc_ldap
import socket
from ipset import IpsetError, Ipset
from iptools import AddrInNet, NetSubnets, IpSubnet, NetInNets
import subprocess
19
20
import syslog
from affich_tools import anim, OK, cprint
21
22
23

squeeze = os.uname()[2] < '3'

24
#: Nom de la machine exécutant le script
25
26
hostname = socket.gethostname()

27
#: Chaines par défaut d'iptables
28
default_chains = ['INPUT', 'OUTPUT', 'FORWARD', 'PREROUTING', 'POSTROUTING']
29
#: Tables d'iptables
30
31
tables = ['raw', 'mangle', 'filter', 'nat']

32
#: Association des interfaces de ``hostname``
33
34
35
dev = hostname in config.firewall.dev.keys() and config.firewall.dev[hostname] or {}

def pretty_print(table, chain):
36
    """Affiche quelle chaine est en train d'être construite dans quelle table de NetFilter"""
37
38
    anim('\t%s dans %s' % (chain, table))

39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

class TcError(Exception):
    """ Gestion des erreurs de tc """
    def __init__(self,cmd,err_code,output):
        self.cmd=cmd
        self.err_code=err_code
        self.output=output
        syslog.syslog(syslog.LOG_ERR,"%s : status %s,%s" % (cmd,err_code,output))
    def __str__(self):
        return "%s\n  status : %s\n  %s" % (self.cmd,self.err_code,self.output)

def tc(cmd, block=True):
    """ Interface de tc """
    params = ['/sbin/tc']
    params.extend(cmd.split())
    p = subprocess.Popen(params , stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if block:
        status = p.wait()
        stdoutdata, stderrdata = p.communicate()
        if status:
            raise TcError(' '.join(params), status, stdoutdata + stderrdata)
        return stdoutdata + stderrdata

62
class firewall_base(object) :
63
    """Classe de base du pare-feu implémentant l'association mac-ip (pour les machines filaires) et les blacklists hard"""
64
65

    def machines(self):
66
        """Renvois la liste de toutes les machines"""
67
68
69
70
71
72
        if self._machines:
            return self._machines
        self._machines, self._adherents = conn.allMachinesAdherents()
        return self._machines

    def adherents(self):
73
        """Renvois la liste de tous les adhérents"""
74
75
76
77
78
79
80
        if self._adherents:
            return self._adherents
        self._machines, self._adherents = conn.allMachinesAdherents()
        self._adherents = [ adh for adh in self._adherents if adh.paiement_ok ]
        return self._adherents

    def blacklisted_machines(self):
81
        """Renvois la liste de toutes les machines ayant une blackliste actives"""
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
        if self._blacklisted_machines:
            return self._blacklisted_machines
        if self._machines:
            self._blacklisted_machines = [ machine for machine in self._machines if machine.blacklist_actif() ]
            return self._blacklisted_machines
        blacklisted = [ machine for machine in conn.search("blacklist=*",sizelimit=4096) if machine.blacklist_actif() ]
        self._blacklisted_machines = set()
        for item in blacklisted:
            if isinstance(item, lc_ldap.proprio):
                 self._blacklisted_machines = self._blacklisted_machines.union(item.machines())
            elif isinstance(item, lc_ldap.machine):
                self._blacklisted_machines.add(item)
            else:
                print >> sys.stderr, 'Objet %s inconnu blacklisté' %  a.__class__.__name__
        return self._blacklisted_machines

98
    def blacklisted_adherents(self):
99
        """Renvois la liste de tous les adhérents ayant une blackliste active"""
100
101
102
103
104
        if self._blacklisted_adherents:
            return self._blacklisted_adherents
        self._blacklisted_adherents = filter(lambda adh: adh.blacklist_actif(), self.adherents())
        return self._blacklisted_adherents

105
    def add(self, table, chain, rule):
106
        """Ajoute la règle ``rule`` à la chaine ``chain`` dans la table ``table``"""
107
108
109
110
111
112
        if not chain in self.chain_list[table]:
            self.chain_list[table].append(chain)
            self.rules_list[table][chain]=[]
        self.rules_list[table][chain].append(rule)

    def delete(self, table=None, chain=None):
113
        """Supprime ``chain`` de ``table`` si fournis, sinon supprime ``table``, sinon toutes les tables"""
114
115
116
117
118
119
        if not table:
            for table in tables:
                self.delete(table, chain)
        if not chain:
            for chain in self.chain_list[table]:
                self.delete(table, chain)
120
121
122
123
124
125
126
127

        if not chain in self.chain_list[table]:
            return
        if not chain in default_chains:
            self.chain_list[table].remove(chain)
            del(self.rules_list[table][chain])
        else:
            self.rules_list[table][chain]=[]
128
129

    def flush(self, table=None, chain=None):
130
131
        """Vide ``chain`` dans ``table`` si fournis, sinon vide toutes
           les chaines de  ``table``, sinon vide toutes les chaines de toutes les tables"""
132
133
134
135
136
137
138
        if not table:
            for table in tables:
                self.flush(table, chain)
        if not chain:
            for chain in self.chain_list[table]:
                self.flush(table, chain)
        if not chain in self.chain_list[table]:
139
140
            self.chain_list[table].append(chain)
        self.rules_list[table][chain]=[]
141

142
    def restore(self, table=None, chains=[], noflush=False):
143
144
145
        """Restores les règles du pare-feu dans le noyau en appelant ``iptables-restore``.
           Si ``table`` est fournis, on ne restore que table.
           Si ``noflush`` n'est pas à ``True`` tout le contenu précédent est supprimé"""
146
147
148
149
150
151
152
153
154
155
156
157
158
159
        str=self.format(chains)
        f=open('/tmp/ipt_rules', 'w')
        f.write(str)
        f.close()
        params = ['/sbin/iptables-restore']
        if noflush:
            params.append('--noflush')
        if table and table in ['raw', 'mangle', 'filter', 'nat']:
            params.append('--table')
            params.append(table)
        p = subprocess.Popen(params , stdin=subprocess.PIPE)
        p.communicate(input=str)

    def apply(self, table, chain):
160
        """Applique les règles de ``chain`` dans ``table``"""
161
162
        if not chain in self.chain_list[table]:
            return
163
164
        self.restore(table, [chain], noflush=True)
        self.delete(table, chain)
165
166

    def format(self, chains=[]):
167
        """Transforme la structure interne des règles du pare-feu en celle comprise par ``iptables-restore``"""
168
169
170
171
172
173
174
175
176
177
178
179
180
        str = ''
        for table in self.chain_list.keys():
            str += '*%s\n' % table
            for chain in self.chain_list[table]:
                if not chains or chain in chains or chain in default_chains:
                    str += ':%s %s [0:0]\n' % (chain, chain in default_chains and 'ACCEPT' or '-')
            for chain in self.chain_list[table]:
                if not chains or chain in chains :
                    for rule in self.rules_list[table][chain]:
                        str += '-A %s %s\n' % (chain, rule)
            str += 'COMMIT\n'
        return str

181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
    def reload(self, func_name):
        if squeeze and self.reloadable[func_name] in self.use_ipset:
            anim('\tVidage de %s' % self.reloadable[func_name]())
            for table in ['raw', 'mangle', 'filter', 'nat']:
                self.flush(table, self.reloadable[func_name]())
            self.restore(noflush=True)
            print OK

        for table in ['raw', 'mangle', 'filter', 'nat']:
            self.reloadable[func_name](table)
        if self.reloadable[func_name] in self.use_ipset:
            self.reloadable[func_name](fill_ipset=True)
        if self.reloadable[func_name] in self.use_tc:
            self.reloadable[func_name](run_tc=True)

        anim('\tRestoration d\'iptables')
        self.restore(noflush=True)
        print OK

200
    def __init__(self):
201
        global conn
202
        #initialisation des structures communes : récupération des ipset
203
204
205
206
207
        if os.getuid() != 0:
            from affich_tools import coul
            sys.stderr.write(coul("Il faut être root pour utiliser le firewall\n", 'gras'))
            sys.exit(1)

208
209
        # Connection à la base ldap
        conn = lc_ldap.lc_ldap_admin()
210
211
212
213
214
215
216

        self.reloadable = {
            'blacklist_hard' : self.blacklist_hard,
            'test_mac_ip' : self.test_mac_ip,
        }

        self.use_ipset = [self.blacklist_hard, self.test_mac_ip]
217
        self.use_tc = []
218
219
220
221

        self._machines = None
        self._adherents = None
        self._blacklisted_machines = None
222
        self._blacklisted_adherents = None
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251

        self.chain_list={
            'raw':['OUTPUT', 'PREROUTING'],
            'mangle':['INPUT', 'OUTPUT', 'FORWARD', 'PREROUTING', 'POSTROUTING'],
            'filter':['INPUT', 'OUTPUT', 'FORWARD'],
            'nat':['OUTPUT', 'PREROUTING', 'POSTROUTING']
        }
        self.rules_list = {
            'raw': { 'OUTPUT':[], 'PREROUTING':[] },
            'mangle':{'INPUT':[], 'OUTPUT':[], 'FORWARD':[], 'PREROUTING':[], 'POSTROUTING':[]},
            'filter':{'INPUT':[], 'OUTPUT':[], 'FORWARD':[]},
            'nat':{'OUTPUT':[], 'PREROUTING':[], 'POSTROUTING':[]}
        }

        self.ipset={}

        self.ipset['mac_ip']={
            'adh' : Ipset("MAC-IP-ADH","macipmap","--from 138.231.136.0 --to 138.231.151.255"),
            'adm' : Ipset("MAC-IP-ADM","macipmap","--from 10.231.136.0 --to 10.231.136.255"),
            'app' : Ipset("MAC-IP-APP","macipmap","--from 10.2.9.0 --to 10.2.9.255"),
        }

        self.ipset['blacklist']={
            'hard' : Ipset("BLACKLIST-HARD","ipmap","--from 138.231.136.0 --to 138.231.151.255"),
        }



    def start(self):
252
        """Démarre le pare-feu : génère les règles, puis les restore"""
253
254
255
256
257
258
        anim('\tChargement des machines')
        self.machines()
        print OK

        if squeeze:
            anim('\tVidage du pare-feu')
259
            self.restore()
260
261
262
263
264
265
266
267
            print OK

        self.raw_table()
        self.mangle_table()
        self.filter_table()
        self.nat_table()

        anim('\tRestoration d\'iptables')
268
        self.restore()
269
270
271
272
        print OK
        return

    def stop(self):
273
        """Vide les règles du pare-feu"""
274
275
        self.delete()
        self.restore()
276
277
278
        return

    def restart(self):
279
        """Alias de :py:func:`start`"""
280
281
282
        self.start()
        return

283
    def blacklist_maj(self, ips):
284
        """Met à jours les blacklists pour les ip présentent dans la liste ``ips``"""
285
        self.blacklist_hard_maj(ips)
286
287

    def raw_table(self):
288
        """Génère les règles pour la table ``raw`` et remplis les chaines de la table"""
289
290
291
292
        table = 'raw'
        return

    def mangle_table(self):
293
        """Génère les règles pour la table ``mangle`` et remplis les chaines de la table"""
294
295
296
297
        table = 'mangle'
        return

    def filter_table(self):
298
        """Génère les règles pour la table ``filter`` et remplis les chaines de la table"""
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
        table = 'filter'

        mac_ip_chain = self.test_mac_ip(table, fill_ipset=True)
        blacklist_hard_chain = self.blacklist_hard(table, fill_ipset=True)

        chain = 'INPUT'
        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')
        for net in NETs['all'] + NETs['adm'] + 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.add(table, chain, '-j REJECT')

        return

    def nat_table(self):
318
        """Génère les règles pour la table ``nat`` et remplis les chaines de la table"""
319
320
321
322
323
324
325
        table = 'nat'
        return




    def blacklist_hard_maj(self, ip_list):
326
        """Met à jour les blacklists hard, est appelée par :py:func:`blacklist_maj`"""
327
        for ip in ip_list:
328
            machine = conn.search("ipHostNumber=%s" % ip)
329
            # Est-ce qu'il y a des blacklists hard parmis les blacklists de la machine
330
            if machine and set([bl.value['type'] for bl in machine[0].blacklist_actif() ]).intersection(blacklist_sanctions):
331
332
333
334
335
336
337
                try: self.ipset['blacklist']['hard'].add(ip)
                except IpsetError: pass
            else:
                try: self.ipset['blacklist']['hard'].delete(ip)
                except IpsetError: pass

    def blacklist_hard(self, table=None, fill_ipset=False, apply=False):
338
339
340
        """Génère la chaine ``BLACKLIST_HARD``.
        Si ``fill_ipset`` est à ``True``, remplis l'ipset ``BLACKLIST-HARD``.
        Si ``apply`` est à True, applique directement les règles"""
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
        chain = 'BLACKLIST_HARD'

        if fill_ipset:
            anim('\tRestoration de l\'ipset %s' % self.ipset['blacklist']['hard'])
            # On récupère la liste de toutes les ips blacklistés hard
            bl_hard_ips = set(
                str(ip) for ips in
                [
                    machine['ipHostNumber'] for machine in self.blacklisted_machines()
                    if set([bl.value['type'] for bl in machine.blacklist_actif() ]).intersection(blacklist_sanctions)
                ]
                for ip in ips
            )

            self.ipset['blacklist']['hard'].restore(bl_hard_ips)
            print OK

        if table == 'filter':
            pretty_print(table, chain)
            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 apply:
            self.apply(table, chain)
        return chain

    def test_mac_ip_dispatch(self, func, machine):
369
        """Détermine à quel set de mac-ip appliquer la fonction ``func`` (add, delete, append, ...)"""
370
371
372
373
        ips = machine['ipHostNumber']
        for ip in ips:
            # Si la machines est sur le réseau des adhérents
            if AddrInNet(str(ip), NETs['wifi']):
374
375
                # Les machines wifi sont vues à travers komaz
                func('adh', "%s,%s" % (ip, mac_komaz))
376
377
378
379
380
381
382
            elif AddrInNet(str(ip), NETs['fil']):
                func('adh', "%s,%s" % (ip, machine['macAddress'][0]))
            # Si la machine est sur le réseau admin
            elif AddrInNet(str(ip), NETs['adm']):
                func('adm', "%s,%s" % (ip, machine['macAddress'][0]))

    def test_mac_ip(self, table=None, fill_ipset=False, apply=False):
383
384
385
        """Génère la chaine ``TEST_MAC-IP``.
        Si ``fill_ipset`` est à ``True``, remplis les ipsets ``MAC-IP-ADH``, ``MAC-IP-ADM``, ``MAC-IP-ADM``.
        Si ``apply`` est à True, applique directement les règles"""
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
        chain = 'TEST_MAC-IP'

        if fill_ipset:
            anim('\tRestoration des ipsets %s' % ', '.join(self.ipset['mac_ip'].keys()))
            rules={
                'adh':[],
                'adm':[],
                'app':[],
            }
            for machine in self.machines():
                self.test_mac_ip_dispatch(lambda set, data: rules[set].append(data), machine)

            for set,rules in rules.items():
                self.ipset['mac_ip'][set].restore(rules)
            print OK

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

            for key in ['accueil', 'isolement', ]:
                for net in NETs[key]:
                    self.add(table, chain, '-s %s -j RETURN' % net)
            for key in self.ipset['mac_ip'].keys():
                self.add(table, chain, '-m set --match-set %s src,src -j RETURN' % self.ipset['mac_ip'][key])

            # Proxy ARP de Komaz et Titanic pour OVH
            ip_ovh = conn.search("host=ovh.adm.crans.org")[0]['ipHostNumber'][0]
            self.add(table, chain, '-m mac -s %s --mac-source %s -j RETURN' % (ip_ovh, mac_komaz))
            self.add(table, chain, '-m mac -s %s --mac-source %s -j RETURN' % (ip_ovh, mac_titanic))

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

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

    def mac_ip_maj(self, ip_list):
424
        """Met à jour la correspondance mac-ip"""
425
        for ip in ip_list:
426
            machine = conn.search("ipHostNumber=%s" % ip)
427
            if machine:
428
                try: self.test_mac_ip_dispatch(lambda set, data: self.ipset['mac_ip'][set].delete(data.split(',',1)[0]), {'ipHostNumber' : [ip], 'macAddress':[''] })
429
                except IpsetError: pass
430
                self.test_mac_ip_dispatch(lambda set, data: self.ipset['mac_ip'][set].add(data), machine[0])
431
            else:
432
                try: self.test_mac_ip_dispatch(lambda set, data: self.ipset['mac_ip'][set].delete(data.split(',',1)[0]), {'ipHostNumber' : [ip], 'macAddress':[''] })
433
434
                except IpsetError: pass

435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
class firewall_base_routeur(firewall_base):
    """Associe mac-ip pour les machines voyant plusieurs réseaux (wifi, filaire, personnel, ...)"""
    def test_mac_ip_dispatch(self, func, machine):
        """Détermine à quel set de mac-ip appliquer la fonction func (add, delete, append, ...)"""
        ips = machine['ipHostNumber']
        for ip in ips:
            # Si la machines est sur le réseau des adhérents
            if AddrInNet(str(ip), NETs['wifi']):
                   func('adh', "%s,%s" % (ip, machine['macAddress'][0]))
            elif AddrInNet(str(ip), NETs['fil']):
                func('adh', "%s,%s" % (ip, machine['macAddress'][0]))
            # Si la machine est sur le réseau admin
            elif AddrInNet(str(ip), NETs['adm']):
                func('adm', "%s,%s" % (ip, machine['macAddress'][0]))
            # Si la machine est sur le réseaux des appartements de l'ENS
            elif AddrInNet(str(ip), NETs['personnel-ens']):
                    func('app', "%s,%s" % (ip, machine['macAddress'][0]))
452

453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
class firewall_base_wifionly(firewall_base):
    """Associe mac-ip pour les machines wifi only : les machines filaires sont vues avec la mac de komaz"""
    def test_mac_ip_dispatch(self, func, machine):
        """Détermine à quel set de mac-ip appliquer la fonction func (add, delete, append, ...)"""
        ips = machine['ipHostNumber']
        for ip in ips:
            # Si la machines est sur le réseau des adhérents
            if AddrInNet(str(ip), NETs['wifi']):
                   func('adh', "%s,%s" % (ip, machine['macAddress'][0]))
            elif AddrInNet(str(ip), NETs['fil']):
                func('adh', "%s,%s" % (ip, mac_komaz))
            # Si la machine est sur le réseau admin
            elif AddrInNet(str(ip), NETs['adm']):
                func('adm', "%s,%s" % (ip, machine['macAddress'][0]))

class firewall_komaz(firewall_base_routeur):
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483

    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,
            'blacklist_soft' : self.blacklist_soft,
            'reseaux_non_routable' : self.reseaux_non_routable,
            'filtrage_ports' : self.filtrage_ports,
484
            'limitation_debit' : self.limitation_debit,
485
            'limit_ssh_connexion' : self.limit_ssh_connexion,
486
487
488
        })

        self.use_ipset.extend([self.blacklist_soft, self.reseaux_non_routable])
489
        self.use_tc.extend([self.limitation_debit])
490
491
492
493
494
495

        self.ipset['reseaux_non_routable'] = {
            'deny' : Ipset("RESEAUX-NON-ROUTABLE-DENY","nethash"),
            'allow' :  Ipset("RESEAUX-NON-ROUTABLE-ALLOW","nethash"),
        }

496
497
498
499
500
        self.ipset['blacklist'].update({
            'soft' : Ipset("BLACKLIST-SOFT","ipmap","--from 138.231.136.0 --to 138.231.151.255"),
            'upload' : Ipset("BLACKLIST-UPLOAD","ipmap","--from 138.231.136.0 --to 138.231.151.255"),
        })

501
502
503
504
    def blacklist_maj(self, ips):
        self.blacklist_hard_maj(ips)
        self.blacklist_soft_maj(ips)

505
506
507
508
509
510
511
512
513
514
515
516
517
    def raw_table(self):
        return

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

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

518
        chain = 'POSTROUTING'
519
        self.add(table, chain, '-j %s' % self.clamp_mss(table))
520
        self.add(table,chain, '-j %s' % self.limitation_debit(table, run_tc=True))
521
522
523
524
525
526
527
528
529
530
        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()

        chain = 'FORWARD'
531
        self.flush(table, chain)
532
533
534
        self.add(table, chain, '-i lo -j ACCEPT')
        self.add(table, chain, '-p icmp -j ACCEPT')
        self.add(table, chain, '-j %s' % self.admin_vlan(table))
535
536
        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))
537
538
539
540
541
542
543
544
        self.add(table, chain, '-m state --state RELATED,ESTABLISHED -j ACCEPT')
        self.add(table, chain, '-j %s' % self.reseaux_non_routable(table, fill_ipset=True))
        self.add(table, chain, '-j %s' % self.blacklist_soft(table))
        for net in NETs['all'] + NETs['adm'] + 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))
        self.add(table, chain, '-j %s' % self.ingress_filtering(table))
545
        self.add(table, chain, '-j %s' % self.limit_ssh_connexion(table))
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
        self.add(table, chain, '-j %s' % 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))
        self.add(table, chain, '-j %s' % self.connexion_secours(table))
        self.add(table, chain, '-j %s' % self.blacklist_soft(table))

        chain = 'POSTROUTING'
        self.add(table, chain, '-j %s' % self.connexion_appartement(table))
        return

562
563
564
565
566
567
568
569
570
571
572
573
574
    def limit_ssh_connexion(self, table=None, apply=False):
        chain = 'LIMIT-SSH-CONNEXION'

        if table == 'filter':
            pretty_print(table, chain)
            self.add(table, chain, '-i %s -p tcp --dport ssh -m state --state NEW -m recent --name SSH --set' % dev['out'])
            self.add(table, chain, '-i %s -p tcp --dport ssh -m state --state NEW -m recent --name SSH --update --seconds 30 --hitcount 10 --rttl -j DROP' % dev['out'])
            print OK

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

575
576
577
578
579
580
581
582
583
584
    def test_mac_ip(self, table=None, fill_ipset=False, apply=False):
        chain = super(self.__class__, self).test_mac_ip()

        if table == 'filter':
            for key in ['out', 'tun-ovh' ]:
                self.add(table, chain, '-i %s -j RETURN' % dev[key])

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


585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
    def log_all(self, table=None, apply=False):
        chain = 'LOG_ALL'

        if table == 'mangle':
            pretty_print(table, chain)
            for device in dev.values():
                self.add(table, chain, '-i %s -m state --state NEW -j LOG --log-prefix "LOG_ALL "' % device)
            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 NETs['adm']:
604
605
                self.add(table, chain, '-o %s -s %s -j ACCEPT' % (dev['tun-ovh'], net))
                self.add(table, chain, '-i %s -d %s -j ACCEPT' % (dev['tun-ovh'], net))
606
607
608
609
610
611
612
613
614
615
616
                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):
617
        """Force la MSS (Max Segment Size) TCP à rentrer dans la MTU (Max Transfert Unit)"""
618
619
620
621
622
623
624
625
626
627
628
629
        chain = 'CLAMP-MSS'
        if table == 'mangle':
            pretty_print(table, chain)

            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):
630
631
        """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)"""
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
        chain = 'INGRESS_FILTERING'
        if table == 'filter':
            pretty_print(table, chain)

            for net in 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 NETs['all']:
                for net_s in 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):
652
        """Pour faire fonctionner ssh2.crans.org"""
653
654
655
656
657
658
659
660
661
662
663
664
665
        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
            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):
666
        """Redirige les paquets vers un proxy lorsqu'on est en connexion de secours"""
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
        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' % (config.firewall.mark['secours']))
            self.add(table, chain, '-m mark --mark %s -j ACCEPT' % 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' % 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' % config.firewall.mark['secours'])
            print OK

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

    def connexion_appartement(self, table=None, apply=False):
691
        """PNAT les appartements derrière appartement.crans.org"""
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
        chain = 'CONNEXION-APPARTEMENT'

        if table == 'nat':
            pretty_print(table, chain)
            for dev_key in ['out', 'fil', 'wifi']:
                for net in 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 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

    def blacklist_soft_maj(self, ip_list):
        for ip in ip_list:
714
715
            machine = conn.search("ipHostNumber=%s" % ip)
            # Est-ce qu'il y a des blacklists soft parmis les blacklists de la machine
716
717
718
            if machine and set([bl.value['type'] for bl in machine[0].blacklist_actif() ]).intersection(blacklist_sanctions_soft):
                try: self.ipset['blacklist']['soft'].add(ip)
                except IpsetError: pass
719
            else:
720
721
                try: self.ipset['blacklist']['soft'].delete(ip)
                except IpsetError: pass
722
723
724
725
726
727

            # Est-ce qu'il y a des blacklists pour upload parmis les blacklists de la machine
            if machine and set([bl.value['type'] for bl in machine[0].blacklist_actif() ]).intersection(blacklist_bridage_upload):
                try: self.ipset['blacklist']['upload'].add(ip)
                except IpsetError: pass
            else:
728
729
730
                try: self.ipset['blacklist']['upload'].delete(ip)
                except IpsetError: pass

731
732

    def blacklist_soft(self, table=None, fill_ipset=False, apply=False):
733
        """Redirige les gens blacklisté vers le portail captif"""
734
735
736
737
738
739
740
741
742
743
744
745
746
747
        chain = 'BLACKLIST_SOFT'

        if fill_ipset:
            anim('\tRestoration de l\'ipset %s' % self.ipset['blacklist']['soft'])
            # On récupère la liste de toutes les ips blacklistés soft
            bl_soft_ips = set(
                str(ip) for ips in
                [
                    machine['ipHostNumber'] for machine in self.blacklisted_machines()
                    if set([bl.value['type'] for bl in machine.blacklist_actif() ]).intersection(blacklist_sanctions_soft)
                ]
                for ip in ips
            )

748
749
750
751
752
753
754
755
756
            bl_upload_ips = set(
                str(ip) for ips in
                [
                    machine['ipHostNumber'] for machine in self.blacklisted_machines()
                    if set([bl.value['type'] for bl in machine.blacklist_actif() ]).intersection(blacklist_bridage_upload)
                ]
                for ip in ips
            )

757
            self.ipset['blacklist']['soft'].restore(bl_soft_ips)
758
            self.ipset['blacklist']['upload'].restore(bl_upload_ips)
759
760
761
762
763
764
765
766
767
768
            print OK

        if table == 'mangle':
            pretty_print(table, chain)
            self.add(table, chain, '-p tcp ! --dport 80 -j RETURN')
            self.add(table, chain, '! -p tcp -j RETURN')
            for net in NETs['all']:
                self.add(table, chain, '-d %s -j RETURN' % net)
            self.add(table, chain, '-m set --match-set %s src -j MARK --set-mark %s'
                    %  (self.ipset['blacklist']['soft'], config.firewall.mark['proxy']))
769

770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
            print OK

        if table == 'filter':
            pretty_print(table, chain)
            self.add(table, chain, '-m mark --mark %s -j ACCEPT' % config.firewall.mark['proxy'])
            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:3128' % config.firewall.mark['proxy'] )
            print OK

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

    def reseaux_non_routable(self, table=None, fill_ipset=False, apply=False):
787
        """Bloque les réseaux non routables autres que ceux utilisés par le crans"""
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
        chain = 'RESEAUX_NON_ROUTABLES'

        if fill_ipset:
            anim('\tRestoration de l\'ipset reseaux_non_routable')
            allowed = [ net for nets in NETs.values() for net in nets if NetInNets(net, config.firewall.reseaux_non_routables) ]
            self.ipset['reseaux_non_routable']['allow'].restore(allowed)
            self.ipset['reseaux_non_routable']['deny'].restore(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):
813
        """Ouvre les ports vers et depuis les machines du réseau crans"""
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
        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, 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['portTCP%s' % sens])
                )
            )

        if table == 'filter':
            pretty_print(table, chain)
838
839
840
841
842
843
844
            for net in NETs['adherents'] + NETs['wifi-adh'] + NETs['personnel-ens']:
                for proto in config.firewall.ports_default.keys():
                    if 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 config.firewall.ports_default[proto]['output'])))
                    if 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 config.firewall.ports_default[proto]['input'])))

845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
            for machine in self.machines():
                for ip in machine['ipHostNumber']:
                    if 'portTCPout' in machine.attrs.keys():
                        add_ports(ip,'tcp','out')
                    if 'portUDPout' in machine.attrs.keys():
                        add_ports(ip,'udp','out')
                    if 'portTCPin' in machine.attrs.keys():
                        add_ports(ip,'tcp','in')
                    if 'portUDPin' in machine.attrs.keys():
                        add_ports(ip,'udp','in')

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

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

863
    def limitation_debit(self, table=None, run_tc=False, apply=False):
864
        """Limite le débit de la connexion selon l'agréement avec l'ENS"""
865
866
867
868
869
870
871
        chain = 'LIMITATION-DEBIT'

        debit_max = config.firewall.debit_max
        uplink_speed = '1024mbit'

        if table == 'mangle':
            pretty_print(table, chain)
872
873
874
875
            # 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
876
877
878
            self.add(table, chain, '-d 138.231.136.98 -j RETURN')
            self.add(table, chain, '-s 138.231.136.98 -j RETURN')

879
880
881
882
            # Idem vers OVH pour le test de la connection de secours
            self.add(table, chain, '-d 91.121.84.138 -j RETURN')
            self.add(table, chain, '-s 91.121.84.138 -j RETURN')

883
884
885
886
887
888
889
890
891
892
            # Classification par defaut pour tous les paquets
            for net in 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 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))
893
894
895

            # 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']))
896
897
898
899

            # 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')
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
            print OK

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

                # Classe par defaut
                tc('class add dev %s parent 1:2 classid 1:10 '
                       'htb rate %skbps ceil %skbps prio 1' % (dev[int_key], debit_max, debit_max))
                tc('qdisc add dev %s parent 1:10 '
                       'handle 10: sfq perturb 10' % dev[int_key])

921
922
923
924
925
                # Classe par pour la voip
                tc('class add dev %s parent 1:2 classid 1:12 '
                       'htb rate %skbps ceil %skbps prio 0' % (dev[int_key], debit_max, debit_max))
                tc('qdisc add dev %s parent 1:12 '
                       'handle 12: sfq perturb 10' % dev[int_key])
926
927
928

            #Classe des decos upload
            tc('class add dev %s parent 1:2 classid 1:11 '
929
                    'htb rate 30kbps ceil 30kbps prio 1' % dev['out'])
930
931
932
            tc('qdisc add dev %s parent 1:11 '
                    'handle 11: sfq perturb 10' % dev['out'])

933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
            for int_key in ['app']:
                try:
                    tc('qdisc del dev %s root' % dev[int_key])
                except TcError:
                    pass
                tc('qdisc add dev %s root handle 1: htb r2q 1' % dev[int_key])

                tc("class add dev %s parent 1: classid 1:1 "
                   "htb rate 128kbps ceil 128kbps" % dev[int_key])

                # Classe pour l'upload des appartements
                tc("class add dev %s parent 1:1 classid 1:2 "
                   "htb rate 128kbps ceil 128kbps" % dev[int_key])
                tc('qdisc add dev %s parent 1:2 '
                   'handle 2: sfq perturb 10' % dev[int_key])

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

            print OK

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

961

962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
class firewall_zamok(firewall_base):

    def __init__(self):
        super(self.__class__, self).__init__()

        self.reloadable.update({
            'admin_vlan' : self.admin_vlan,
            'blacklist_output' : self.blacklist_output,
        })

        self.use_ipset.extend([])
        self.use_tc.extend([])


    def raw_table(self):
        table = 'raw'

        super(self.__class__, self).raw_table()

        return

    def mangle_table(self):
        table = 'mangle'

        super(self.__class__, self).mangle_table()

        return

    def filter_table(self):
        table = 'filter'

        super(self.__class__, self).filter_table()

        chain = 'OUTPUT'
        self.add(table, chain , '-d 224.0.0.0/4 -j DROP')
        admin_vlan_chain = self.admin_vlan(table)
998
        self.add(table, chain, '-m state --state RELATED,ESTABLISHED -j ACCEPT')
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
        for net in NETs['adm']:
            self.add(table, chain, '-d %s -j %s' % (net, admin_vlan_chain))
        self.add(table, chain, '-o lo -j ACCEPT')
        self.add(table, chain, '-j %s' % self.blacklist_output(table))

        return

    def nat_table(self):
        table = 'nat'

        super(self.__class__, self).raw_table()
        return

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

        if table == 'filter':
1016
            pretty_print(table, chain)
1017
1018
1019
1020
1021
1022
            # ldap et dns toujours joinable
            self.add(table, chain, '-p tcp --dport ldap -j ACCEPT')
            self.add(table, chain, '-p tcp --dport domain -j ACCEPT')
            self.add(table, chain, '-p udp --dport domain -j ACCEPT')

            # Pour le nfs (le paquet à laisser passer n'a pas d'owner)
1023
            self.add(table, chain, '-d nfs.adm.crans.org -j ACCEPT')
1024

1025
1026
1027
1028
1029
1030
1031
            for user in adm_users:
                try: self.add(table, chain, '-m owner --uid-owner %d -j ACCEPT' % pwd.getpwnam(user)[2])
                except KeyError: print "Utilisateur %s inconnu" % user

            for nounou in conn.search("droits=%s" % lc_ldap.attributs.nounou):
                self.add(table, chain, '-m owner --uid-owner %s -j RETURN' % nounou['uidNumber'][0])

1032
1033
            # Rien d'autre ne passe
            self.add(table, chain, '-j REJECT --reject-with icmp-net-prohibited')
1034
            print OK
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046

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

    def blacklist_maj(self, ips):
        anim('\tMise à jour des blacklists')
        self.blacklist_output('filter', apply=True)
        self.blacklist_hard_maj(ips)
        print OK

    def blacklist_output(self, table=None, apply=False):
1047
1048
        """Empêche les gens blacklisté d'utiliser zamok comme relaie"""
        chain='BLACKLIST-OUTPUT'
1049
1050

        if table == 'filter':
1051
1052
            pretty_print(table, chain)
            self.add(table, chain, '-d 127.0.0.1/8 -j RETURN')
1053
            for net in NETs['all']:
1054
                        self.add(table, chain, '-d %s -j RETURN' % net)
1055
1056
1057
            for adh in self.blacklisted_adherents():
                if 'uidNumber' in adh.attrs.keys():
                    self.add(table, chain, '-m owner --uid-owner %s -j REJECT' % adh['uidNumber'][0])
1058
            print OK
1059
1060
1061
1062
1063

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

1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
class firewall_routeur(firewall_base):

    def __init__(self):
        super(self.__class__, self).__init__()

        self.reloadable.update({
            'portail_captif_route' : self.portail_captif_route,
            'portail_captif' : self.portail_captif,
        })

        self.use_ipset.extend([])
        self.use_tc.extend([])

    def raw_table(self):
        table = 'raw'
        super(self.__class__, self).raw_table()
        return

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

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

        chain = 'FORWARD'
        self.flush(table, chain)
        self.add(table, chain, '-j %s' % self.portail_captif_route(table))
        return

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

        chain = 'PREROUTING'
        self.add(table, chain, '-j %s' % self.portail_captif(table))

        chain = 'POSTROUTING'
        self.add(table, chain, '-j %s' % self.portail_captif_route(table))
        return

    def portail_captif_route(self, table=None, apply=False):
1108
        """PNAT les (ip,port) à laisser passer à travers le portail captif"""
1109
1110
1111
        chain = 'CAPTIF-ROUTE'

        if table == 'filter':
1112
            pretty_print(table, chain)
1113
1114
1115
1116
1117
1118
            for ip in accueil_route.keys():
                for type in accueil_route[ip].keys():
                    if type in ['udp', 'tcp']:
                        self.add(table, chain, '-p %s -d %s -m multiport --dports %s -j ACCEPT' % (type, ip, ','.join(accueil_route[ip][type])))
                        self.add(table, chain, '-p %s -s %s -m multiport --sports %s -j ACCEPT' % (type, ip, ','.join(accueil_route[ip][type])))
            self.add(table, chain, '-j REJECT')
1119
            print OK
1120
1121

        if table == 'nat':
1122
            pretty_print(table, chain)
1123
1124
1125
1126
            #intranet et wiki pour le vlan accueil
            for ip in accueil_route.keys():
                for type in accueil_route[ip].keys():
                    if type in ['udp', 'tcp']:
1127
1128
1129
1130
                        for net in NETs['accueil']:
                            self.add(table, chain, '-s %s -p %s -d %s -m multiport --dports %s -j MASQUERADE' % (net, type, ip, ','.join(accueil_route[ip][type])))
                        for net in NETs['isolement']:
                            self.add(table, chain, '-s %s -p %s -d %s -m multiport --dports %s -j MASQUERADE' % (net, type, ip, ','.join(accueil_route[ip][type])))
1131
1132
            for net in NETs['personnel-ens']:
                self.add(table, chain, '-i %s -s %s -j MASQUERADE' % (dev['app'], net))
1133
            print OK
1134
1135
1136
1137
1138
1139

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

    def portail_captif(self, table=None, apply=False):
1140
        """Redirige vers le portail captif"""
1141
1142
1143
        chain = 'PORTAIL-CAPTIF'

        if table == 'nat':
1144
            pretty_print(table, chain)
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
            for ip in accueil_route.keys():
                for type in accueil_route[ip].keys():
                    if type in ['udp', 'tcp']:
                        self.add(table, chain, '-p %s -d %s -m multiport --dports %s -j RETURN' % (type, ip, ','.join(accueil_route[ip][type])))

            for net in NETs['isolement']:
                self.add(table, chain, '-p tcp -s %s --destination-port 80 -j DNAT --to-destination 10.52.0.10' % net)

            for net in NETs['accueil']:
                self.add(table, chain, '-p tcp -s %s --destination-port 80 -j DNAT --to-destination 10.51.0.10' % net)
                self.add(table, chain, '-p udp -s %s --dport 53 -j DNAT --to 10.51.0.10' % net)
                self.add(table, chain, '-p tcp -s %s --dport 53 -j DNAT --to 10.51.0.10' % net)
1157
            print OK
1158
1159
1160
1161
1162

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

1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179

#: Associe à un ``hostname`` la classe du pare-feu correspondant
firewall = {
    'komaz' : firewall_komaz,
    'zamok' : firewall_zamok,
    'routeur' : firewall_routeur,
    'gordon' : firewall_base_routeur,
    'eap' : firewall_base_wifionly,
}

if hostname in firewall.keys():
    #: Classe du pare-feu pour la machine ``hostname`` ou :py:class:`firewall_base` si non trouvé
    firewall = firewall[hostname]
else:
    #: Classe du pare-feu pour la machine ``hostname`` ou :py:class:`firewall_base` si non trouvé
    firewall = firewall_base

1180
if __name__ == '__main__' :
1181
1182
1183

    fw = firewall()

1184
1185
1186
1187
1188
1189
    # Chaînes pouvant être recontruites
    chaines = fw.reloadable.keys()

    def __usage(txt=None) :
        if txt!=None : cprint(txt,'gras')

1190
1191
        chaines.sort()

1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
        print """Usage:
   %(p)s start   : Construction du firewall.
   %(p)s restart : Reconstruction du firewall.
   %(p)s stop    : Arrêt du firewall.
   %(p)s <noms de chaînes> : reconstruit les chaînes
Les chaînes pouvant être reconstruites sont :
   %(chaines)s
Pour reconfiguration d'IPs particulières, utiliser generate. """ % \
{ 'p' : sys.argv[0].split('/')[-1] , 'chaines' : '\n   '.join(chaines) }
        sys.exit(-1)

    # Bons arguments ?
    if len(sys.argv) == 1 :
        __usage()
    for arg in sys.argv[1:] :
        if arg in [ 'stop', 'restart', 'start' ] and len(sys.argv) != 2 :
            __usage("L'argument %s ne peut être employé que seul." % arg)

        if arg not in [ 'stop', 'restart', 'start' ] + chaines :
            __usage("L'argument %s est inconnu." % arg)

    for arg in sys.argv[1:] :
        if arg == 'stop':
            fw.stop()
        elif arg == 'start':
            fw.start()
        elif arg == 'restart':
            fw.restart()
        else:
1221
            fw.reload(arg)