blob: afb580aedc29efe6b163b9a46dafd78423ecf496 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001# 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 argparse
Patrick Williamsf1e5d692016-03-30 15:21:19 -05005 import itertools
Patrick Williamsc124f4f2015-09-15 14:41:29 -05006 import re
Patrick Williamsc0f7c042017-02-23 20:41:17 -06007 import errno
Patrick Williamsc124f4f2015-09-15 14:41:29 -05008
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):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060019 bb.fatal(message)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050020
Patrick Williamsf1e5d692016-03-30 15:21:19 -050021 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
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050026 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():
Patrick Williamsc0f7c042017-02-23 20:41:17 -060034 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
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050050
51 return id_table
52
Patrick Williamsc0f7c042017-02-23 20:41:17 -060053 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 bb.fatal("%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
Patrick Williamsc124f4f2015-09-15 14:41:29 -050061 # 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")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050076 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)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050079 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")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050085 parser.add_argument("-U", "--user-group", help="create a group with the same name as the user", action="store_const", const=True)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050086 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
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050090 # paths are resolved via BBPATH
Patrick Williamsc124f4f2015-09-15 14:41:29 -050091 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 = []
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500102 users = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500103 for param in re.split('''[ \t]*;[ \t]*(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', params):
104 param = param.strip()
105 if not param:
106 continue
107 try:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600108 uaargs = parser.parse_args(re.split('''[ \t]+(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', param))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500109 except:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600110 bb.fatal("%s: Unable to parse arguments for USERADD_PARAM_%s: '%s'" % (d.getVar('PN', True), pkg, param))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500111
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500112 # Read all passwd files specified in USERADD_UID_TABLES or files/passwd
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500113 # Use the standard passwd layout:
114 # username:password:user_id:group_id:comment:home_directory:login_shell
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500115 #
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.
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500123 if not users:
124 users = merge_files(get_passwd_list(d), 7)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500125
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500126 if uaargs.LOGIN not in users:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600127 if not uaargs.uid or not uaargs.uid.isdigit() or not uaargs.gid:
128 handle_missing_id(uaargs.LOGIN, 'user', pkg)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500129 continue
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500130
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500131 field = users[uaargs.LOGIN]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500132
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500133 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
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500176
177 # Should be an error if a specific option is set...
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600178 if not uaargs.uid or not uaargs.uid.isdigit() or not uaargs.gid:
179 handle_missing_id(uaargs.LOGIN, 'user', pkg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500180
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]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500193 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]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500196 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]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500202 newparam += ['', ' --user-group'][uaargs.user_group is True]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500203 newparam += ' %s' % uaargs.LOGIN
204
205 newparams.append(newparam)
206
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500207 return ";".join(newparams).strip()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500208
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
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500224 # paths are resolved via BBPATH
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500225 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 = []
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500236 groups = None
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500237 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...
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600243 gaargs = parser.parse_args(re.split('''[ \t]+(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', param))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500244 except:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600245 bb.fatal("%s: Unable to parse arguments for GROUPADD_PARAM_%s: '%s'" % (d.getVar('PN', True), pkg, param))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500246
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500247 # Read all group files specified in USERADD_GID_TABLES or files/group
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500248 # 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
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500256 if not groups:
257 groups = merge_files(get_group_list(d), 4)
258
259 if gaargs.GROUP not in groups:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600260 if not gaargs.gid or not gaargs.gid.isdigit():
261 handle_missing_id(gaargs.GROUP, 'group', pkg)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500262 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]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500270
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600271 if not gaargs.gid or not gaargs.gid.isdigit():
272 handle_missing_id(gaargs.GROUP, 'group', pkg)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500273
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
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500286 return ";".join(newparams).strip()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500287
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600288 # 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
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500301 # 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
321python __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}