02bd8dc8ae2a9747cc810ba447bb6b1f9ce5adda
[snf-image-creator] / image_creator / os_type / freebsd.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright 2012 GRNET S.A. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
7 # conditions are met:
8 #
9 #   1. Redistributions of source code must retain the above
10 #      copyright notice, this list of conditions and the following
11 #      disclaimer.
12 #
13 #   2. Redistributions in binary form must reproduce the above
14 #      copyright notice, this list of conditions and the following
15 #      disclaimer in the documentation and/or other materials
16 #      provided with the distribution.
17 #
18 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 # POSSIBILITY OF SUCH DAMAGE.
30 #
31 # The views and conclusions contained in the software and
32 # documentation are those of the authors and should not be
33 # interpreted as representing official policies, either expressed
34 # or implied, of GRNET S.A.
35
36 """This module hosts OS-specific code for FreeBSD."""
37
38 from image_creator.os_type.unix import Unix, sysprep
39
40 import re
41
42
43 class Freebsd(Unix):
44     """OS class for FreeBSD Unix-like os"""
45     def __init__(self, rootdev, ghandler, output):
46         super(Freebsd, self).__init__(rootdev, ghandler, output)
47
48     @sysprep()
49     def cleanup_password(self, print_header=True):
50         """Remove all passwords and lock all user accounts"""
51
52         if print_header:
53             self.out.output("Cleaning up passwords & locking all user "
54                             "accounts")
55
56         master_passwd = []
57
58         for line in self.g.cat('/etc/master.passwd').splitlines():
59
60             # Check for empty or comment lines
61             if len(line.split('#')[0]) == 0:
62                 master_passwd.append(line)
63                 continue
64
65             fields = line.split(':')
66             if fields[1] not in ('*', '!'):
67                 fields[1] = '!'
68
69             master_passwd.append(":".join(fields))
70
71         self.g.write('/etc/master.passwd', "\n".join(master_passwd) + '\n')
72
73         # Make sure no one can login on the system
74         self.g.rm_rf('/etc/spwd.db')
75
76     def _do_collect_metadata(self):
77         """Collect metadata about the OS"""
78         super(Freebsd, self)._do_collect_metadata()
79         self.meta["USERS"] = " ".join(self._get_passworded_users())
80
81         #The original product name key is long and ugly
82         self.meta['DESCRIPTION'] = \
83             self.meta['DESCRIPTION'].split('#')[0].strip()
84
85         # Delete the USERS metadata if empty
86         if not len(self.meta['USERS']):
87             self.out.warn("No passworded users found!")
88             del self.meta['USERS']
89
90     def _get_passworded_users(self):
91         """Returns a list of non-locked user accounts"""
92         users = []
93         regexp = re.compile(
94             '^([^:]+):((?:![^:]+)|(?:[^!*][^:]+)|):(?:[^:]*:){7}(?:[^:]*)'
95         )
96
97         for line in self.g.cat('/etc/master.passwd').splitlines():
98             line = line.split('#')[0]
99             match = regexp.match(line)
100             if not match:
101                 continue
102
103             user, passwd = match.groups()
104             if len(passwd) > 0 and passwd[0] == '!':
105                 self.out.warn("Ignoring locked %s account." % user)
106             else:
107                 users.append(user)
108
109         return users
110
111     def _do_mount(self, readonly):
112         """Mount partitions in the correct order"""
113
114         critical_mpoints = ('/', '/etc', '/root', '/home', '/var')
115
116         # libguestfs can't handle correct freebsd partitions on a GUID
117         # Partition Table. We have to do the translation to linux device names
118         # ourselves
119         guid_device = re.compile('^/dev/((?:ada)|(?:vtbd))(\d+)p(\d+)$')
120
121         mopts = "ufstype=ufs2,%s" % ('ro' if readonly else 'rw')
122         for mp, dev in self._mountpoints():
123             match = guid_device.match(dev)
124             if match:
125                 group2 = int(match.group(2))
126                 group3 = int(match.group(3))
127                 dev = '/dev/sd%c%d' % (chr(ord('a') + group2), group3)
128             try:
129                 self.g.mount_vfs(mopts, 'ufs', dev, mp)
130             except RuntimeError as msg:
131                 if mp in critical_mpoints:
132                     self.out.warn('unable to mount %s. Reason: %s' % (mp, msg))
133                     return False
134                 else:
135                     self.out.warn('%s (ignored)' % msg)
136
137         return True
138
139 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :