Extend data_cleanup method in unix
[snf-image-creator] / image_creator / os_type / unix.py
1 #!/usr/bin/env python
2
3 import re
4 import sys
5
6 from image_creator.os_type import OSBase
7
8
9 class Unix(OSBase):
10
11     sensitive_userdata = [
12         '.bash_history',
13         '.gnupg',
14         '.ssh',
15         '.mozilla',
16         '.thunderbird'
17     ]
18
19     def get_metadata(self):
20         meta = super(Unix, self).get_metadata()
21         meta["USERS"] = " ".join(self.get_passworded_users())
22         return meta
23
24     def get_passworded_users(self):
25         users = []
26         regexp = re.compile('(\S+):((?:!\S+)|(?:[^!*]\S+)|):(?:\S*:){6}')
27
28         for line in self.g.cat('/etc/shadow').splitlines():
29             match = regexp.match(line)
30             if not match:
31                 continue
32
33             user, passwd = match.groups()
34             if len(passwd) > 0 and passwd[0] == '!':
35                 print "Warning: Ignoring locked %s account." % user
36             else:
37                 users.append(user)
38
39         return users
40
41     def data_cleanup(self):
42         self.data_cleanup_userdata()
43         self.data_cleanup_tmp()
44         self.data_cleanup_log()
45         self.data_cleanup_mail()
46         self.data_cleanup_cache()
47
48     def data_cleanup_cache(self):
49         """Remove all regular files under /var/cache"""
50         self.foreach_file('/var/cache', self.g.rm, ftype='r')
51
52     def data_cleanup_tmp(self):
53         """Remove all files under /tmp and /var/tmp"""
54         self.foreach_file('/tmp', self.g.rm_rf, maxdepth=1)
55         self.foreach_file('/var/tmp', self.g.rm_rf, maxdepth=1)
56
57     def data_cleanup_log(self):
58         """Empty all files under /var/log"""
59         self.foreach_file('/var/log', self.g.truncate, ftype='r')
60
61     def data_cleanup_mail(self):
62         """Remove all files under /var/mail and /var/spool/mail"""
63         self.foreach_file('/var/spool/mail', self.g.rm_rf, maxdepth=1)
64         self.foreach_file('/var/mail', self.g.rm_rf, maxdepth=1)
65
66     def data_cleanup_userdata(self):
67         """Delete sensitive userdata"""
68         homedirs = ['/root'] + self.ls('/home/')
69
70         for homedir in homedirs:
71             for data in self.sensitive_userdata:
72                 fname = "%s/%s" % (homedir, data)
73                 if self.g.is_file(fname):
74                     self.g.scrub_file(fname)
75
76 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :