aboutsummaryrefslogtreecommitdiffstats
path: root/src/msec/libmsec.py
blob: 9cd384abb0c0eed28bf0331f30b857dd7930a22a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
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
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
284
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
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
424
425
426
427
428
429
430
431
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
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
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
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
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
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
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
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
#!/usr/bin/python -O
"""This is the main msec module, responsible for all msec operations.

The following classes are defined here:

    ConfigFile: an individual config file. This class is responsible for
            configuration modification, variable searching and replacing,
            and so on.

    ConfigFiles: this file contains the entire set of modifications performed
            by msec, stored in list of ConfigFile instances. When required, all
            changes are commited back to physical files. This way, no real
            change occurs on the system until the msec app explicitly tells
            to do so.

    Log: logging class, that supports logging to terminal, a fixed log file,
            and syslog. A single log instance can be shared by all other
            classes.

    MSEC: main msec class. It contains the callback functions for all msec
            operations.

All configuration variables, and config file names are defined here as well.
"""

#---------------------------------------------------------------
# Project         : Mandriva Linux
# Module          : mseclib
# File            : libmsec.py
# Version         : $Id$
# Author          : Eugeni Dodonov
# Original Author : Frederic Lepied
# Created On      : Mon Dec 10 22:52:17 2001
# Purpose         : low-level msec functions
#---------------------------------------------------------------

import os
import grp
import gettext
import pwd
import re
import string
import commands
import time
import stat
import traceback
import sys
import glob

# logging
import logging
from logging.handlers import SysLogHandler

# configuration
import config

# localization
try:
    cat = gettext.Catalog('msec')
    _ = cat.gettext
except IOError:
    _ = str

# backup file suffix
SUFFIX = '.msec'

# list of config files

ATALLOW = '/etc/at.allow'
AUTOLOGIN = '/etc/sysconfig/autologin'
BASTILLENOLOGIN = '/etc/bastille-no-login'
CRON = '/etc/cron.d/msec'
CRONALLOW = '/etc/cron.allow'
FSTAB = '/etc/fstab'
GDM = '/etc/pam.d/gdm'
GDMCONF = '/etc/X11/gdm/custom.conf'
HALT = '/usr/bin/halt'
HOSTCONF = '/etc/host.conf'
HOSTSDENY = '/etc/hosts.deny'
INITTAB = '/etc/inittab'
ISSUE = '/etc/issue'
ISSUENET = '/etc/issue.net'
KDE = '/etc/pam.d/kde'
KDMRC = '/usr/share/config/kdm/kdmrc'
LILOCONF = '/etc/lilo.conf'
LOGINDEFS = '/etc/login.defs'
MENULST = '/boot/grub/menu.lst'
SHELLCONF = '/etc/security/shell'
MSECBIN = '/usr/sbin/msec'
MSECCRON = '/etc/cron.hourly/msec'
MSEC_XINIT = '/etc/X11/xinit.d/msec'
OPASSWD = '/etc/security/opasswd'
PASSWD = '/etc/pam.d/passwd'
POWEROFF = '/usr/bin/poweroff'
REBOOT = '/usr/bin/reboot'
SECURITYCRON = '/etc/cron.daily/msec'
SECURITYSH = '/usr/share/msec/security.sh'
SERVER = '/etc/security/msec/server'
SHADOW = '/etc/shadow'
SHUTDOWN = '/usr/bin/shutdown'
SHUTDOWNALLOW = '/etc/shutdown.allow'
SSHDCONFIG = '/etc/ssh/sshd_config'
STARTX = '/usr/bin/startx'
SYSCTLCONF = '/etc/sysctl.conf'
SYSLOGCONF = '/etc/syslog.conf'
XDM = '/etc/pam.d/xdm'
XSERVERS = '/etc/X11/xdm/Xservers'
EXPORT = '/root/.xauth/export'

# ConfigFile constants
STRING_TYPE = type('')

BEFORE=0
INSIDE=1
AFTER=2

# regexps
space = re.compile('\s')
# X server
SECURETTY = '/etc/securetty'
STARTX_REGEXP = '(\s*serverargs=".*) -nolisten tcp(.*")'
XSERVERS_REGEXP = '(\s*[^#]+/usr/bin/X .*) -nolisten tcp(.*)'
GDMCONF_REGEXP = '(\s*command=.*/X.*?) -nolisten tcp(.*)$'
KDMRC_REGEXP = re.compile('(.*?)-nolisten tcp(.*)$')
# ctrl-alt-del
CTRALTDEL_REGEXP = '^ca::ctrlaltdel:/sbin/shutdown.*'
# consolehelper
CONSOLE_HELPER = 'consolehelper'
# ssh PermitRootLogin
PERMIT_ROOT_LOGIN_REGEXP = '^\s*PermitRootLogin\s+(no|yes|without-password|forced-commands-only)'
# cron
CRON_ENTRY = '*/1 * * * *    root    /usr/share/msec/promisc_check.sh'
CRON_REGEX = '[^#]+/usr/share/msec/promisc_check.sh'
# tcp_wrappers
ALL_REGEXP = '^ALL:ALL:DENY'
ALL_LOCAL_REGEXP = '^ALL:ALL EXCEPT 127\.0\.0\.1:DENY'
# sulogin
SULOGIN_REGEXP = '~~:S:wait:/sbin/sulogin'

# {{{  helper functions
def move(old, new):
    """Renames files, deleting existent ones when necessary."""
    try:
        os.unlink(new)
    except OSError:
        pass
    try:
        os.rename(old, new)
    except:
        error('rename %s %s: %s' % (old, new, str(sys.exc_value)))

def substitute_re_result(res, s):
    for idx in range(0, (res.lastindex or 0) + 1):
        subst = res.group(idx) or ''
        s = string.replace(s, '@' + str(idx), subst)
    return s

def invert(param):
    """Returns inverse value for param. E.g., yes becomes no, and no becomes yes."""
    if param == "yes":
        return "no"
    else:
        return "yes"
# }}}

# {{{ Log
class Log:
    """Logging class. Logs to both syslog and log file"""
    def __init__(self,
                app_name="msec",
                log_syslog=True,
                log_file=True,
                log_level = logging.INFO,
                log_facility=SysLogHandler.LOG_AUTHPRIV,
                syslog_address="/dev/log",
                log_path="/var/log/msec.log",
                interactive=True,
                quiet=False):
        self.log_facility = log_facility
        self.log_path = log_path

        # buffer
        self.buffer = None

        # common logging stuff
        self.logger = logging.getLogger(app_name)

        self.quiet = quiet

        # syslog
        if log_syslog:
            try:
                self.syslog_h = SysLogHandler(facility=log_facility, address=syslog_address)
                formatter = logging.Formatter('%(name)s: %(levelname)s: %(message)s')
                self.syslog_h.setFormatter(formatter)
                self.logger.addHandler(self.syslog_h)
            except:
                print >>sys.stderr, "Logging to syslog not available: %s" % (sys.exc_value[1])
                interactive = True

        # log to file
        if log_file:
            try:
                self.file_h = logging.FileHandler(self.log_path)
                formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
                self.file_h.setFormatter(formatter)
                self.logger.addHandler(self.file_h)
            except:
                print >>sys.stderr, "Logging to '%s' not available: %s" % (self.log_path, sys.exc_value[1])
                interactive = True

        # interactive logging
        if interactive:
            self.interactive_h = logging.StreamHandler(sys.stderr)
            formatter = logging.Formatter('%(levelname)s: %(message)s')
            self.interactive_h.setFormatter(formatter)
            self.logger.addHandler(self.interactive_h)

        self.logger.setLevel(log_level)

    def info(self, message):
        """Informative message (normal msec operation)"""
        if self.quiet:
            # skip informative messages in quiet mode
            return
        if self.buffer:
            self.buffer["info"].append(message)
        else:
            self.logger.info(message)

    def error(self, message):
        """Error message (security has changed: authentication, passwords, etc)"""
        if self.buffer:
            self.buffer["error"].append(message)
        else:
            self.logger.error(message)

    def debug(self, message):
        """Debugging message"""
        if self.buffer:
            self.buffer["debug"].append(message)
        else:
            self.logger.debug(message)

    def critical(self, message):
        """Critical message (big security risk, e.g., rootkit, etc)"""
        if self.buffer:
            self.buffer["critical"].append(message)
        else:
            self.logger.critical(message)

    def warn(self, message):
        """Warning message (slight security change, permissions change, etc)"""
        if self.quiet:
            # skip warning messages in quiet mode
            return
        if self.buffer:
            self.buffer["warn"].append(message)
        else:
            self.logger.warn(message)

    def start_buffer(self):
        """Beginns message buffering"""
        self.buffer = {"info": [], "error": [], "debug": [], "critical": [], "warn": []}

    def get_buffer(self):
        """Returns buffered messages"""
        messages = self.buffer.copy()
        del self.buffer
        self.buffer = None
        return messages

# }}}

# {{{ ConfigFiles - stores references to all configuration files
class ConfigFiles:
    """This class is responsible to store references to all configuration files,
        mark them as changed, and update on disk when necessary"""
    def __init__(self, log, root=''):
        """Initializes list of ConfigFiles"""
        self.files = {}
        self.modified_files = []
        self.action_assoc = []
        self.log = log
        self.root = root

    def add(self, file, path):
        """Appends a path to list of files"""
        self.files[path] = file

    def modified(self, path):
        """Marks a file as modified"""
        if not path in self.modified_files:
            self.modified_files.append(path)

    def get_config_file(self, path, suffix=None):
        """Retreives corresponding config file"""
        try:
            return self.files[path]
        except KeyError:
            return ConfigFile(path, self, self.log, suffix=suffix, root=self.root)

    def add_config_assoc(self, regex, action):
        """Adds association between a file and an action"""
        self.log.debug("Adding custom command '%s' for '%s'" % (action, regex))
        self.action_assoc.append((re.compile(regex), action))

    def write_files(self, commit=True):
        """Writes all files back to disk"""
        for f in self.files.values():
            self.log.debug("Attempting to write %s" % f.path)
            if commit:
                f.write()

        if len(self.modified_files) > 0:
            self.log.info("%s: %s" % (config.MODIFICATIONS_FOUND, " ".join(self.modified_files)))
        else:
            self.log.info(config.MODIFICATIONS_NOT_FOUND)

        for f in self.modified_files:
            for a in self.action_assoc:
                res = a[0].search(f)
                if res:
                    s = substitute_re_result(res, a[1])
                    if commit:
                        self.log.info(_('%s modified so launched command: %s') % (f, s))
                        cmd = commands.getstatusoutput(s)
                        cmd = [0, '']
                        if cmd[0] == 0:
                            if cmd[1]:
                                self.log.info(cmd[1])
                        else:
                            self.log.error(cmd[1])
                    else:
                        self.log.info(_('%s modified so should have run command: %s') % (f, s))

# }}}

# {{{ ConfigFile - an individual config file
class ConfigFile:
    """This class represents an individual config file.
       All config files are stored in meta (which is ConfigFiles).
       All operations are performed in memory, and written when required"""
    def __init__(self, path, meta, log, root='', suffix=None):
        """Initializes a config file, and put reference to meta (ConfigFiles)"""
        self.meta=meta
        self.path = root + path
        self.is_modified = 0
        self.is_touched = 0
        self.is_deleted = 0
        self.is_moved = 0
        self.suffix = suffix
        self.lines = None
        self.sym_link = None
        self.log = log
        self.meta.add(self, path)

    def get_lines(self):
        if self.lines == None:
            file=None
            try:
                file = open(self.path, 'r')
            except IOError:
                if self.suffix:
                    try:
                        moved = self.path + self.suffix
                        file = open(moved, 'r')
                        move(moved, self.path)
                        self.meta.modified(self.path)
                    except IOError:
                        self.lines = []
                else:
                    self.lines = []
            if file:
                self.lines = string.split(file.read(), "\n")
                file.close()
        return self.lines

    def append(self, value):
        lines = self.lines
        l = len(lines)
        if l > 0 and lines[l - 1] == '':
            lines.insert(l - 1,  value)
        else:
            lines.append(value)
            lines.append('')

    def modified(self):
        self.is_modified = 1
        self.meta.modified(self.path)
        return self

    def touch(self):
        self.is_touched = 1
        self.modified()
        return self

    def symlink(self, link):
        self.sym_link = link
        self.modified()
        return self

    def exists(self):
        return os.path.lexists(self.path)
        #return os.path.exists(self.path) or (self.suffix and os.path.exists(self.path + self.suffix))

    def realpath(self):
        return os.path.realpath(self.path)

    def move(self, suffix):
        self.suffix = suffix
        self.is_moved = 1
        self.modified()

    def unlink(self):
        self.is_deleted = 1
        self.lines=[]
        self.modified()
        return self

    def is_link(self):
        '''Checks if file is a symlink and, if yes, returns the real path'''
        full = os.stat(self.path)
        if stat.S_ISLNK(full[stat.ST_MODE]):
            link = os.readlink(self.path)
        else:
            link = None
        return link

    def write(self):
        if self.is_deleted:
            if self.exists():
                try:
                    os.unlink(self.path)
                except:
                    error('unlink %s: %s' % (self.path, str(sys.exc_value)))
                self.log.info(_('deleted %s') % (self.path,))
        elif self.is_touched:
            if os.path.exists(self.path):
                try:
                    os.utime(self.path, None)
                except:
                    self.log.error('utime %s: %s' % (self.path, str(sys.exc_value)))
            elif self.suffix and os.path.exists(self.path + self.suffix):
                move(self.path + self.suffix, self.path)
                try:
                    os.utime(self.path, None)
                except:
                    self.log.error('utime %s: %s' % (self.path, str(sys.exc_value)))
            else:
                self.lines = []
                self.is_modified = 1
                file = open(self.path, 'w')
                file.close()
                self.log.info(_('touched file %s') % (self.path,))
        elif self.sym_link:
            done = 0
            if self.exists():
               full = os.lstat(self.path)
               if stat.S_ISLNK(full[stat.ST_MODE]):
                   link = os.readlink(self.path)
                   # to be fixed: resolv relative symlink
                   done = (link == self.sym_link)
               if not done:
                   try:
                       os.unlink(self.path)
                   except:
                       self.log.error('unlink %s: %s' % (self.path, str(sys.exc_value)))
                   self.log.info(_('deleted %s') % (self.path,))
            if not done:
                try:
                    os.symlink(self.sym_link, self.path)
                except:
                    self.log.error('symlink %s %s: %s' % (self.sym_link, self.path, str(sys.exc_value)))
                self.log.info(_('made symbolic link from %s to %s') % (self.sym_link, self.path))
        elif self.is_moved:
            move(self.path, self.path + self.suffix)
            self.log.info(_('moved file %s to %s') % (self.path, self.path + self.suffix))
            self.meta.modified(self.path)
        elif self.is_modified:
            content = string.join(self.lines, "\n")
            dirname = os.path.dirname(self.path)
            if not os.path.exists(dirname):
                os.makedirs(dirname)
            file = open(self.path, 'w')
            file.write(content)
            file.close()
            self.meta.modified(self.path)
        self.is_touched = 0
        self.is_modified = 0
        self.is_deleted = 0
        self.is_moved = 0

    def set_shell_variable(self, var, value, start=None, end=None):
        regex = re.compile('^' + var + '="?([^#"]+)"?(.*)')
        lines = self.get_lines()
        idx=0
        value=str(value)
        start_regexp = start

        if start:
            status = BEFORE
            start = re.compile(start)
        else:
            status = INSIDE

        if end:
            end = re.compile(end)

        idx = None
        for idx in range(0, len(lines)):
            line = lines[idx]
            if status == BEFORE:
                if start.search(line):
                    status = INSIDE
                else:
                    continue
            elif end and end.search(line):
                break
            res = regex.search(line)
            if res:
                if res.group(1) != value:
                    if space.search(value):
                        lines[idx] = var + '="' + value + '"' + res.group(2)
                    else:
                        lines[idx] = var + '=' + value + res.group(2)
                    self.modified()
                    self.log.debug(_('set variable %s to %s in %s') % (var, value, self.path,))
                return self
        if status == BEFORE:
            # never found the start delimiter
            self.log.debug('WARNING: never found regexp %s in %s, not writing changes' % (start_regexp, self.path))
            return self
        if space.search(value):
            s = var + '="' + value + '"'
        else:
            s = var + '=' + value
        if idx == None or idx == len(lines):
            self.append(s)
        else:
            lines.insert(idx, s)

        self.modified()
        self.log.info(_('set variable %s to %s in %s') % (var, value, self.path,))
        return self

    def get_shell_variable(self, var, start=None, end=None):
        # if file does not exists, fail quickly
        if not self.exists():
            return None
        if end:
            end=re.compile(end)
        if start:
            start=re.compile(start)
        regex = re.compile('^' + var + '="?([^#"]+)"?(.*)')
        lines = self.get_lines()
        llen = len(lines)
        start_idx = 0
        end_idx = llen
        if start:
            found = 0
            for idx in range(0, llen):
                if start.search(lines[idx]):
                    start_idx = idx
                    found = 1
                    break
            if found:
                for idx in range(start_idx, llen):
                    if end.search(lines[idx]):
                        end_idx = idx
                        break
        else:
            start_idx = 0
        for idx in range(end_idx - 1, start_idx - 1, -1):
            res = regex.search(lines[idx])
            if res:
                return res.group(1)
        return None

    def get_match(self, regex, replace=None):
        # if file does not exists, fail quickly
        if not self.exists():
            return None
        r=re.compile(regex)
        lines = self.get_lines()
        for idx in range(0, len(lines)):
            res = r.search(lines[idx])
            if res:
                if replace:
                    s = substitute_re_result(res, replace)
                    return s
                else:
                    return lines[idx]
        return None

    def replace_line_matching(self, regex, value, at_end_if_not_found=0, all=0, start=None, end=None):
        # if at_end_if_not_found is a string its value will be used as the string to inster
        r=re.compile(regex)
        lines = self.get_lines()
        matches = 0

        if start:
            status = BEFORE
            start = re.compile(start)
        else:
            status = INSIDE

        if end:
            end = re.compile(end)

        idx = None
        for idx in range(0, len(lines)):
            line = lines[idx]
            if status == BEFORE:
                if start.search(line):
                    status = INSIDE
                else:
                    continue
            elif end and end.search(line):
                break
            res = r.search(line)
            if res:
                s = substitute_re_result(res, value)
                matches = matches + 1
                if s != line:
                    self.log.debug("replaced in %s the line %d:\n%s\nwith the line:\n%s" % (self.path, idx, line, s))
                    lines[idx] = s
                    self.modified()
                if not all:
                    return matches
        if matches == 0 and at_end_if_not_found:
            if type(at_end_if_not_found) == STRING_TYPE:
                value = at_end_if_not_found
            self.log.debug("appended in %s the line:\n%s" % (self.path, value))
            if idx == None or idx == len(lines):
                self.append(value)
            else:
                lines.insert(idx, value)
            self.modified()
            matches = matches + 1
        return matches

    def insert_after(self, regex, value, at_end_if_not_found=0, all=0):
        matches = 0
        r=re.compile(regex)
        lines = self.get_lines()
        for idx in range(0, len(lines)):
            res = r.search(lines[idx])
            if res:
                s = substitute_re_result(res, value)
                self.log.debug("inserted in %s after the line %d:\n%s\nthe line:\n%s" % (self.path, idx, lines[idx], s))
                lines.insert(idx+1, s)
                self.modified()
                matches = matches + 1
                if not all:
                    return matches
        if matches == 0 and at_end_if_not_found:
            self.log.debug("appended in %s the line:\n%s" % (self.path, value))
            self.append(value)
            self.modified()
            matches = matches + 1
        return matches

    def insert_before(self, regex, value, at_top_if_not_found=0, all=0):
        matches = 0
        r=re.compile(regex)
        lines = self.get_lines()
        for idx in range(0, len(lines)):
            res = r.search(lines[idx])
            if res:
                s = substitute_re_result(res, value)
                self.log.debug("inserted in %s before the line %d:\n%s\nthe line:\n%s" % (self.path, idx, lines[idx], s))
                lines.insert(idx, s)
                self.modified()
                matches = matches + 1
                if not all:
                    return matches
        if matches == 0 and at_top_if_not_found:
            self.log.debug("inserted at the top of %s the line:\n%s" % (self.path, value))
            lines.insert(0, value)
            self.modified()
            matches = matches + 1
        return matches

    def insert_at(self, idx, value):
        lines = self.get_lines()
        try:
            lines.insert(idx, value)
            self.log.debug("inserted in %s at the line %d:\n%s" % (self.path, idx, value))
            self.modified()
            return 1
        except KeyError:
            return 0

    def remove_line_matching(self, regex, all=0):
        matches = 0
        r=re.compile(regex)
        lines = self.get_lines()
        for idx in range(len(lines) - 1, -1, -1):
            res = r.search(lines[idx])
            if res:
                self.log.debug("removing in %s the line %d:\n%s" % (self.path, idx, lines[idx]))
                lines.pop(idx)
                self.modified()
                matches = matches + 1
                if not all:
                    return matches
        return matches
# }}}

