useradd-staticids.bbclass 15 KB

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