blob: 3a1b5f132058175193eed44edb940a68767b7662 [file] [log] [blame]
lh9ed821d2023-04-07 01:36:19 -07001# 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
3def update_useradd_static_config(d):
4 import itertools
5 import re
6 import errno
7 import oe.useradd
8
9 def list_extend(iterable, length, obj = None):
10 """Ensure that iterable is the specified length by extending with obj
11 and return it as a list"""
12 return list(itertools.islice(itertools.chain(iterable, itertools.repeat(obj)), length))
13
14 def merge_files(file_list, exp_fields):
15 """Read each passwd/group file in file_list, split each line and create
16 a dictionary with the user/group names as keys and the split lines as
17 values. If the user/group name already exists in the dictionary, then
18 update any fields in the list with the values from the new list (if they
19 are set)."""
20 id_table = dict()
21 for conf in file_list.split():
22 try:
23 with open(conf, "r") as f:
24 for line in f:
25 if line.startswith('#'):
26 continue
27 # Make sure there always are at least exp_fields
28 # elements in the field list. This allows for leaving
29 # out trailing colons in the files.
30 fields = list_extend(line.rstrip().split(":"), exp_fields)
31 if fields[0] not in id_table:
32 id_table[fields[0]] = fields
33 else:
34 id_table[fields[0]] = list(map(lambda x, y: x or y, fields, id_table[fields[0]]))
35 except IOError as e:
36 if e.errno == errno.ENOENT:
37 pass
38
39 return id_table
40
41 def handle_missing_id(id, type, pkg, files, var, value):
42 # For backwards compatibility we accept "1" in addition to "error"
43 error_dynamic = d.getVar('USERADD_ERROR_DYNAMIC')
44 msg = "%s - %s: %sname %s does not have a static ID defined." % (d.getVar('PN'), pkg, type, id)
45 if files:
46 msg += " Add %s to one of these files: %s" % (id, files)
47 else:
48 msg += " %s file(s) not found in BBPATH: %s" % (var, value)
49 if error_dynamic == 'error' or error_dynamic == '1':
50 raise NotImplementedError(msg)
51 elif error_dynamic == 'warn':
52 bb.warn(msg)
53 elif error_dynamic == 'skip':
54 raise bb.parse.SkipRecipe(msg)
55
56 # Return a list of configuration files based on either the default
57 # files/group or the contents of USERADD_GID_TABLES, resp.
58 # files/passwd for USERADD_UID_TABLES.
59 # Paths are resolved via BBPATH.
60 def get_table_list(d, var, default):
61 files = []
62 bbpath = d.getVar('BBPATH')
63 tables = d.getVar(var)
64 if not tables:
65 tables = default
66 for conf_file in tables.split():
67 files.append(bb.utils.which(bbpath, conf_file))
68 return (' '.join(files), var, default)
69
70 # We parse and rewrite the useradd components
71 def rewrite_useradd(params, is_pkg):
72 parser = oe.useradd.build_useradd_parser()
73
74 newparams = []
75 users = None
76 for param in oe.useradd.split_commands(params):
77 try:
78 uaargs = parser.parse_args(oe.useradd.split_args(param))
79 except Exception as e:
80 bb.fatal("%s: Unable to parse arguments for USERADD_PARAM_%s '%s': %s" % (d.getVar('PN'), pkg, param, e))
81
82 # Read all passwd files specified in USERADD_UID_TABLES or files/passwd
83 # Use the standard passwd layout:
84 # username:password:user_id:group_id:comment:home_directory:login_shell
85 #
86 # If a field is left blank, the original value will be used. The 'username'
87 # field is required.
88 #
89 # Note: we ignore the password field, as including even the hashed password
90 # in the useradd command may introduce a security hole. It's assumed that
91 # all new users get the default ('*' which prevents login) until the user is
92 # specifically configured by the system admin.
93 if not users:
94 files, table_var, table_value = get_table_list(d, 'USERADD_UID_TABLES', 'files/passwd')
95 users = merge_files(files, 7)
96
97 type = 'system user' if uaargs.system else 'normal user'
98 if uaargs.LOGIN not in users:
99 handle_missing_id(uaargs.LOGIN, type, pkg, files, table_var, table_value)
100 newparams.append(param)
101 continue
102
103 field = users[uaargs.LOGIN]
104
105 if uaargs.uid and field[2] and (uaargs.uid != field[2]):
106 bb.warn("%s: Changing username %s's uid from (%s) to (%s), verify configuration files!" % (d.getVar('PN'), uaargs.LOGIN, uaargs.uid, field[2]))
107 uaargs.uid = field[2] or uaargs.uid
108
109 # Determine the possible groupname
110 # Unless the group name (or gid) is specified, we assume that the LOGIN is the groupname
111 #
112 # By default the system has creation of the matching groups enabled
113 # So if the implicit username-group creation is on, then the implicit groupname (LOGIN)
114 # is used, and we disable the user_group option.
115 #
116 if uaargs.gid:
117 uaargs.groupname = uaargs.gid
118 elif uaargs.user_group is not False:
119 uaargs.groupname = uaargs.LOGIN
120 else:
121 uaargs.groupname = 'users'
122 uaargs.groupid = field[3] or uaargs.groupname
123
124 if uaargs.groupid and uaargs.gid != uaargs.groupid:
125 newgroup = None
126 if not uaargs.groupid.isdigit():
127 # We don't have a group number, so we have to add a name
128 bb.debug(1, "Adding group %s!" % uaargs.groupid)
129 newgroup = "%s %s" % (' --system' if uaargs.system else '', uaargs.groupid)
130 elif uaargs.groupname and not uaargs.groupname.isdigit():
131 # We have a group name and a group number to assign it to
132 bb.debug(1, "Adding group %s (gid %s)!" % (uaargs.groupname, uaargs.groupid))
133 newgroup = "-g %s %s" % (uaargs.groupid, uaargs.groupname)
134 else:
135 # We want to add a group, but we don't know it's name... so we can't add the group...
136 # We have to assume the group has previously been added or we'll fail on the adduser...
137 # Note: specifying the actual gid is very rare in OE, usually the group name is specified.
138 bb.warn("%s: Changing gid for login %s to %s, verify configuration files!" % (d.getVar('PN'), uaargs.LOGIN, uaargs.groupid))
139
140 uaargs.gid = uaargs.groupid
141 uaargs.user_group = None
142 if newgroup and is_pkg:
143 groupadd = d.getVar("GROUPADD_PARAM_%s" % pkg)
144 if groupadd:
145 # Only add the group if not already specified
146 if not uaargs.groupname in groupadd:
147 d.setVar("GROUPADD_PARAM_%s" % pkg, "%s; %s" % (groupadd, newgroup))
148 else:
149 d.setVar("GROUPADD_PARAM_%s" % pkg, newgroup)
150
151 uaargs.comment = "'%s'" % field[4] if field[4] else uaargs.comment
152 uaargs.home_dir = field[5] or uaargs.home_dir
153 uaargs.shell = field[6] or uaargs.shell
154
155 # Should be an error if a specific option is set...
156 if not uaargs.uid or not uaargs.uid.isdigit() or not uaargs.gid:
157 handle_missing_id(uaargs.LOGIN, type, pkg, files, table_var, table_value)
158
159 # Reconstruct the args...
160 newparam = ['', ' --defaults'][uaargs.defaults]
161 newparam += ['', ' --base-dir %s' % uaargs.base_dir][uaargs.base_dir != None]
162 newparam += ['', ' --comment %s' % uaargs.comment][uaargs.comment != None]
163 newparam += ['', ' --home-dir %s' % uaargs.home_dir][uaargs.home_dir != None]
164 newparam += ['', ' --expiredate %s' % uaargs.expiredate][uaargs.expiredate != None]
165 newparam += ['', ' --inactive %s' % uaargs.inactive][uaargs.inactive != None]
166 newparam += ['', ' --gid %s' % uaargs.gid][uaargs.gid != None]
167 newparam += ['', ' --groups %s' % uaargs.groups][uaargs.groups != None]
168 newparam += ['', ' --skel %s' % uaargs.skel][uaargs.skel != None]
169 newparam += ['', ' --key %s' % uaargs.key][uaargs.key != None]
170 newparam += ['', ' --no-log-init'][uaargs.no_log_init]
171 newparam += ['', ' --create-home'][uaargs.create_home is True]
172 newparam += ['', ' --no-create-home'][uaargs.create_home is False]
173 newparam += ['', ' --no-user-group'][uaargs.user_group is False]
174 newparam += ['', ' --non-unique'][uaargs.non_unique]
175 if uaargs.password != None:
176 newparam += ['', ' --password %s' % uaargs.password][uaargs.password != None]
177 elif uaargs.clear_password:
178 newparam += ['', ' --clear-password %s' % uaargs.clear_password][uaargs.clear_password != None]
179 newparam += ['', ' --root %s' % uaargs.root][uaargs.root != None]
180 newparam += ['', ' --system'][uaargs.system]
181 newparam += ['', ' --shell %s' % uaargs.shell][uaargs.shell != None]
182 newparam += ['', ' --uid %s' % uaargs.uid][uaargs.uid != None]
183 newparam += ['', ' --user-group'][uaargs.user_group is True]
184 newparam += ' %s' % uaargs.LOGIN
185
186 newparams.append(newparam)
187
188 return ";".join(newparams).strip()
189
190 # We parse and rewrite the groupadd components
191 def rewrite_groupadd(params, is_pkg):
192 parser = oe.useradd.build_groupadd_parser()
193
194 newparams = []
195 groups = None
196 for param in oe.useradd.split_commands(params):
197 try:
198 # If we're processing multiple lines, we could have left over values here...
199 gaargs = parser.parse_args(oe.useradd.split_args(param))
200 except Exception as e:
201 bb.fatal("%s: Unable to parse arguments for GROUPADD_PARAM_%s '%s': %s" % (d.getVar('PN'), pkg, param, e))
202
203 # Read all group files specified in USERADD_GID_TABLES or files/group
204 # Use the standard group layout:
205 # groupname:password:group_id:group_members
206 #
207 # If a field is left blank, the original value will be used. The 'groupname' field
208 # is required.
209 #
210 # Note: similar to the passwd file, the 'password' filed is ignored
211 # Note: group_members is ignored, group members must be configured with the GROUPMEMS_PARAM
212 if not groups:
213 files, table_var, table_value = get_table_list(d, 'USERADD_GID_TABLES', 'files/group')
214 groups = merge_files(files, 4)
215
216 type = 'system group' if gaargs.system else 'normal group'
217 if gaargs.GROUP not in groups:
218 handle_missing_id(gaargs.GROUP, type, pkg, files, table_var, table_value)
219 newparams.append(param)
220 continue
221
222 field = groups[gaargs.GROUP]
223
224 if field[2]:
225 if gaargs.gid and (gaargs.gid != field[2]):
226 bb.warn("%s: Changing groupname %s's gid from (%s) to (%s), verify configuration files!" % (d.getVar('PN'), gaargs.GROUP, gaargs.gid, field[2]))
227 gaargs.gid = field[2]
228
229 if not gaargs.gid or not gaargs.gid.isdigit():
230 handle_missing_id(gaargs.GROUP, type, pkg, files, table_var, table_value)
231
232 # Reconstruct the args...
233 newparam = ['', ' --force'][gaargs.force]
234 newparam += ['', ' --gid %s' % gaargs.gid][gaargs.gid != None]
235 newparam += ['', ' --key %s' % gaargs.key][gaargs.key != None]
236 newparam += ['', ' --non-unique'][gaargs.non_unique]
237 if gaargs.password != None:
238 newparam += ['', ' --password %s' % gaargs.password][gaargs.password != None]
239 elif gaargs.clear_password:
240 newparam += ['', ' --clear-password %s' % gaargs.clear_password][gaargs.clear_password != None]
241 newparam += ['', ' --root %s' % gaargs.root][gaargs.root != None]
242 newparam += ['', ' --system'][gaargs.system]
243 newparam += ' %s' % gaargs.GROUP
244
245 newparams.append(newparam)
246
247 return ";".join(newparams).strip()
248
249 # The parsing of the current recipe depends on the content of
250 # the files listed in USERADD_UID/GID_TABLES. We need to tell bitbake
251 # about that explicitly to trigger re-parsing and thus re-execution of
252 # this code when the files change.
253 bbpath = d.getVar('BBPATH')
254 for varname, default in (('USERADD_UID_TABLES', 'files/passwd'),
255 ('USERADD_GID_TABLES', 'files/group')):
256 tables = d.getVar(varname)
257 if not tables:
258 tables = default
259 for conf_file in tables.split():
260 bb.parse.mark_dependency(d, bb.utils.which(bbpath, conf_file))
261
262 # Load and process the users and groups, rewriting the adduser/addgroup params
263 useradd_packages = d.getVar('USERADD_PACKAGES') or ""
264
265 for pkg in useradd_packages.split():
266 # Groupmems doesn't have anything we might want to change, so simply validating
267 # is a bit of a waste -- only process useradd/groupadd
268 useradd_param = d.getVar('USERADD_PARAM_%s' % pkg)
269 if useradd_param:
270 #bb.warn("Before: 'USERADD_PARAM_%s' - '%s'" % (pkg, useradd_param))
271 d.setVar('USERADD_PARAM_%s' % pkg, rewrite_useradd(useradd_param, True))
272 #bb.warn("After: 'USERADD_PARAM_%s' - '%s'" % (pkg, d.getVar('USERADD_PARAM_%s' % pkg)))
273
274 groupadd_param = d.getVar('GROUPADD_PARAM_%s' % pkg)
275 if groupadd_param:
276 #bb.warn("Before: 'GROUPADD_PARAM_%s' - '%s'" % (pkg, groupadd_param))
277 d.setVar('GROUPADD_PARAM_%s' % pkg, rewrite_groupadd(groupadd_param, True))
278 #bb.warn("After: 'GROUPADD_PARAM_%s' - '%s'" % (pkg, d.getVar('GROUPADD_PARAM_%s' % pkg)))
279
280 # Load and process extra users and groups, rewriting only adduser/addgroup params
281 pkg = d.getVar('PN')
282 extrausers = d.getVar('EXTRA_USERS_PARAMS') or ""
283
284 #bb.warn("Before: 'EXTRA_USERS_PARAMS' - '%s'" % (d.getVar('EXTRA_USERS_PARAMS')))
285 new_extrausers = []
286 for cmd in oe.useradd.split_commands(extrausers):
287 if re.match('''useradd (.*)''', cmd):
288 useradd_param = re.match('''useradd (.*)''', cmd).group(1)
289 useradd_param = rewrite_useradd(useradd_param, False)
290 cmd = 'useradd %s' % useradd_param
291 elif re.match('''groupadd (.*)''', cmd):
292 groupadd_param = re.match('''groupadd (.*)''', cmd).group(1)
293 groupadd_param = rewrite_groupadd(groupadd_param, False)
294 cmd = 'groupadd %s' % groupadd_param
295
296 new_extrausers.append(cmd)
297
298 new_extrausers.append('')
299 d.setVar('EXTRA_USERS_PARAMS', ';'.join(new_extrausers))
300 #bb.warn("After: 'EXTRA_USERS_PARAMS' - '%s'" % (d.getVar('EXTRA_USERS_PARAMS')))
301
302
303python __anonymous() {
304 if not bb.data.inherits_class('nativesdk', d) \
305 and not bb.data.inherits_class('native', d):
306 try:
307 update_useradd_static_config(d)
308 except NotImplementedError as f:
309 bb.debug(1, "Skipping recipe %s: %s" % (d.getVar('PN'), f))
310 raise bb.parse.SkipRecipe(f)
311}