Monitor executed syspreps in os_type/__init__.py
[snf-image-creator] / image_creator / os_type / linux.py
index 91f6910..86638c0 100644 (file)
@@ -38,11 +38,36 @@ import time
 
 
 class Linux(Unix):
+    """OS class for Linux"""
     def __init__(self, rootdev, ghandler, output):
         super(Linux, self).__init__(rootdev, ghandler, output)
         self._uuid = dict()
         self._persistent = re.compile('/dev/[hsv]d[a-z][1-9]*')
 
+        self.meta["USERS"] = " ".join(self._get_passworded_users())
+
+        # Delete the USERS metadata if empty
+        if not len(self.meta['USERS']):
+            self.out.warn("No passworded users found!")
+            del self.meta['USERS']
+
+    def _get_passworded_users(self):
+        users = []
+        regexp = re.compile('(\S+):((?:!\S+)|(?:[^!*]\S+)|):(?:\S*:){6}')
+
+        for line in self.g.cat('/etc/shadow').splitlines():
+            match = regexp.match(line)
+            if not match:
+                continue
+
+            user, passwd = match.groups()
+            if len(passwd) > 0 and passwd[0] == '!':
+                self.out.warn("Ignoring locked %s account." % user)
+            else:
+                users.append(user)
+
+        return users
+
     def is_persistent(self, dev):
         return not self._persistent.match(dev)
 
@@ -55,6 +80,82 @@ class Linux(Unix):
         self._uuid[dev] = uuid
         return uuid
 
+    @sysprep(enabled=False)
+    def remove_user_accounts(self, print_header=True):
+        """Remove all user accounts with id greater than 1000"""
+
+        if print_header:
+            self.out.output("Removing all user accounts with id greater than "
+                            "1000")
+
+        if 'USERS' not in self.meta:
+            return
+
+        # Remove users from /etc/passwd
+        passwd = []
+        removed_users = {}
+        metadata_users = self.meta['USERS'].split()
+        for line in self.g.cat('/etc/passwd').splitlines():
+            fields = line.split(':')
+            if int(fields[2]) > 1000:
+                removed_users[fields[0]] = fields
+                # remove it from the USERS metadata too
+                if fields[0] in metadata_users:
+                    metadata_users.remove(fields[0])
+            else:
+                passwd.append(':'.join(fields))
+
+        self.meta['USERS'] = " ".join(metadata_users)
+
+        # Delete the USERS metadata if empty
+        if not len(self.meta['USERS']):
+            del self.meta['USERS']
+
+        self.g.write('/etc/passwd', '\n'.join(passwd) + '\n')
+
+        # Remove the corresponding /etc/shadow entries
+        shadow = []
+        for line in self.g.cat('/etc/shadow').splitlines():
+            fields = line.split(':')
+            if fields[0] not in removed_users:
+                shadow.append(':'.join(fields))
+
+        self.g.write('/etc/shadow', "\n".join(shadow) + '\n')
+
+        # Remove the corresponding /etc/group entries
+        group = []
+        for line in self.g.cat('/etc/group').splitlines():
+            fields = line.split(':')
+            # Remove groups tha have the same name as the removed users
+            if fields[0] not in removed_users:
+                group.append(':'.join(fields))
+
+        self.g.write('/etc/group', '\n'.join(group) + '\n')
+
+        # Remove home directories
+        for home in [field[5] for field in removed_users.values()]:
+            if self.g.is_dir(home) and home.startswith('/home/'):
+                self.g.rm_rf(home)
+
+    @sysprep()
+    def cleanup_passwords(self, print_header=True):
+        """Remove all passwords and lock all user accounts"""
+
+        if print_header:
+            self.out.output("Cleaning up passwords & locking all user "
+                            "accounts")
+
+        shadow = []
+
+        for line in self.g.cat('/etc/shadow').splitlines():
+            fields = line.split(':')
+            if fields[1] not in ('*', '!'):
+                fields[1] = '!'
+
+            shadow.append(":".join(fields))
+
+        self.g.write('/etc/shadow', "\n".join(shadow) + '\n')
+
     @sysprep()
     def fix_acpid(self, print_header=True):
         """Replace acpid powerdown action scripts to immediately shutdown the
@@ -91,7 +192,7 @@ class Linux(Unix):
                     action = m.group(1)
                     continue
 
-            if event.strip() == "button[ /]power":
+            if event.strip() in ("button[ /]power", "button/power.*"):
                 if action:
                     if not self.g.is_file(action):
                         self.out.warn("Acpid action file: %s does not exist" %
@@ -114,6 +215,8 @@ class Linux(Unix):
                               action.strip().split()[0])
                 return
 
+        self.out.warn("No acpi power button event found!")
+
     @sysprep()
     def remove_persistent_net_rules(self, print_header=True):
         """Remove udev rules that will keep network interface names persistent
@@ -154,12 +257,12 @@ class Linux(Unix):
     @sysprep()
     def use_persistent_block_device_names(self, print_header=True):
         """Scan fstab & grub configuration files and replace all non-persistent
-        device appearences with UUIDs.
+        device references with UUIDs.
         """
 
         if print_header:
             self.out.output("Replacing fstab & grub non-persistent device "
-                            "appearences")
+                            "references")
 
         # convert all devices in fstab to persistent
         persistent_root = self._persistent_fstab()