Update useradd overlays in meta-agl
[AGL/meta-agl.git] / meta-agl / classes / useradd-staticids.bbclass
1 # In order to support a deterministic set of 'dynamic' users/groups,
2 # we need a function to reformat the params based on a static file
3 def update_useradd_static_config(d):
4     import argparse
5     import itertools
6     import re
7     import errno
8
9     class myArgumentParser( argparse.ArgumentParser ):
10         def _print_message(self, message, file=None):
11             bb.warn("%s - %s: %s" % (d.getVar('PN', True), pkg, message))
12
13         # This should never be called...
14         def exit(self, status=0, message=None):
15             message = message or ("%s - %s: useradd.bbclass: Argument parsing exited" % (d.getVar('PN', True), pkg))
16             error(message)
17
18         def error(self, message):
19             raise bb.build.FuncFailed(message)
20
21     def list_extend(iterable, length, obj = None):
22         """Ensure that iterable is the specified length by extending with obj
23         and return it as a list"""
24         return list(itertools.islice(itertools.chain(iterable, itertools.repeat(obj)), length))
25
26     def merge_files(file_list, exp_fields):
27         """Read each passwd/group file in file_list, split each line and create
28         a dictionary with the user/group names as keys and the split lines as
29         values. If the user/group name already exists in the dictionary, then
30         update any fields in the list with the values from the new list (if they
31         are set)."""
32         id_table = dict()
33         for conf in file_list.split():
34             try:
35                 with open(conf, "r") as f:
36                     for line in f:
37                         if line.startswith('#'):
38                             continue
39                         # Make sure there always are at least exp_fields
40                         # elements in the field list. This allows for leaving
41                         # out trailing colons in the files.
42                         fields = list_extend(line.rstrip().split(":"), exp_fields)
43                         if fields[0] not in id_table:
44                             id_table[fields[0]] = fields
45                         else:
46                             id_table[fields[0]] = list(map(lambda x, y: x or y, fields, id_table[fields[0]]))
47             except IOError as e:
48                 if e.errno == errno.ENOENT:
49                     pass
50
51         return id_table
52
53     def handle_missing_id(id, type, pkg):
54         # For backwards compatibility we accept "1" in addition to "error"
55         if d.getVar('USERADD_ERROR_DYNAMIC', True) == 'error' or d.getVar('USERADD_ERROR_DYNAMIC', True) == '1':
56             #bb.error("Skipping recipe %s, package %s which adds %sname %s does not have a static ID defined." % (d.getVar('PN', True),  pkg, type, id))
57             raise bb.build.FuncFailed("%s - %s: %sname %s does not have a static ID defined." % (d.getVar('PN', True), pkg, type, id))
58         elif d.getVar('USERADD_ERROR_DYNAMIC', True) == 'warn':
59             bb.warn("%s - %s: %sname %s does not have a static ID defined." % (d.getVar('PN', True), pkg, type, id))
60
61     # We parse and rewrite the useradd components
62     def rewrite_useradd(params):
63         # The following comes from --help on useradd from shadow
64         parser = myArgumentParser(prog='useradd')
65         parser.add_argument("-b", "--base-dir", metavar="BASE_DIR", help="base directory for the home directory of the new account")
66         parser.add_argument("-c", "--comment", metavar="COMMENT", help="GECOS field of the new account")
67         parser.add_argument("-d", "--home-dir", metavar="HOME_DIR", help="home directory of the new account")
68         parser.add_argument("-D", "--defaults", help="print or change default useradd configuration", action="store_true")
69         parser.add_argument("-e", "--expiredate", metavar="EXPIRE_DATE", help="expiration date of the new account")
70         parser.add_argument("-f", "--inactive", metavar="INACTIVE", help="password inactivity period of the new account")
71         parser.add_argument("-g", "--gid", metavar="GROUP", help="name or ID of the primary group of the new account")
72         parser.add_argument("-G", "--groups", metavar="GROUPS", help="list of supplementary groups of the new account")
73         parser.add_argument("-k", "--skel", metavar="SKEL_DIR", help="use this alternative skeleton directory")
74         parser.add_argument("-K", "--key", metavar="KEY=VALUE", help="override /etc/login.defs defaults")
75         parser.add_argument("-l", "--no-log-init", help="do not add the user to the lastlog and faillog databases", action="store_true")
76         parser.add_argument("-m", "--create-home", help="create the user's home directory", action="store_const", const=True)
77         parser.add_argument("-M", "--no-create-home", dest="create_home", help="do not create the user's home directory", action="store_const", const=False)
78         parser.add_argument("-N", "--no-user-group", dest="user_group", help="do not create a group with the same name as the user", action="store_const", const=False)
79         parser.add_argument("-o", "--non-unique", help="allow to create users with duplicate (non-unique UID)", action="store_true")
80         parser.add_argument("-p", "--password", metavar="PASSWORD", help="encrypted password of the new account")
81         parser.add_argument("-R", "--root", metavar="CHROOT_DIR", help="directory to chroot into")
82         parser.add_argument("-r", "--system", help="create a system account", action="store_true")
83         parser.add_argument("-s", "--shell", metavar="SHELL", help="login shell of the new account")
84         parser.add_argument("-u", "--uid", metavar="UID", help="user ID of the new account")
85         parser.add_argument("-U", "--user-group", help="create a group with the same name as the user", action="store_const", const=True)
86         parser.add_argument("LOGIN", help="Login name of the new user")
87
88         # Return a list of configuration files based on either the default
89         # files/passwd or the contents of USERADD_UID_TABLES
90         # paths are resolved via BBPATH
91         def get_passwd_list(d):
92             str = ""
93             bbpath = d.getVar('BBPATH', True)
94             passwd_tables = d.getVar('USERADD_UID_TABLES', True)
95             if not passwd_tables:
96                 passwd_tables = 'files/passwd'
97             for conf_file in passwd_tables.split():
98                 str += " %s" % bb.utils.which(bbpath, conf_file)
99             return str
100
101         newparams = []
102         users = None
103         for param in re.split('''[ \t]*;[ \t]*(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', params):
104             param = param.strip()
105             if not param:
106                 continue
107             try:
108                 uaargs = parser.parse_args(re.split('''[ \t]+(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', param))
109             except:
110                 raise bb.build.FuncFailed("%s: Unable to parse arguments for USERADD_PARAM_%s: '%s'" % (d.getVar('PN', True), pkg, param))
111
112             # Read all passwd files specified in USERADD_UID_TABLES or files/passwd
113             # Use the standard passwd layout:
114             #  username:password:user_id:group_id:comment:home_directory:login_shell
115             #
116             # If a field is left blank, the original value will be used.  The 'username'
117             # field is required.
118             #
119             # Note: we ignore the password field, as including even the hashed password
120             # in the useradd command may introduce a security hole.  It's assumed that
121             # all new users get the default ('*' which prevents login) until the user is
122             # specifically configured by the system admin.
123             if not users:
124                 users = merge_files(get_passwd_list(d), 7)
125
126             if uaargs.LOGIN not in users:
127                 if not uaargs.uid or not uaargs.uid.isdigit() or not uaargs.gid:
128                     handle_missing_id(uaargs.LOGIN, 'user', pkg)
129                 continue
130
131             field = users[uaargs.LOGIN]
132
133             if uaargs.uid and field[2] and (uaargs.uid != field[2]):
134                 bb.warn("%s: Changing username %s's uid from (%s) to (%s), verify configuration files!" % (d.getVar('PN', True), uaargs.LOGIN, uaargs.uid, field[2]))
135             uaargs.uid = field[2] or uaargs.uid
136
137             # Determine the possible groupname
138             # Unless the group name (or gid) is specified, we assume that the LOGIN is the groupname
139             #
140             # By default the system has creation of the matching groups enabled
141             # So if the implicit username-group creation is on, then the implicit groupname (LOGIN)
142             # is used, and we disable the user_group option.
143             #
144             user_group = uaargs.user_group is None or uaargs.user_group is True
145             uaargs.groupname = uaargs.LOGIN if user_group else uaargs.gid
146             uaargs.groupid = field[3] or uaargs.gid or uaargs.groupname
147
148             if uaargs.groupid and uaargs.gid != uaargs.groupid:
149                 newgroup = None
150                 if not uaargs.groupid.isdigit():
151                     # We don't have a group number, so we have to add a name
152                     bb.debug(1, "Adding group %s!" % uaargs.groupid)
153                     newgroup = "%s %s" % (' --system' if uaargs.system else '', uaargs.groupid)
154                 elif uaargs.groupname and not uaargs.groupname.isdigit():
155                     # We have a group name and a group number to assign it to
156                     bb.debug(1, "Adding group %s (gid %s)!" % (uaargs.groupname, uaargs.groupid))
157                     newgroup = "-g %s %s" % (uaargs.groupid, uaargs.groupname)
158                 else:
159                     # We want to add a group, but we don't know it's name... so we can't add the group...
160                     # We have to assume the group has previously been added or we'll fail on the adduser...
161                     # Note: specifying the actual gid is very rare in OE, usually the group name is specified.
162                     bb.warn("%s: Changing gid for login %s to %s, verify configuration files!" % (d.getVar('PN', True), uaargs.LOGIN, uaargs.groupid))
163
164                 uaargs.gid = uaargs.groupid
165                 uaargs.user_group = None
166                 if newgroup:
167                     groupadd = d.getVar("GROUPADD_PARAM_%s" % pkg, True)
168                     if groupadd:
169                         d.setVar("GROUPADD_PARAM_%s" % pkg, "%s; %s" % (groupadd, newgroup))
170                     else:
171                         d.setVar("GROUPADD_PARAM_%s" % pkg, newgroup)
172
173             uaargs.comment = "'%s'" % field[4] if field[4] else uaargs.comment
174             uaargs.home_dir = field[5] or uaargs.home_dir
175             uaargs.shell = field[6] or uaargs.shell
176
177             # Should be an error if a specific option is set...
178             if not uaargs.uid or not uaargs.uid.isdigit() or not uaargs.gid:
179                  handle_missing_id(uaargs.LOGIN, 'user', pkg)
180
181             # Reconstruct the args...
182             newparam  = ['', ' --defaults'][uaargs.defaults]
183             newparam += ['', ' --base-dir %s' % uaargs.base_dir][uaargs.base_dir != None]
184             newparam += ['', ' --comment %s' % uaargs.comment][uaargs.comment != None]
185             newparam += ['', ' --home-dir %s' % uaargs.home_dir][uaargs.home_dir != None]
186             newparam += ['', ' --expiredata %s' % uaargs.expiredate][uaargs.expiredate != None]
187             newparam += ['', ' --inactive %s' % uaargs.inactive][uaargs.inactive != None]
188             newparam += ['', ' --gid %s' % uaargs.gid][uaargs.gid != None]
189             newparam += ['', ' --groups %s' % uaargs.groups][uaargs.groups != None]
190             newparam += ['', ' --skel %s' % uaargs.skel][uaargs.skel != None]
191             newparam += ['', ' --key %s' % uaargs.key][uaargs.key != None]
192             newparam += ['', ' --no-log-init'][uaargs.no_log_init]
193             newparam += ['', ' --create-home'][uaargs.create_home is True]
194             newparam += ['', ' --no-create-home'][uaargs.create_home is False]
195             newparam += ['', ' --no-user-group'][uaargs.user_group is False]
196             newparam += ['', ' --non-unique'][uaargs.non_unique]
197             newparam += ['', ' --password %s' % uaargs.password][uaargs.password != None]
198             newparam += ['', ' --root %s' % uaargs.root][uaargs.root != None]
199             newparam += ['', ' --system'][uaargs.system]
200             newparam += ['', ' --shell %s' % uaargs.shell][uaargs.shell != None]
201             newparam += ['', ' --uid %s' % uaargs.uid][uaargs.uid != None]
202             newparam += ['', ' --user-group'][uaargs.user_group is True]
203             newparam += ' %s' % uaargs.LOGIN
204
205             newparams.append(newparam)
206
207         return ";".join(newparams).strip()
208
209     # We parse and rewrite the groupadd components
210     def rewrite_groupadd(params):
211         # The following comes from --help on groupadd from shadow
212         parser = myArgumentParser(prog='groupadd')
213         parser.add_argument("-f", "--force", help="exit successfully if the group already exists, and cancel -g if the GID is already used", action="store_true")
214         parser.add_argument("-g", "--gid", metavar="GID", help="use GID for the new group")
215         parser.add_argument("-K", "--key", metavar="KEY=VALUE", help="override /etc/login.defs defaults")
216         parser.add_argument("-o", "--non-unique", help="allow to create groups with duplicate (non-unique) GID", action="store_true")
217         parser.add_argument("-p", "--password", metavar="PASSWORD", help="use this encrypted password for the new group")
218         parser.add_argument("-R", "--root", metavar="CHROOT_DIR", help="directory to chroot into")
219         parser.add_argument("-r", "--system", help="create a system account", action="store_true")
220         parser.add_argument("GROUP", help="Group name of the new group")
221
222         # Return a list of configuration files based on either the default
223         # files/group or the contents of USERADD_GID_TABLES
224         # paths are resolved via BBPATH
225         def get_group_list(d):
226             str = ""
227             bbpath = d.getVar('BBPATH', True)
228             group_tables = d.getVar('USERADD_GID_TABLES', True)
229             if not group_tables:
230                 group_tables = 'files/group'
231             for conf_file in group_tables.split():
232                 str += " %s" % bb.utils.which(bbpath, conf_file)
233             return str
234
235         newparams = []
236         groups = None
237         for param in re.split('''[ \t]*;[ \t]*(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', params):
238             param = param.strip()
239             if not param:
240                 continue
241             try:
242                 # If we're processing multiple lines, we could have left over values here...
243                 gaargs = parser.parse_args(re.split('''[ \t]+(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', param))
244             except:
245                 raise bb.build.FuncFailed("%s: Unable to parse arguments for GROUPADD_PARAM_%s: '%s'" % (d.getVar('PN', True), pkg, param))
246
247             # Read all group files specified in USERADD_GID_TABLES or files/group
248             # Use the standard group layout:
249             #  groupname:password:group_id:group_members
250             #
251             # If a field is left blank, the original value will be used. The 'groupname' field
252             # is required.
253             #
254             # Note: similar to the passwd file, the 'password' filed is ignored
255             # Note: group_members is ignored, group members must be configured with the GROUPMEMS_PARAM
256             if not groups:
257                 groups = merge_files(get_group_list(d), 4)
258
259             if gaargs.GROUP not in groups:
260                 if not gaargs.gid or not gaargs.gid.isdigit():
261                     handle_missing_id(gaargs.GROUP, 'group', pkg)
262                 continue
263
264             field = groups[gaargs.GROUP]
265
266             if field[2]:
267                 if gaargs.gid and (gaargs.gid != field[2]):
268                     bb.warn("%s: Changing groupname %s's gid from (%s) to (%s), verify configuration files!" % (d.getVar('PN', True), gaargs.GROUP, gaargs.gid, field[2]))
269                 gaargs.gid = field[2]
270
271             if not gaargs.gid or not gaargs.gid.isdigit():
272                 handle_missing_id(gaargs.GROUP, 'group', pkg)
273
274             # Reconstruct the args...
275             newparam  = ['', ' --force'][gaargs.force]
276             newparam += ['', ' --gid %s' % gaargs.gid][gaargs.gid != None]
277             newparam += ['', ' --key %s' % gaargs.key][gaargs.key != None]
278             newparam += ['', ' --non-unique'][gaargs.non_unique]
279             newparam += ['', ' --password %s' % gaargs.password][gaargs.password != None]
280             newparam += ['', ' --root %s' % gaargs.root][gaargs.root != None]
281             newparam += ['', ' --system'][gaargs.system]
282             newparam += ' %s' % gaargs.GROUP
283
284             newparams.append(newparam)
285
286         return ";".join(newparams).strip()
287
288     # The parsing of the current recipe depends on the content of
289     # the files listed in USERADD_UID/GID_TABLES. We need to tell bitbake
290     # about that explicitly to trigger re-parsing and thus re-execution of
291     # this code when the files change.
292     bbpath = d.getVar('BBPATH', True)
293     for varname, default in (('USERADD_UID_TABLES', 'files/passwd'),
294                              ('USERADD_GID_TABLES', 'files/group')):
295         tables = d.getVar(varname, True)
296         if not tables:
297             tables = default
298         for conf_file in tables.split():
299             bb.parse.mark_dependency(d, bb.utils.which(bbpath, conf_file))
300
301     # Load and process the users and groups, rewriting the adduser/addgroup params
302     useradd_packages = d.getVar('USERADD_PACKAGES', True)
303
304     for pkg in useradd_packages.split():
305         # Groupmems doesn't have anything we might want to change, so simply validating
306         # is a bit of a waste -- only process useradd/groupadd
307         useradd_param = d.getVar('USERADD_PARAM_%s' % pkg, True)
308         if useradd_param:
309             #bb.warn("Before: 'USERADD_PARAM_%s' - '%s'" % (pkg, useradd_param))
310             d.setVar('USERADD_PARAM_%s' % pkg, rewrite_useradd(useradd_param))
311             #bb.warn("After:  'USERADD_PARAM_%s' - '%s'" % (pkg, d.getVar('USERADD_PARAM_%s' % pkg, True)))
312
313         groupadd_param = d.getVar('GROUPADD_PARAM_%s' % pkg, True)
314         if groupadd_param:
315             #bb.warn("Before: 'GROUPADD_PARAM_%s' - '%s'" % (pkg, groupadd_param))
316             d.setVar('GROUPADD_PARAM_%s' % pkg, rewrite_groupadd(groupadd_param))
317             #bb.warn("After:  'GROUPADD_PARAM_%s' - '%s'" % (pkg, d.getVar('GROUPADD_PARAM_%s' % pkg, True)))
318
319
320
321 python __anonymous() {
322     if not bb.data.inherits_class('nativesdk', d) \
323         and not bb.data.inherits_class('native', d):
324         try:
325             update_useradd_static_config(d)
326         except bb.build.FuncFailed as f:
327             bb.debug(1, "Skipping recipe %s: %s" % (d.getVar('PN', True), f))
328             raise bb.parse.SkipPackage(f)
329 }