root / image_creator / os_type / linux.py @ 2dcd42b7
History | View | Annotate | Download (11.9 kB)
1 |
# Copyright 2012 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
|
34 |
from image_creator.os_type.unix import Unix, sysprep |
35 |
|
36 |
import re |
37 |
import time |
38 |
|
39 |
|
40 |
class Linux(Unix): |
41 |
"""OS class for Linux"""
|
42 |
def __init__(self, rootdev, ghandler, output): |
43 |
super(Linux, self).__init__(rootdev, ghandler, output) |
44 |
self._uuid = dict() |
45 |
self._persistent = re.compile('/dev/[hsv]d[a-z][1-9]*') |
46 |
|
47 |
self.meta["USERS"] = " ".join(self._get_passworded_users()) |
48 |
|
49 |
# Delete the USERS metadata if empty
|
50 |
if not len(self.meta['USERS']): |
51 |
self.out.warn("No passworded users found!") |
52 |
del self.meta['USERS'] |
53 |
|
54 |
def _get_passworded_users(self): |
55 |
users = [] |
56 |
regexp = re.compile('(\S+):((?:!\S+)|(?:[^!*]\S+)|):(?:\S*:){6}')
|
57 |
|
58 |
for line in self.g.cat('/etc/shadow').splitlines(): |
59 |
match = regexp.match(line) |
60 |
if not match: |
61 |
continue
|
62 |
|
63 |
user, passwd = match.groups() |
64 |
if len(passwd) > 0 and passwd[0] == '!': |
65 |
self.out.warn("Ignoring locked %s account." % user) |
66 |
else:
|
67 |
users.append(user) |
68 |
|
69 |
return users
|
70 |
|
71 |
def is_persistent(self, dev): |
72 |
return not self._persistent.match(dev) |
73 |
|
74 |
def get_uuid(self, dev): |
75 |
if dev in self._uuid: |
76 |
return self._uuid[dev] |
77 |
|
78 |
uuid = self.g.vfs_uuid(dev)
|
79 |
assert len(uuid) |
80 |
self._uuid[dev] = uuid
|
81 |
return uuid
|
82 |
|
83 |
@sysprep(enabled=False) |
84 |
def remove_user_accounts(self, print_header=True): |
85 |
"""Remove all user accounts with id greater than 1000"""
|
86 |
|
87 |
if print_header:
|
88 |
self.out.output("Removing all user accounts with id greater than " |
89 |
"1000")
|
90 |
|
91 |
if 'USERS' not in self.meta: |
92 |
return
|
93 |
|
94 |
# Remove users from /etc/passwd
|
95 |
passwd = [] |
96 |
removed_users = {} |
97 |
metadata_users = self.meta['USERS'].split() |
98 |
for line in self.g.cat('/etc/passwd').splitlines(): |
99 |
fields = line.split(':')
|
100 |
if int(fields[2]) > 1000: |
101 |
removed_users[fields[0]] = fields
|
102 |
# remove it from the USERS metadata too
|
103 |
if fields[0] in metadata_users: |
104 |
metadata_users.remove(fields[0])
|
105 |
else:
|
106 |
passwd.append(':'.join(fields))
|
107 |
|
108 |
self.meta['USERS'] = " ".join(metadata_users) |
109 |
|
110 |
# Delete the USERS metadata if empty
|
111 |
if not len(self.meta['USERS']): |
112 |
del self.meta['USERS'] |
113 |
|
114 |
self.g.write('/etc/passwd', '\n'.join(passwd) + '\n') |
115 |
|
116 |
# Remove the corresponding /etc/shadow entries
|
117 |
shadow = [] |
118 |
for line in self.g.cat('/etc/shadow').splitlines(): |
119 |
fields = line.split(':')
|
120 |
if fields[0] not in removed_users: |
121 |
shadow.append(':'.join(fields))
|
122 |
|
123 |
self.g.write('/etc/shadow', "\n".join(shadow) + '\n') |
124 |
|
125 |
# Remove the corresponding /etc/group entries
|
126 |
group = [] |
127 |
for line in self.g.cat('/etc/group').splitlines(): |
128 |
fields = line.split(':')
|
129 |
# Remove groups tha have the same name as the removed users
|
130 |
if fields[0] not in removed_users: |
131 |
group.append(':'.join(fields))
|
132 |
|
133 |
self.g.write('/etc/group', '\n'.join(group) + '\n') |
134 |
|
135 |
# Remove home directories
|
136 |
for home in [field[5] for field in removed_users.values()]: |
137 |
if self.g.is_dir(home) and home.startswith('/home/'): |
138 |
self.g.rm_rf(home)
|
139 |
|
140 |
@sysprep()
|
141 |
def cleanup_passwords(self, print_header=True): |
142 |
"""Remove all passwords and lock all user accounts"""
|
143 |
|
144 |
if print_header:
|
145 |
self.out.output("Cleaning up passwords & locking all user " |
146 |
"accounts")
|
147 |
|
148 |
shadow = [] |
149 |
|
150 |
for line in self.g.cat('/etc/shadow').splitlines(): |
151 |
fields = line.split(':')
|
152 |
if fields[1] not in ('*', '!'): |
153 |
fields[1] = '!' |
154 |
|
155 |
shadow.append(":".join(fields))
|
156 |
|
157 |
self.g.write('/etc/shadow', "\n".join(shadow) + '\n') |
158 |
|
159 |
@sysprep()
|
160 |
def fix_acpid(self, print_header=True): |
161 |
"""Replace acpid powerdown action scripts to immediately shutdown the
|
162 |
system without checking if a GUI is running.
|
163 |
"""
|
164 |
|
165 |
if print_header:
|
166 |
self.out.output('Fixing acpid powerdown action') |
167 |
|
168 |
powerbtn_action = '#!/bin/sh\n\nPATH=/sbin:/bin:/usr/bin\n' \
|
169 |
'shutdown -h now "Power button pressed"\n'
|
170 |
|
171 |
events_dir = '/etc/acpi/events'
|
172 |
if not self.g.is_dir(events_dir): |
173 |
self.out.warn("No acpid event directory found") |
174 |
return
|
175 |
|
176 |
event_exp = re.compile('event=(.+)', re.I)
|
177 |
action_exp = re.compile('action=(.+)', re.I)
|
178 |
for f in self.g.readdir(events_dir): |
179 |
if f['ftyp'] != 'r': |
180 |
continue
|
181 |
|
182 |
fullpath = "%s/%s" % (events_dir, f['name']) |
183 |
event = ""
|
184 |
action = ""
|
185 |
for line in self.g.cat(fullpath).splitlines(): |
186 |
m = event_exp.match(line) |
187 |
if m:
|
188 |
event = m.group(1)
|
189 |
continue
|
190 |
m = action_exp.match(line) |
191 |
if m:
|
192 |
action = m.group(1)
|
193 |
continue
|
194 |
|
195 |
if event.strip() in ("button[ /]power", "button/power.*"): |
196 |
if action:
|
197 |
if not self.g.is_file(action): |
198 |
self.out.warn("Acpid action file: %s does not exist" % |
199 |
action) |
200 |
return
|
201 |
self.g.copy_file_to_file(action,
|
202 |
"%s.orig.snf-image-creator-%d" %
|
203 |
(action, time.time())) |
204 |
self.g.write(action, powerbtn_action)
|
205 |
return
|
206 |
else:
|
207 |
self.out.warn("Acpid event file %s does not contain and " |
208 |
"action")
|
209 |
return
|
210 |
elif event.strip() == ".*": |
211 |
self.out.warn("Found action `.*'. Don't know how to handle " |
212 |
"this. Please edit `%s' image file manually to "
|
213 |
"make the system immediatelly shutdown when an "
|
214 |
"power button acpi event occures." %
|
215 |
action.strip().split()[0])
|
216 |
return
|
217 |
|
218 |
self.out.warn("No acpi power button event found!") |
219 |
|
220 |
@sysprep()
|
221 |
def remove_persistent_net_rules(self, print_header=True): |
222 |
"""Remove udev rules that will keep network interface names persistent
|
223 |
after hardware changes and reboots. Those rules will be created again
|
224 |
the next time the image runs.
|
225 |
"""
|
226 |
|
227 |
if print_header:
|
228 |
self.out.output('Removing persistent network interface names') |
229 |
|
230 |
rule_file = '/etc/udev/rules.d/70-persistent-net.rules'
|
231 |
if self.g.is_file(rule_file): |
232 |
self.g.rm(rule_file)
|
233 |
|
234 |
@sysprep()
|
235 |
def remove_swap_entry(self, print_header=True): |
236 |
"""Remove swap entry from /etc/fstab. If swap is the last partition
|
237 |
then the partition will be removed when shrinking is performed. If the
|
238 |
swap partition is not the last partition in the disk or if you are not
|
239 |
going to shrink the image you should probably disable this.
|
240 |
"""
|
241 |
|
242 |
if print_header:
|
243 |
self.out.output('Removing swap entry from fstab') |
244 |
|
245 |
new_fstab = ""
|
246 |
fstab = self.g.cat('/etc/fstab') |
247 |
for line in fstab.splitlines(): |
248 |
|
249 |
entry = line.split('#')[0].strip().split() |
250 |
if len(entry) == 6 and entry[2] == 'swap': |
251 |
continue
|
252 |
|
253 |
new_fstab += "%s\n" % line
|
254 |
|
255 |
self.g.write('/etc/fstab', new_fstab) |
256 |
|
257 |
@sysprep()
|
258 |
def use_persistent_block_device_names(self, print_header=True): |
259 |
"""Scan fstab & grub configuration files and replace all non-persistent
|
260 |
device references with UUIDs.
|
261 |
"""
|
262 |
|
263 |
if print_header:
|
264 |
self.out.output("Replacing fstab & grub non-persistent device " |
265 |
"references")
|
266 |
|
267 |
# convert all devices in fstab to persistent
|
268 |
persistent_root = self._persistent_fstab()
|
269 |
|
270 |
# convert all devices in grub1 to persistent
|
271 |
self._persistent_grub1(persistent_root)
|
272 |
|
273 |
def _persistent_grub1(self, new_root): |
274 |
if self.g.is_file('/boot/grub/menu.lst'): |
275 |
grub1 = '/boot/grub/menu.lst'
|
276 |
elif self.g.is_file('/etc/grub.conf'): |
277 |
grub1 = '/etc/grub.conf'
|
278 |
else:
|
279 |
return
|
280 |
|
281 |
self.g.aug_init('/', 0) |
282 |
try:
|
283 |
roots = self.g.aug_match('/files%s/title[*]/kernel/root' % grub1) |
284 |
for root in roots: |
285 |
dev = self.g.aug_get(root)
|
286 |
if not self.is_persistent(dev): |
287 |
# This is not always correct. Grub may contain root entries
|
288 |
# for other systems, but we only support 1 OS per hard
|
289 |
# disk, so this shouldn't harm.
|
290 |
self.g.aug_set(root, new_root)
|
291 |
finally:
|
292 |
self.g.aug_save()
|
293 |
self.g.aug_close()
|
294 |
|
295 |
def _persistent_fstab(self): |
296 |
mpoints = self.g.mountpoints()
|
297 |
if len(mpoints) == 0: |
298 |
pass # TODO: error handling |
299 |
|
300 |
device_dict = dict([[mpoint, dev] for dev, mpoint in mpoints]) |
301 |
|
302 |
root_dev = None
|
303 |
new_fstab = ""
|
304 |
fstab = self.g.cat('/etc/fstab') |
305 |
for line in fstab.splitlines(): |
306 |
|
307 |
line, dev, mpoint = self._convert_fstab_line(line, device_dict)
|
308 |
new_fstab += "%s\n" % line
|
309 |
|
310 |
if mpoint == '/': |
311 |
root_dev = dev |
312 |
|
313 |
self.g.write('/etc/fstab', new_fstab) |
314 |
if root_dev is None: |
315 |
pass # TODO: error handling |
316 |
|
317 |
return root_dev
|
318 |
|
319 |
def _convert_fstab_line(self, line, devices): |
320 |
orig = line |
321 |
line = line.split('#')[0].strip() |
322 |
if len(line) == 0: |
323 |
return orig, "", "" |
324 |
|
325 |
entry = line.split() |
326 |
if len(entry) != 6: |
327 |
self.out.warn("Detected abnormal entry in fstab") |
328 |
return orig, "", "" |
329 |
|
330 |
dev = entry[0]
|
331 |
mpoint = entry[1]
|
332 |
|
333 |
if not self.is_persistent(dev): |
334 |
if mpoint in devices: |
335 |
dev = "UUID=%s" % self.get_uuid(devices[mpoint]) |
336 |
entry[0] = dev
|
337 |
else:
|
338 |
# comment out the entry
|
339 |
entry[0] = "#%s" % dev |
340 |
return " ".join(entry), dev, mpoint |
341 |
|
342 |
return orig, dev, mpoint
|
343 |
|
344 |
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :
|