# {{{ MSEC - main class
class MSEC:
    """Main msec class. Contains all functions and performs the actions"""
    def __init__(self, log, root='', plugins=config.PLUGINS_DIR):
        """Initializes config files and associations"""
        # all config files
        self.log = log
        self.root = root
        self.configfiles = ConfigFiles(log, root=root)

        # associate helper commands with files
        self.configfiles.add_config_assoc(INITTAB, '/sbin/telinit q')
        self.configfiles.add_config_assoc('/etc(?:/rc.d)?/init.d/(.+)', '[ -f /var/lock/subsys/@1 ] && @0 reload')
        self.configfiles.add_config_assoc(SYSCTLCONF, '/sbin/sysctl -e -p /etc/sysctl.conf')
        self.configfiles.add_config_assoc(SSHDCONFIG, '[ -f /var/lock/subsys/sshd ] && /etc/rc.d/init.d/sshd restart')
        self.configfiles.add_config_assoc(LILOCONF, '[ `/usr/sbin/detectloader` = LILO ] && /sbin/lilo')
        self.configfiles.add_config_assoc(SYSLOGCONF, '[ -f /var/lock/subsys/syslog ] && service syslog reload')
        self.configfiles.add_config_assoc('^/etc/issue$', '/usr/bin/killall mingetty')

        # plugins
        self.init_plugins(plugins)

    def init_plugins(self, path=config.PLUGINS_DIR):
        """Loads msec plugins from path"""
        self.plugins = {}
        plugin_files = glob.glob("%s/*.py" % path)
        plugin_r = re.compile("plugins/(.*).py")
        sys.path.insert(0, path)
        for file in plugin_files:
            f = plugin_r.findall(file)
            if f:
                plugin_f = f[0]
                try:
                    plugin = __import__(plugin_f, fromlist=[path])
                    if not hasattr(plugin, "PLUGIN"):
                        # not a valid plugin
                        continue
                    self.log.debug("Loading plugin %s" % file)
                    plugin_name = getattr(plugin, "PLUGIN")
                    plugin_class = getattr(plugin, plugin_name)
                    plugin = plugin_class(log=self.log, configfiles=self.configfiles, root=self.root)
                    self.plugins[plugin_name] = plugin
                    self.log.debug("Loaded plugin '%s'" % plugin_f)
                except:
                    self.log.error(_("Error loading plugin '%s' from %s: %s") % (plugin_f, file, sys.exc_value))

    def reset(self):
        """Resets the configuration"""
        self.log.debug("Resetting msec data.")
        self.configfiles = ConfigFiles(self.log, root=self.root)

    def get_action(self, name):
        """Determines correspondent function for requested action."""
        # finding out what function to call
        try:
            plugin_, callback = name.split(".", 1)
        except:
            # bad format?
            self.log.error(_("Invalid callback: %s") % (name))
            return None
        # is it a main function or a plugin?
        if plugin_ == config.MAIN_LIB:
            plugin = self
        else:
            if plugin_ in self.plugins:
                plugin = self.plugins[plugin_]
            else:
                self.log.info(_("Plugin %s not found") % plugin_)
                return self.log.info
                return None
        try:
            func = getattr(plugin, callback)
            return func
        except:
            self.log.info(_("Not supported function '%s' in '%s'") % (callback, plugin))
            traceback.print_exc()
            return None

    def commit(self, really_commit=True):
        """Commits changes"""
        if not really_commit:
            self.log.info(_("In check-only mode, nothing is written back to disk."))
        self.configfiles.write_files(really_commit)

    def apply(self, curconfig):
        '''Applies configuration from a MsecConfig instance'''
        # first, reset previous msec data
        self.reset()
        # process all options
        for opt in curconfig.list_options():
            # Determines correspondent function
            action = None
            callback = config.find_callback(opt)
            valid_params = config.find_valid_params(opt)
            if callback:
                action = self.get_action(callback)
            if not action:
                # The required functionality is not supported
                self.log.info(_("'%s' is not available in this version") % opt)
                continue
            self.log.debug("Processing action %s: %s(%s)" % (opt, callback, curconfig.get(opt)))
            # validating parameters
            param = curconfig.get(opt)
            # if param is None, this option is to be skipped
            if param == None:
                self.log.debug("Skipping %s" % opt)
                continue
            if param not in valid_params and '*' not in valid_params:
                self.log.error(_("Invalid parameter for %s: '%s'. Valid parameters: '%s'.") % (opt,
                            param, valid_params))
                continue
            action(curconfig.get(opt))

    def base_level(self, param):
        """Defines the base security level, on top of which the current configuration is based."""
        pass

    def create_server_link(self, param):
        '''  Creates the symlink /etc/security/msec/server to point to /etc/security/msec/server.SERVER_LEVEL. The /etc/security/msec/server is used by chkconfig --add to decide to add a service if it is present in the file during the installation of packages. By default, two presets are provided: local (which only enables local services) and remote (which also enables some remote services considered safe). Note that the allowed services must be placed manually into the server.SERVER_LEVEL files when necessary.'''
        server = self.configfiles.get_config_file(SERVER)

        if param == "no":
            if server.exists():
                self.log.info(_('Allowing unrestricted chkconfig for packages'))
                server.unlink()
        else:
            newpath = "%s.%s" % (SERVER, param)
            if server.realpath() != newpath:
                self.log.info(_('Restricting chkconfig for packages according to "%s" profile') % param)
                server.symlink(newpath)

    def set_root_umask(self, umask):
        '''  Set the root umask.'''
        msec = self.configfiles.get_config_file(SHELLCONF)

        val = msec.get_shell_variable('UMASK_ROOT')

        if val != umask:
            self.log.info(_('Setting root umask to %s') % (umask))
            msec.set_shell_variable('UMASK_ROOT', umask)

    def set_user_umask(self, umask):
        '''  Set the user umask.'''
        msec = self.configfiles.get_config_file(SHELLCONF)

        val = msec.get_shell_variable('UMASK_USER')

        if val != umask:
            self.log.info(_('Setting users umask to %s') % (umask))
            msec.set_shell_variable('UMASK_USER', umask)

    def allow_x_connections(self, arg):
        '''  Allow local users to connect to X server. Accepted arguments: yes (all connections are allowed), local (only local connection), no (no connection).'''

        xinit = self.configfiles.get_config_file(MSEC_XINIT)
        val = xinit.get_match('/usr/bin/xhost\s*(\+\s*[^#]*)', '@1')

        if val:
            if val == '+':
                val = "yes"
            elif val == "+ localhost":
                val = "local"
            else:
                val = "no"
        else:
            val = "no"

        if val != arg:
            if arg == "yes":
                self.log.info(_('Allowing users to connect X server from everywhere'))
                xinit.replace_line_matching('/usr/bin/xhost', '/usr/bin/xhost +', 1)
            elif arg == "local":
                self.log.info(_('Allowing users to connect X server from localhost'))
                xinit.replace_line_matching('/usr/bin/xhost', '/usr/bin/xhost + localhost', 1)
            elif arg == "no":
                self.log.info(_('Restricting X server connection to the console user'))
                xinit.remove_line_matching('/usr/bin/xhost', 1)
            else:
                self.log.error(_('invalid allow_x_connections arg: %s') % arg)

    def allow_xserver_to_listen(self, arg):
        '''  Allow X server to accept connections from network on tcp port 6000.'''

        startx = self.configfiles.get_config_file(STARTX)
        xservers = self.configfiles.get_config_file(XSERVERS)
        gdmconf = self.configfiles.get_config_file(GDMCONF)
        kdmrc = self.configfiles.get_config_file(KDMRC)

        val_startx = startx.get_match(STARTX_REGEXP)
        val_xservers = xservers.get_match(XSERVERS_REGEXP)
        val_gdmconf = gdmconf.get_shell_variable('DisallowTCP')
        str = kdmrc.get_shell_variable('ServerArgsLocal', 'X-\*-Core', '^\s*$')
        if str:
            val_kdmrc = KDMRC_REGEXP.search(str)
        else:
            val_kdmrc = None

        # TODO: better check for file existance

        if arg == "yes":
            if val_startx or val_xservers or val_kdmrc or val_gdmconf != 'false':
                self.log.info(_('Allowing the X server to listen to tcp connections'))
                if startx.exists():
                    startx.replace_line_matching(STARTX_REGEXP, '@1@2')
                if xservers.exists():
                    xservers.replace_line_matching(XSERVERS_REGEXP, '@1@2', 0, 1)
                if gdmconf.exists():
                    gdmconf.set_shell_variable('DisallowTCP', 'false', '\[security\]', '^\s*$')
                if kdmrc.exists():
                    kdmrc.replace_line_matching('^(ServerArgsLocal=.*?)-nolisten tcp(.*)$', '@1@2', 0, 0, 'X-\*-Core', '^\s*$')
        else:
            if not val_startx or not val_xservers or not val_kdmrc or val_gdmconf != 'true':
                self.log.info(_('Forbidding the X server to listen to tcp connection'))
                if not val_startx:
                    startx.exists() and startx.replace_line_matching('serverargs="(.*?)( -nolisten tcp)?"', 'serverargs="@1 -nolisten tcp"')
                if not val_xservers:
                    xservers.exists() and xservers.replace_line_matching('(\s*[^#]+/usr/bin/X .*?)( -nolisten tcp)?$', '@1 -nolisten tcp', 0, 1)
                if val_gdmconf != 'true':
                    gdmconf.exists() and gdmconf.set_shell_variable('DisallowTCP', 'true', '\[security\]', '^\s*$')
                if not val_kdmrc:
                    kdmrc.exists() and kdmrc.replace_line_matching('^(ServerArgsLocal=.*)$', '@1 -nolisten tcp', 'ServerArgsLocal=-nolisten tcp', 0, 'X-\*-Core', '^\s*$')

    def set_shell_timeout(self, val):
        '''  Set the shell timeout. A value of zero means no timeout.'''
        msec = self.configfiles.get_config_file(SHELLCONF)
        try:
            timeout = int(val)
        except:
            self.log.error(_('Invalid shell timeout "%s"') % val)
            return

        old = msec.get_shell_variable('TMOUT')
        if old:
            old = int(old)

        if old != timeout:
            self.log.info(_('Setting shell timeout to %s') % timeout)
            msec.set_shell_variable('TMOUT', timeout)

    def set_shell_history_size(self, size):
        '''  Set shell commands history size. A value of -1 means unlimited.'''
        try:
            size = int(size)
        except:
            self.log.error(_('Invalid shell history size "%s"') % size)
            return

        msec = self.configfiles.get_config_file(SHELLCONF)

        val = msec.get_shell_variable('HISTFILESIZE')
        if val:
            val = int(val)

        if size >= 0:
            if val != size:
                self.log.info(_('Setting shell history size to %s') % size)
                msec.set_shell_variable('HISTFILESIZE', size)
        else:
            if val != None:
                self.log.info(_('Removing limit on shell history size'))
                msec.remove_line_matching('^HISTFILESIZE=')

    def set_win_parts_umask(self, umask):
        ''' Set umask option for mounting vfat and ntfs partitions. If umask is '0', default system umask is used.'''
        fstab = self.configfiles.get_config_file(FSTAB)
        try:
            test_umask = int(umask)
        except:
            self.log.error(_('Invalid file system umask "%s"') % umask)
            return
        if umask == "0":
            fstab.replace_line_matching("(.*\s(vfat|ntfs|ntfs-3g)\s+)umask=\d+(\s.*)", "@1defaults@3", 0, 1)
            fstab.replace_line_matching("(.*\s(vfat|ntfs|ntfs-3g)\s+)umask=\d+,(.*)", "@1@3", 0, 1)
            fstab.replace_line_matching("(.*\s(vfat|ntfs|ntfs-3g)\s+\S+),umask=\d+(.*)", "@1@3", 0, 1)
        else:
            fstab.replace_line_matching("(.*\s(vfat|ntfs|ntfs-3g)\s+\S*)umask=\d+(.*)", "@1umask="+umask+"@3", 0, 1)
            fstab.replace_line_matching("(.*\s(vfat|ntfs|ntfs-3g)\s+)(?!.*umask=)(\S+)(.*)", "@1@3,umask="+umask+"@4", 0, 1)

    def allow_reboot(self, arg):
        '''  Allow system reboot and shutdown to local users.'''
        shutdownallow = self.configfiles.get_config_file(SHUTDOWNALLOW)
        sysctlconf = self.configfiles.get_config_file(SYSCTLCONF)
        kdmrc = self.configfiles.get_config_file(KDMRC)
        gdmconf = self.configfiles.get_config_file(GDMCONF)
        inittab = self.configfiles.get_config_file(INITTAB)
        shutdown = self.configfiles.get_config_file(SHUTDOWN)
        poweroff = self.configfiles.get_config_file(POWEROFF)
        reboot = self.configfiles.get_config_file(REBOOT)
        halt = self.configfiles.get_config_file(HALT)

        val_shutdownallow = shutdownallow.exists()
        val_shutdown = shutdown.exists()
        val_poweroff = poweroff.exists()
        val_reboot = reboot.exists()
        val_halt = halt.exists()
        val_sysctlconf = sysctlconf.get_shell_variable('kernel.sysrq')
        val_inittab = inittab.get_match(CTRALTDEL_REGEXP)
        val_gdmconf = gdmconf.get_shell_variable('SystemMenu')
        oldval_kdmrc = kdmrc.get_shell_variable('AllowShutdown', 'X-:\*-Core', '^\s*$')

        if arg == "yes":
            if val_shutdownallow or not val_shutdown or not val_poweroff or not val_reboot or not val_halt:
                self.log.info(_('Allowing reboot and shutdown to the console user'))
                shutdownallow.exists() and shutdownallow.move(SUFFIX)
                shutdown.exists() or shutdown.symlink(CONSOLE_HELPER)
                poweroff.exists() or poweroff.symlink(CONSOLE_HELPER)
                reboot.exists() or reboot.symlink(CONSOLE_HELPER)
                halt.exists() or halt.symlink(CONSOLE_HELPER)
            if val_sysctlconf == '0':
                self.log.info(_('Allowing SysRq key to the console user'))
                sysctlconf.set_shell_variable('kernel.sysrq', 1)
            if val_gdmconf == 'false':
                self.log.info(_('Allowing Shutdown/Reboot in GDM'))
                gdmconf.exists() and gdmconf.set_shell_variable('SystemMenu', 'true', '\[greeter\]', '^\s*$')
            if kdmrc.exists():
                if oldval_kdmrc != 'All':
                    self.log.info(_('Allowing Shutdown/Reboot in KDM'))
                    kdmrc.set_shell_variable('AllowShutdown', 'All', 'X-:\*-Core', '^\s*$')
            if not val_inittab:
                self.log.info(_('Allowing Ctrl-Alt-Del from console'))
                inittab.exists() and inittab.replace_line_matching(CTRALTDEL_REGEXP, 'ca::ctrlaltdel:/sbin/shutdown -t3 -r now', 1)
        else:
            if not val_shutdownallow or val_shutdown or val_poweroff or val_reboot or val_halt:
                self.log.info(_('Forbidding reboot and shutdown to the console user'))
                if not shutdownallow.exists():
                    self.configfiles.get_config_file(SHUTDOWNALLOW, SUFFIX).touch()
                shutdown.exists() and shutdown.unlink()
                poweroff.exists() and poweroff.unlink()
                reboot.exists() and reboot.unlink()
                halt.exists() and halt.unlink()
            if val_sysctlconf != '0':
                self.log.info(_('Forbidding SysRq key to the console user'))
                sysctlconf.set_shell_variable('kernel.sysrq', 0)
            if val_gdmconf != 'false':
                self.log.info(_('Forbidding Shutdown/Reboot in GDM'))
                gdmconf.exists() and gdmconf.set_shell_variable('SystemMenu', 'false', '\[greeter\]', '^\s*$')
            if kdmrc.exists():
                if oldval_kdmrc != 'None':
                    self.log.info(_('Forbidding Shutdown/Reboot in KDM'))
                    kdmrc.set_shell_variable('AllowShutdown', 'None', 'X-:\*-Core', '^\s*$')
            if val_inittab:
                self.log.info(_('Forbidding Ctrl-Alt-Del from console'))
                inittab.exists() and inittab.remove_line_matching(CTRALTDEL_REGEXP)

    def allow_user_list(self, arg):
        '''  Allow display managers (kdm and gdm) to display list of local users.'''
        kdmrc = self.configfiles.get_config_file(KDMRC)
        gdmconf = self.configfiles.get_config_file(GDMCONF)

        oldval_gdmconf = gdmconf.get_shell_variable('Browser')
        oldval_kdmrc = kdmrc.get_shell_variable('ShowUsers', 'X-\*-Greeter', '^\s*$')

        if arg == "yes":
            if kdmrc.exists():
                if oldval_kdmrc != 'NotHidden':
                    self.log.info(_("Allowing list of users in KDM"))
                    kdmrc.set_shell_variable('ShowUsers', 'NotHidden', 'X-\*-Greeter', '^\s*$')
            if gdmconf.exists():
                if oldval_gdmconf != 'true':
                    self.log.info(_("Allowing list of users in GDM"))
                    gdmconf.set_shell_variable('Browser', 'true')
        else:
            if kdmrc.exists():
                if oldval_kdmrc != 'Selected':
                    self.log.info(_("Forbidding list of users in KDM"))
                    kdmrc.set_shell_variable('ShowUsers', 'Selected', 'X-\*-Greeter', '^\s*$')
            if gdmconf.exists():
                if oldval_gdmconf != 'false':
                    self.log.info(_("Forbidding list of users in GDM"))
                    gdmconf.set_shell_variable('Browser', 'false')

    def allow_remote_root_login(self, arg):
        '''  Allow remote root login via sshd. If yes, login is allowed. If without-password, only public-key authentication logins are allowed. See sshd_config(5) man page for more information.'''
        sshd_config = self.configfiles.get_config_file(SSHDCONFIG)

        if not sshd_config.exists():
            return

        val = sshd_config.get_match(PERMIT_ROOT_LOGIN_REGEXP, '@1')

        if val != arg:
            if arg == "yes":
                self.log.info(_('Allowing remote root login'))
                sshd_config.exists() and sshd_config.replace_line_matching(PERMIT_ROOT_LOGIN_REGEXP,
                                                                           'PermitRootLogin yes', 1)
            elif arg == "no":
                self.log.info(_('Forbidding remote root login'))
                sshd_config.exists() and sshd_config.replace_line_matching(PERMIT_ROOT_LOGIN_REGEXP,
                                                                           'PermitRootLogin no', 1)
            elif arg == "without-password":
                self.log.info(_('Allowing remote root login only by passphrase'))
                sshd_config.exists() and sshd_config.replace_line_matching(PERMIT_ROOT_LOGIN_REGEXP,
                                                                           'PermitRootLogin without-password', 1)

    def allow_autologin(self, arg):
        '''  Allow autologin.'''
        autologin = self.configfiles.get_config_file(AUTOLOGIN)

        val = autologin.get_shell_variable('AUTOLOGIN')

        if val != arg:
            if arg == "yes":
                self.log.info(_('Allowing autologin'))
                autologin.set_shell_variable('AUTOLOGIN', 'yes')
            else:
                self.log.info(_('Forbidding autologin'))
                autologin.set_shell_variable('AUTOLOGIN', 'no')

    def password_loader(self, value):
        '''Unused'''
        self.log.info(_('Activating password in boot loader'))
        liloconf = self.configfiles.get_config_file(LILOCONF)
        liloconf.exists() and (liloconf.replace_line_matching('^password=', 'password="' + value + '"', 0, 1) or \
                               liloconf.insert_after('^boot=', 'password="' + value + '"')) and \
                               Perms.chmod(liloconf.path, 0600)
        # TODO encrypt password in grub
        menulst = self.configfiles.get_config_file(MENULST)
        menulst.exists() and (menulst.replace_line_matching('^password\s', 'password "' + value + '"') or \
                              menulst.insert_at(0, 'password "' + value + '"')) and \
                              Perms.chmod(menulst.path, 0600)
        # TODO add yaboot support

    def nopassword_loader(self):
        '''Unused'''
        self.log.info(_('Removing password in boot loader'))
        liloconf = self.configfiles.get_config_file(LILOCONF)
        liloconf.exists() and liloconf.remove_line_matching('^password=', 1)
        menulst = self.configfiles.get_config_file(MENULST)
        menulst.exists() and menulst.remove_line_matching('^password\s')

    def enable_console_log(self, arg, expr='*.*', dev='tty12'):
        ''' Log syslog messages on console terminal 12.'''

        syslogconf = self.configfiles.get_config_file(SYSLOGCONF)

        val = syslogconf.get_match('\s*[^#]+/dev/([^ ]+)', '@1')

        if arg == "yes":
            if dev != val:
                self.log.info(_('Enabling log on console'))
                syslogconf.exists() and syslogconf.replace_line_matching('\s*[^#]+/dev/', expr + ' /dev/' + dev, 1)
        else:
            if val != None:
                self.log.info(_('Disabling log on console'))
                syslogconf.exists() and syslogconf.remove_line_matching('\s*[^#]+/dev/')

    def enable_security_check(self, arg):
        '''  Activate daily security check.'''
        cron = self.configfiles.get_config_file(CRON)
        cron.remove_line_matching('[^#]+/usr/share/msec/security.sh')

        securitycron = self.configfiles.get_config_file(SECURITYCRON)

        if arg == "yes":
            if not securitycron.exists():
                self.log.info(_('Activating daily security check'))
                securitycron.symlink(SECURITYSH)
        else:
            if securitycron.exists():
                self.log.info(_('Disabling daily security check'))
                securitycron.unlink()

    def authorize_services(self, arg):
        ''' Allow full access to network services controlled by tcp_wrapper (see hosts.deny(5)). If yes, all services are allowed. If local, only connections to local services are authorized. If no, the services must be authorized manually in /etc/hosts.allow (see hosts.allow(5)).'''

        hostsdeny = self.configfiles.get_config_file(HOSTSDENY)

        if hostsdeny.get_match(ALL_REGEXP):
            val = "no"
        elif hostsdeny.get_match(ALL_LOCAL_REGEXP):
            val = "local"
        else:
            val = "yes"

        if val != arg:
            if arg == "yes":
                self.log.info(_('Authorizing all services'))
                hostsdeny.remove_line_matching(ALL_REGEXP, 1)
                hostsdeny.remove_line_matching(ALL_LOCAL_REGEXP, 1)
            elif arg == "no":
                self.log.info(_('Disabling all services'))
                hostsdeny.remove_line_matching(ALL_LOCAL_REGEXP, 1)
                hostsdeny.replace_line_matching(ALL_REGEXP, 'ALL:ALL:DENY', 1)
            elif arg == "local":
                self.log.info(_('Disabling non local services'))
                hostsdeny.remove_line_matching(ALL_REGEXP, 1)
                hostsdeny.replace_line_matching(ALL_LOCAL_REGEXP, 'ALL:ALL EXCEPT 127.0.0.1:DENY', 1)

    def set_zero_one_variable(self, file, variable, value, one_msg, zero_msg):
        ''' Helper function for enable_ip_spoofing_protection, accept_icmp_echo, accept_broadcasted_icmp_echo,
        # accept_bogus_error_responses and enable_log_strange_packets.'''
        f = self.configfiles.get_config_file(file)
        curvalue = f.get_shell_variable(variable)
        if value == "yes":
            value = "1"
        else:
            value = "0"
        if value != curvalue:
            if value == "1":
                self.log.info(one_msg)
                f.set_shell_variable(variable, 1)
            else:
                self.log.info(zero_msg)
                f.set_shell_variable(variable, 0)

    def enable_ip_spoofing_protection(self, arg, alert=1):
        '''  Enable IP spoofing protection.'''
        self.set_zero_one_variable(SYSCTLCONF, 'net.ipv4.conf.all.rp_filter', arg, 'Enabling ip spoofing protection', 'Disabling ip spoofing protection')

    def enable_dns_spoofing_protection(self, arg, alert=1):
        '''  Enable name resolution spoofing protection.'''
        hostconf = self.configfiles.get_config_file(HOSTCONF)

        val = hostconf.get_match('nospoof\s+on')

        if arg:
            if not val:
                self.log.info(_('Enabling name resolution spoofing protection'))
                hostconf.replace_line_matching('nospoof', 'nospoof on', 1)
                hostconf.replace_line_matching('spoofalert', 'spoofalert on', (alert != 0))
        else:
            if val:
                self.log.info(_('Disabling name resolution spoofing protection'))
                hostconf.remove_line_matching('nospoof')
                hostconf.remove_line_matching('spoofalert')

    def accept_icmp_echo(self, arg):
        ''' Accept ICMP echo.'''
        self.set_zero_one_variable(SYSCTLCONF, 'net.ipv4.icmp_echo_ignore_all', invert(arg), 'Ignoring icmp echo', 'Accepting icmp echo')

    def accept_broadcasted_icmp_echo(self, arg):
        ''' Accept broadcasted ICMP echo.'''
        self.set_zero_one_variable(SYSCTLCONF, 'net.ipv4.icmp_echo_ignore_broadcasts', invert(arg), 'Ignoring broadcasted icmp echo', 'Accepting broadcasted icmp echo')

    def accept_bogus_error_responses(self, arg):
        '''  Accept bogus IPv4 error messages.'''
        self.set_zero_one_variable(SYSCTLCONF, 'net.ipv4.icmp_ignore_bogus_error_responses', invert(arg), 'Ignoring bogus icmp error responses', 'Accepting bogus icmp error responses')

    def enable_log_strange_packets(self, arg):
        '''  Enable logging of strange network packets.'''
        self.set_zero_one_variable(SYSCTLCONF, 'net.ipv4.conf.all.log_martians', arg, 'Enabling logging of strange packets', 'Disabling logging of strange packets')

    def enable_sulogin(self, arg):
        ''' Ask for root password when going to single user level (man sulogin(8)).'''
        inittab = self.configfiles.get_config_file(INITTAB)

        val = inittab.get_match(SULOGIN_REGEXP)

        if arg == "yes":
            if not val:
                self.log.info(_('Enabling sulogin in single user runlevel'))
                inittab.replace_line_matching('[^#]+:S:', '~~:S:wait:/sbin/sulogin', 1)
        else:
            if val:
                self.log.info(_('Disabling sulogin in single user runlevel'))
                inittab.remove_line_matching('~~:S:wait:/sbin/sulogin')

    def enable_msec_cron(self, arg):
        '''  Perform hourly security check for changes in system configuration.'''
        mseccron = self.configfiles.get_config_file(MSECCRON)

        val = mseccron.exists()

        if arg == "yes":
            if not val:
                self.log.info(_('Enabling msec periodic runs'))
                mseccron.symlink(MSECBIN)
        else:
            if val:
                self.log.info(_('Disabling msec periodic runs'))
                mseccron.unlink()

    def enable_at_crontab(self, arg):
        ''' Enable crontab and at for users. Put allowed users in /etc/cron.allow and /etc/at.allow (see man at(1) and crontab(1)).'''
        cronallow = self.configfiles.get_config_file(CRONALLOW)
        atallow = self.configfiles.get_config_file(ATALLOW)

        val_cronallow = cronallow.get_match('root')
        val_atallow = atallow.get_match('root')

        if arg == "yes":
            if val_cronallow or val_atallow:
                self.log.info(_('Enabling crontab and at'))
                if val_cronallow:
                    cronallow.exists() and cronallow.move(SUFFIX)
                if val_atallow:
                    atallow.exists() and atallow.move(SUFFIX)
        else:
            if not val_cronallow or not val_atallow:
                self.log.info(_('Disabling crontab and at'))
                cronallow.replace_line_matching('root', 'root', 1)
                atallow.replace_line_matching('root', 'root', 1)

    def allow_xauth_from_root(self, arg):
        ''' Allow to export display when passing from the root account to the other users. See pam_xauth(8) for more details.'''
        export = self.configfiles.get_config_file(EXPORT)

        allow = export.get_match('^\*$')

        if arg == 'yes':
            if not allow:
                self.log.info(_('Allowing export display from root'))
                export.insert_at(0, '*')
        else:
            if allow:
                self.log.info(_('Forbidding export display from root'))
                export.remove_line_matching('^\*$')

    def check_promisc(self, param):
        '''  Activate ethernet cards promiscuity check.'''
        cron = self.configfiles.get_config_file(CRON)

        val = cron.get_match(CRON_REGEX)

        if param == "yes":
            if val != CRON_ENTRY:
                self.log.info(_('Activating periodic promiscuity check'))
                cron.replace_line_matching(CRON_REGEX, CRON_ENTRY, 1)
        else:
            if val:
                self.log.info(_('Disabling periodic promiscuity check'))
                cron.remove_line_matching('[^#]+/usr/share/msec/promisc_check.sh')

    def allow_root_login(self, arg):
        '''  Allow direct root login on terminal.'''
        securetty = self.configfiles.get_config_file(SECURETTY)
        kde = self.configfiles.get_config_file(KDE)
        gdm = self.configfiles.get_config_file(GDM)
        gdmconf = self.configfiles.get_config_file(GDMCONF)
        xdm = self.configfiles.get_config_file(XDM)

        val = {}
        val_kde = kde.get_match('auth required (?:/lib/security/)?pam_listfile.so onerr=succeed item=user sense=deny file=/etc/bastille-no-login')
        val_gdm = gdm.get_match('auth required (?:/lib/security/)?pam_listfile.so onerr=succeed item=user sense=deny file=/etc/bastille-no-login')
        val_xdm = xdm.get_match('auth required (?:/lib/security/)?pam_listfile.so onerr=succeed item=user sense=deny file=/etc/bastille-no-login')
        num = 0
        for n in range(1, 7):
            s = 'tty' + str(n)
            if securetty.get_match(s):
                num = num + 1
            s = 'vc/' + str(n)
            if securetty.get_match(s):
                num = num + 1

        if arg == "yes":
            if val_kde or val_gdm or val_xdm or num != 12:
                self.log.info(_('Allowing direct root login'))
                if gdmconf.exists():
                    gdmconf.set_shell_variable('ConfigAvailable', 'true', '\[greeter\]', '^\s*$')

                for cnf in [kde, gdm, xdm]:
                    if cnf.exists():
                        cnf.remove_line_matching('^auth\s*required\s*(?:/lib/security/)?pam_listfile.so.*bastille-no-login', 1)

                for n in range(1, 7):
                    s = 'tty' + str(n)
                    securetty.replace_line_matching(s, s, 1)
                    s = 'vc/' + str(n)
                    securetty.replace_line_matching(s, s, 1)
        else:
            if gdmconf.exists():
                gdmconf.set_shell_variable('ConfigAvailable', 'false', '\[greeter\]', '^\s*$')
            if (kde.exists() and not val_kde) or (gdm.exists() and not val_gdm) or (xdm.exists() and not val_xdm) or num > 0:
                self.log.info(_('Forbidding direct root login'))

                bastillenologin = self.configfiles.get_config_file(BASTILLENOLOGIN)
                bastillenologin.replace_line_matching('^\s*root', 'root', 1)

                # TODO: simplify this
                for cnf in [kde, gdm, xdm]:
                    if cnf.exists():
                        (cnf.replace_line_matching('^auth\s*required\s*(?:/lib/security/)?pam_listfile.so.*bastille-no-login',
                            'auth required pam_listfile.so onerr=succeed item=user sense=deny file=/etc/bastille-no-login') or
                          cnf.insert_at(0, 'auth required pam_listfile.so onerr=succeed item=user sense=deny file=/etc/bastille-no-login'))
                securetty.remove_line_matching('.+', 1)

    # The following checks are run from crontab. We only have these functions here
    # to get their descriptions.

    def check_security(self, param):
        """ Enable daily security checks."""
        self.enable_security_check(param)
        pass

    def check_perms(self, param):
        """ Enable periodic permission checking for system files."""
        pass

    def check_user_files(self, param):
        """ Enable permission checking on users' files that should not be owned by someone else, or writable."""
        pass

    def check_suid_root(self, param):
        """ Enable checking for additions/removals of suid root files."""
        pass

    def check_suid_md5(self, param):
        """ Enable checksum verification for suid files."""
        pass

    def check_sgid(self, param):
        """ Enable checking for additions/removals of sgid files."""
        pass

    def check_writable(self, param):
        """ Enable checking for files/directories writable by everybody."""
        pass

    def check_unowned(self, param):
        """ Enable checking for unowned files."""
        pass

    def check_open_port(self, param):
        """ Enable checking for open network ports."""
        pass

    def check_passwd(self, param):
        """ Enable password-related checks, such as empty passwords and strange super-user accounts."""
        pass

    def check_shadow(self, param):
        """ Enable checking for empty passwords in /etc/shadow (man shadow(5))."""
        pass

    def check_chkrootkit(self, param):
        """ Enable checking for known rootkits using chkrootkit."""
        pass

    def check_rpm(self, param):
        """ Enable verification of installed RPM packages."""
        pass

    def tty_warn(self, param):
        """ Enable periodic security check results to terminal."""
        pass

    def mail_warn(self, param):
        """ Send security check results by email."""
        pass

    def mail_empty_content(self, param):
        """ Send mail reports even if no changes were detected."""
        pass

    def syslog_warn(self, param):
        """ Enables logging of periodic checks to system log."""
        pass

    def mail_user(self, param):
        """ User email to receive security notifications."""
        pass

    def check_shosts(self, param):
        """ Enable checking for dangerous options in users' .rhosts/.shosts files."""
        pass

    def enable_sudo(self, param):
        """Allow users to authenticate with their passwords for sudo. If this parameter is set to 'wheel', users must belong to the 'wheel' group to be able to use sudo"""
        pass

    def notify_warn(self, param):
        """Show security notifications in system tray using libnotify."""
        pass

    # bogus functions
    def enable_startup_msec(self, param):
        """Enforce MSEC settings on system startup"""
        pass

    def enable_startup_perms(self, param):
        """Enforce MSEC file directory permissions on system startup. If this parameter is set to 'enforce', system permissions will be enforced automatically, according to system security settings."""
        pass


# }}}

# {{{ PERMS - permissions handling
class PERMS:
    """Permission checking/enforcing."""
    def __init__(self, log, root=''):
        """Initializes internal variables"""
        self.log = log
        self.root = root
        self.USER = {}
        self.GROUP = {}
        self.USERID = {}
        self.GROUPID = {}
        self.files = {}
        self.fs_regexp = self.build_non_localfs_regexp()

    def get_user_id(self, name):
        '''Caches and retreives user id correspondent to name'''
        try:
            return self.USER[name]
        except KeyError:
            try:
                self.USER[name] = pwd.getpwnam(name)[2]
            except KeyError:
                error(_('user name %s not found') % name)
                self.USER[name] = -1
        return self.USER[name]

    def get_user_name(self, id):
        '''Caches and retreives user name correspondent to id'''
        try:
            return self.USERID[id]
        except KeyError:
            try:
                self.USERID[id] = pwd.getpwuid(id)[0]
            except KeyError:
                error(_('user name not found for id %d') % id)
                self.USERID[id] = str(id)
        return self.USERID[id]

    def get_group_id(self, name):
        '''Caches and retreives group id correspondent to name'''
        try:
            return self.GROUP[name]
        except KeyError:
            try:
                self.GROUP[name] = grp.getgrnam(name)[2]
            except KeyError:
                error(_('group name %s not found') % name)
                self.GROUP[name] = -1
        return self.GROUP[name]

    def get_group_name(self, id):
        '''Caches and retreives group name correspondent to id'''
        try:
            return self.GROUPID[id]
        except KeyError:
            try:
                self.GROUPID[id] = grp.getgrgid(id)[0]
            except KeyError:
                error(_('group name not found for id %d') % id)
                self.GROUPID[id] = str(id)
        return self.GROUPID[id]

    def build_non_localfs_regexp(self,
            non_localfs = ['nfs', 'codafs', 'smbfs', 'cifs', 'autofs']):
        """Build a regexp that matches all the non local filesystems"""
        try:
            file = open('/proc/mounts', 'r')
        except IOError:
            self.log.error(_('Unable to check /proc/mounts. Assuming all file systems are local.'))
            return None

        regexp = None

        for line in file.readlines():
            fields = string.split(line)
            if fields[2] in non_localfs:
                if regexp:
                    regexp = regexp + '|' + fields[1]
                else:
                    regexp = '^(' + fields[1]

        file.close()

        if not regexp:
            return None
        else:
            return re.compile(regexp + ')')

    def commit(self, really_commit=True, enforce=False):
        """Commits changes.
        If enforce is True, the permissions on all files are enforced."""
        if not really_commit:
            self.log.info(_("In check-only mode, nothing is written back to disk."))

        if len(self.files) > 0:
            self.log.info("%s: %s" % (config.MODIFICATIONS_FOUND, " ".join(self.files)))
        else:
            self.log.info(config.MODIFICATIONS_NOT_FOUND)

        for file in self.files:
            newperm, newuser, newgroup, force = self.files[file]
            # are we in enforcing mode?
            if enforce:
                force = True

            if newuser != None:
                if force and really_commit:
                    self.log.warn(_("Forcing ownership of %s to %s") % (file, self.get_user_name(newuser)))
                    try:
                        os.chown(file, newuser, -1)
                    except:
                        self.log.error(_("Error changing user on %s: %s") % (file, sys.exc_value))
                else:
                    self.log.warn(_("Wrong owner of %s: should be %s") % (file, self.get_user_name(newuser)))
            if newgroup != None:
                if force and really_commit:
                    self.log.warn(_("Enforcing group on %s to %s") % (file, self.get_group_name(newgroup)))
                    try:
                        os.chown(file, -1, newgroup)
                    except:
                        self.log.error(_("Error changing group on %s: %s") % (file, sys.exc_value))
                else:
                    self.log.warn(_("Wrong group of %s: should be %s") % (file, self.get_group_name(newgroup)))
            # permissions should be last, as chown resets them
            # on suid files
            if newperm != None:
                if force and really_commit:
                    self.log.warn(_("Enforcing permissions on %s to %o") % (file, newperm))
                    try:
                        os.chmod(file, newperm)
                    except:
                        self.log.error(_("Error changing permissions on %s: %s") % (file, sys.exc_value))
                else:
                    self.log.warn(_("Wrong permissions of %s: should be %o") % (file, newperm))


    def check_perms(self, perms, files_to_check=[]):
        '''Checks permissions for all entries in perms (PermConfig).
        If files_to_check is specified, only the specified files are checked.'''

        for file in perms.list_options():
            user_s, group_s, perm_s, force = perms.get(file)

            # permission
            if perm_s == 'current':
                perm = -1
            else:
                try:
                    perm = int(perm_s, 8)
                except ValueError:
                    self.log.error(_("bad permissions for '%s': '%s'") % (file, perm_s))
                    continue

            # user
            if user_s == 'current':
                user = -1
            else:
                user = self.get_user_id(user_s)

            # group
            if group_s == 'current':
                group = -1
            else:
                group = self.get_group_id(group_s)

            # now check the permissions
            for f in glob.glob('%s%s' % (self.root, file)):
                # get file properties
                f = os.path.realpath(f)
                try:
                    full = os.lstat(f)
                except OSError:
                    continue

                if self.fs_regexp and self.fs_regexp.search(f):
                    self.log.info(_('Non local file: "%s". Nothing changed.') % fields[0])
                    continue

                curperm = perm
                mode = stat.S_IMODE(full[stat.ST_MODE])

                if perm != -1 and stat.S_ISDIR(full[stat.ST_MODE]):
                    if curperm & 0400:
                        curperm = curperm | 0100
                    if curperm & 0040:
                        curperm = curperm | 0010
                    if curperm & 0004:
                        curperm = curperm | 0001

                curuser = full[stat.ST_UID]
                curgroup = full[stat.ST_GID]
                curperm = mode
                # checking for subdirectory permissions
                if f != '/' and f[-1] == '/':
                    f = f[:-1]
                if f[-2:] == '/.':
                    f = f[:-2]
                # check for changes
                newperm = None
                newuser = None
                newgroup = None
                if perm != -1 and perm != curperm:
                    newperm = perm
                if user != -1 and user != curuser:
                    newuser = user
                if group != -1 and group != curgroup:
                    newgroup = group
                if newperm != None or newuser != None or newgroup != None:
                    self.files[f] = (newperm, newuser, newgroup, force)
                    self.log.debug("Updating %s (matched by '%s')" % (f, file))
                else:
                    # see if any other rule put this file into the list
                    if f in self.files:
                        self.log.debug("Removing previously selected %s (matched by '%s')" % (f, file))
                        del self.files[f]
        # do we have to check for any specific paths?
        if files_to_check:
            self.log.info(_("Checking paths: %s") % ", ".join(files_to_check))
            paths_to_check = []
            for f in files_to_check:
                paths_to_check.extend(glob.glob(f))
            paths_to_check = set(paths_to_check)
            # remove unneeded entries from self.files
            for f in self.files.keys():
                if f not in paths_to_check:
                    del self.files[f]
        return self.files
# }}}

if __name__ == "__main__":
    # this should never ever be run directly
    print >>sys.stderr, """This file should not be run directly."""