blob: 924d6eae606ab78d37e3bb27c033d5e75e23773b [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
7
8 class myArgumentParser( argparse.ArgumentParser ):
9 def _print_message(self, message, file=None):
10 bb.warn("%s - %s: %s" % (d.getVar('PN', True), pkg, message))
11
12 # This should never be called...
13 def exit(self, status=0, message=None):
14 message = message or ("%s - %s: useradd.bbclass: Argument parsing exited" % (d.getVar('PN', True), pkg))
15 error(message)
16
17 def error(self, message):
18 raise bb.build.FuncFailed(message)
19
Patrick Williamsf1e5d692016-03-30 15:21:19 -050020 def list_extend(iterable, length, obj = None):
21 """Ensure that iterable is the specified length by extending with obj
22 and return it as a list"""
23 return list(itertools.islice(itertools.chain(iterable, itertools.repeat(obj)), length))
24
Patrick Williamsc124f4f2015-09-15 14:41:29 -050025 # We parse and rewrite the useradd components
26 def rewrite_useradd(params):
27 # The following comes from --help on useradd from shadow
28 parser = myArgumentParser(prog='useradd')
29 parser.add_argument("-b", "--base-dir", metavar="BASE_DIR", help="base directory for the home directory of the new account")
30 parser.add_argument("-c", "--comment", metavar="COMMENT", help="GECOS field of the new account")
31 parser.add_argument("-d", "--home-dir", metavar="HOME_DIR", help="home directory of the new account")
32 parser.add_argument("-D", "--defaults", help="print or change default useradd configuration", action="store_true")
33 parser.add_argument("-e", "--expiredate", metavar="EXPIRE_DATE", help="expiration date of the new account")
34 parser.add_argument("-f", "--inactive", metavar="INACTIVE", help="password inactivity period of the new account")
35 parser.add_argument("-g", "--gid", metavar="GROUP", help="name or ID of the primary group of the new account")
36 parser.add_argument("-G", "--groups", metavar="GROUPS", help="list of supplementary groups of the new account")
37 parser.add_argument("-k", "--skel", metavar="SKEL_DIR", help="use this alternative skeleton directory")
38 parser.add_argument("-K", "--key", metavar="KEY=VALUE", help="override /etc/login.defs defaults")
39 parser.add_argument("-l", "--no-log-init", help="do not add the user to the lastlog and faillog databases", action="store_true")
40 parser.add_argument("-m", "--create-home", help="create the user's home directory", action="store_true")
41 parser.add_argument("-M", "--no-create-home", help="do not create the user's home directory", action="store_true")
42 parser.add_argument("-N", "--no-user-group", help="do not create a group with the same name as the user", action="store_true")
43 parser.add_argument("-o", "--non-unique", help="allow to create users with duplicate (non-unique UID)", action="store_true")
44 parser.add_argument("-p", "--password", metavar="PASSWORD", help="encrypted password of the new account")
45 parser.add_argument("-R", "--root", metavar="CHROOT_DIR", help="directory to chroot into")
46 parser.add_argument("-r", "--system", help="create a system account", action="store_true")
47 parser.add_argument("-s", "--shell", metavar="SHELL", help="login shell of the new account")
48 parser.add_argument("-u", "--uid", metavar="UID", help="user ID of the new account")
49 parser.add_argument("-U", "--user-group", help="create a group with the same name as the user", action="store_true")
50 parser.add_argument("LOGIN", help="Login name of the new user")
51
52 # Return a list of configuration files based on either the default
53 # files/passwd or the contents of USERADD_UID_TABLES
54 # paths are resulved via BBPATH
55 def get_passwd_list(d):
56 str = ""
57 bbpath = d.getVar('BBPATH', True)
58 passwd_tables = d.getVar('USERADD_UID_TABLES', True)
59 if not passwd_tables:
60 passwd_tables = 'files/passwd'
61 for conf_file in passwd_tables.split():
62 str += " %s" % bb.utils.which(bbpath, conf_file)
63 return str
64
65 newparams = []
66 for param in re.split('''[ \t]*;[ \t]*(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', params):
67 param = param.strip()
68 if not param:
69 continue
70 try:
71 uaargs = parser.parse_args(re.split('''[ \t]*(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', param))
72 except:
73 raise bb.build.FuncFailed("%s: Unable to parse arguments for USERADD_PARAM_%s: '%s'" % (d.getVar('PN', True), pkg, param))
74
75 # files/passwd or the contents of USERADD_UID_TABLES
76 # Use the standard passwd layout:
77 # username:password:user_id:group_id:comment:home_directory:login_shell
78 # (we want to process in reverse order, as 'last found' in the list wins)
79 #
80 # If a field is left blank, the original value will be used. The 'username'
81 # field is required.
82 #
83 # Note: we ignore the password field, as including even the hashed password
84 # in the useradd command may introduce a security hole. It's assumed that
85 # all new users get the default ('*' which prevents login) until the user is
86 # specifically configured by the system admin.
87 for conf in get_passwd_list(d).split()[::-1]:
88 if os.path.exists(conf):
89 f = open(conf, "r")
90 for line in f:
91 if line.startswith('#'):
92 continue
Patrick Williamsf1e5d692016-03-30 15:21:19 -050093 # Make sure there always are at least seven elements in
94 # the field list. This allows for leaving out trailing
95 # colons in the passwd file.
96 field = list_extend(line.rstrip().split(":"), 7)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050097 if field[0] == uaargs.LOGIN:
98 if uaargs.uid and field[2] and (uaargs.uid != field[2]):
99 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]))
100 uaargs.uid = [field[2], uaargs.uid][not field[2]]
101
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 uaargs.groupname = [uaargs.gid, uaargs.LOGIN][not uaargs.gid or uaargs.user_group]
110 uaargs.groupid = [uaargs.gid, uaargs.groupname][not uaargs.gid]
111 uaargs.groupid = [field[3], uaargs.groupid][not field[3]]
112
113 if not uaargs.gid or uaargs.gid != uaargs.groupid:
114 if (uaargs.groupid and uaargs.groupid.isdigit()) and (uaargs.groupname and uaargs.groupname.isdigit()) and (uaargs.groupid != uaargs.groupname):
115 # We want to add a group, but we don't know it's name... so we can't add the group...
116 # We have to assume the group has previously been added or we'll fail on the adduser...
117 # Note: specifying the actual gid is very rare in OE, usually the group name is specified.
118 bb.warn("%s: Changing gid for login %s from (%s) to (%s), verify configuration files!" % (d.getVar('PN', True), uaargs.LOGIN, uaargs.groupname, uaargs.gid))
119 elif (uaargs.groupid and not uaargs.groupid.isdigit()) and uaargs.groupid == uaargs.groupname:
120 # We don't have a number, so we have to add a name
121 bb.debug(1, "Adding group %s!" % (uaargs.groupname))
122 uaargs.gid = uaargs.groupid
123 uaargs.user_group = False
124 groupadd = d.getVar("GROUPADD_PARAM_%s" % pkg, True)
125 newgroup = "%s %s" % (['', ' --system'][uaargs.system], uaargs.groupname)
126 if groupadd:
127 d.setVar("GROUPADD_PARAM_%s" % pkg, "%s ; %s" % (groupadd, newgroup))
128 else:
129 d.setVar("GROUPADD_PARAM_%s" % pkg, newgroup)
130 elif uaargs.groupname and (uaargs.groupid and uaargs.groupid.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 uaargs.gid = uaargs.groupid
134 uaargs.user_group = False
135 groupadd = d.getVar("GROUPADD_PARAM_%s" % pkg, True)
136 newgroup = "-g %s %s" % (uaargs.gid, uaargs.groupname)
137 if groupadd:
138 d.setVar("GROUPADD_PARAM_%s" % pkg, "%s ; %s" % (groupadd, newgroup))
139 else:
140 d.setVar("GROUPADD_PARAM_%s" % pkg, newgroup)
141
142 uaargs.comment = ["'%s'" % field[4], uaargs.comment][not field[4]]
143 uaargs.home_dir = [field[5], uaargs.home_dir][not field[5]]
144 uaargs.shell = [field[6], uaargs.shell][not field[6]]
145 break
146
147 # Should be an error if a specific option is set...
148 if d.getVar('USERADD_ERROR_DYNAMIC', True) == '1' and not ((uaargs.uid and uaargs.uid.isdigit()) and uaargs.gid):
149 #bb.error("Skipping recipe %s, package %s which adds username %s does not have a static uid defined." % (d.getVar('PN', True), pkg, uaargs.LOGIN))
150 raise bb.build.FuncFailed("%s - %s: Username %s does not have a static uid defined." % (d.getVar('PN', True), pkg, uaargs.LOGIN))
151
152 # Reconstruct the args...
153 newparam = ['', ' --defaults'][uaargs.defaults]
154 newparam += ['', ' --base-dir %s' % uaargs.base_dir][uaargs.base_dir != None]
155 newparam += ['', ' --comment %s' % uaargs.comment][uaargs.comment != None]
156 newparam += ['', ' --home-dir %s' % uaargs.home_dir][uaargs.home_dir != None]
157 newparam += ['', ' --expiredata %s' % uaargs.expiredate][uaargs.expiredate != None]
158 newparam += ['', ' --inactive %s' % uaargs.inactive][uaargs.inactive != None]
159 newparam += ['', ' --gid %s' % uaargs.gid][uaargs.gid != None]
160 newparam += ['', ' --groups %s' % uaargs.groups][uaargs.groups != None]
161 newparam += ['', ' --skel %s' % uaargs.skel][uaargs.skel != None]
162 newparam += ['', ' --key %s' % uaargs.key][uaargs.key != None]
163 newparam += ['', ' --no-log-init'][uaargs.no_log_init]
164 newparam += ['', ' --create-home'][uaargs.create_home]
165 newparam += ['', ' --no-create-home'][uaargs.no_create_home]
166 newparam += ['', ' --no-user-group'][uaargs.no_user_group]
167 newparam += ['', ' --non-unique'][uaargs.non_unique]
168 newparam += ['', ' --password %s' % uaargs.password][uaargs.password != None]
169 newparam += ['', ' --root %s' % uaargs.root][uaargs.root != None]
170 newparam += ['', ' --system'][uaargs.system]
171 newparam += ['', ' --shell %s' % uaargs.shell][uaargs.shell != None]
172 newparam += ['', ' --uid %s' % uaargs.uid][uaargs.uid != None]
173 newparam += ['', ' --user-group'][uaargs.user_group]
174 newparam += ' %s' % uaargs.LOGIN
175
176 newparams.append(newparam)
177
178 return " ;".join(newparams).strip()
179
180 # We parse and rewrite the groupadd components
181 def rewrite_groupadd(params):
182 # The following comes from --help on groupadd from shadow
183 parser = myArgumentParser(prog='groupadd')
184 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")
185 parser.add_argument("-g", "--gid", metavar="GID", help="use GID for the new group")
186 parser.add_argument("-K", "--key", metavar="KEY=VALUE", help="override /etc/login.defs defaults")
187 parser.add_argument("-o", "--non-unique", help="allow to create groups with duplicate (non-unique) GID", action="store_true")
188 parser.add_argument("-p", "--password", metavar="PASSWORD", help="use this encrypted password for the new group")
189 parser.add_argument("-R", "--root", metavar="CHROOT_DIR", help="directory to chroot into")
190 parser.add_argument("-r", "--system", help="create a system account", action="store_true")
191 parser.add_argument("GROUP", help="Group name of the new group")
192
193 # Return a list of configuration files based on either the default
194 # files/group or the contents of USERADD_GID_TABLES
195 # paths are resulved via BBPATH
196 def get_group_list(d):
197 str = ""
198 bbpath = d.getVar('BBPATH', True)
199 group_tables = d.getVar('USERADD_GID_TABLES', True)
200 if not group_tables:
201 group_tables = 'files/group'
202 for conf_file in group_tables.split():
203 str += " %s" % bb.utils.which(bbpath, conf_file)
204 return str
205
206 newparams = []
207 for param in re.split('''[ \t]*;[ \t]*(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', params):
208 param = param.strip()
209 if not param:
210 continue
211 try:
212 # If we're processing multiple lines, we could have left over values here...
213 gaargs = parser.parse_args(re.split('''[ \t]*(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', param))
214 except:
215 raise bb.build.FuncFailed("%s: Unable to parse arguments for GROUPADD_PARAM_%s: '%s'" % (d.getVar('PN', True), pkg, param))
216
217 # Need to iterate over layers and open the right file(s)
218 # Use the standard group layout:
219 # groupname:password:group_id:group_members
220 #
221 # If a field is left blank, the original value will be used. The 'groupname' field
222 # is required.
223 #
224 # Note: similar to the passwd file, the 'password' filed is ignored
225 # Note: group_members is ignored, group members must be configured with the GROUPMEMS_PARAM
226 for conf in get_group_list(d).split()[::-1]:
227 if os.path.exists(conf):
228 f = open(conf, "r")
229 for line in f:
230 if line.startswith('#'):
231 continue
Patrick Williamsf1e5d692016-03-30 15:21:19 -0500232 # Make sure there always are at least four elements in
233 # the field list. This allows for leaving out trailing
234 # colons in the group file.
235 field = list_extend(line.rstrip().split(":"), 4)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500236 if field[0] == gaargs.GROUP and field[2]:
237 if gaargs.gid and (gaargs.gid != field[2]):
238 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]))
239 gaargs.gid = field[2]
240 break
241
242 if d.getVar('USERADD_ERROR_DYNAMIC', True) == '1' and not (gaargs.gid and gaargs.gid.isdigit()):
243 #bb.error("Skipping recipe %s, package %s which adds groupname %s does not have a static gid defined." % (d.getVar('PN', True), pkg, gaargs.GROUP))
244 raise bb.build.FuncFailed("%s - %s: Groupname %s does not have a static gid defined." % (d.getVar('PN', True), pkg, gaargs.GROUP))
245
246 # Reconstruct the args...
247 newparam = ['', ' --force'][gaargs.force]
248 newparam += ['', ' --gid %s' % gaargs.gid][gaargs.gid != None]
249 newparam += ['', ' --key %s' % gaargs.key][gaargs.key != None]
250 newparam += ['', ' --non-unique'][gaargs.non_unique]
251 newparam += ['', ' --password %s' % gaargs.password][gaargs.password != None]
252 newparam += ['', ' --root %s' % gaargs.root][gaargs.root != None]
253 newparam += ['', ' --system'][gaargs.system]
254 newparam += ' %s' % gaargs.GROUP
255
256 newparams.append(newparam)
257
258 return " ;".join(newparams).strip()
259
260 # Load and process the users and groups, rewriting the adduser/addgroup params
261 useradd_packages = d.getVar('USERADD_PACKAGES', True)
262
263 for pkg in useradd_packages.split():
264 # Groupmems doesn't have anything we might want to change, so simply validating
265 # is a bit of a waste -- only process useradd/groupadd
266 useradd_param = d.getVar('USERADD_PARAM_%s' % pkg, True)
267 if useradd_param:
268 #bb.warn("Before: 'USERADD_PARAM_%s' - '%s'" % (pkg, useradd_param))
269 d.setVar('USERADD_PARAM_%s' % pkg, rewrite_useradd(useradd_param))
270 #bb.warn("After: 'USERADD_PARAM_%s' - '%s'" % (pkg, d.getVar('USERADD_PARAM_%s' % pkg, True)))
271
272 groupadd_param = d.getVar('GROUPADD_PARAM_%s' % pkg, True)
273 if groupadd_param:
274 #bb.warn("Before: 'GROUPADD_PARAM_%s' - '%s'" % (pkg, groupadd_param))
275 d.setVar('GROUPADD_PARAM_%s' % pkg, rewrite_groupadd(groupadd_param))
276 #bb.warn("After: 'GROUPADD_PARAM_%s' - '%s'" % (pkg, d.getVar('GROUPADD_PARAM_%s' % pkg, True)))
277
278
279
280python __anonymous() {
281 if not bb.data.inherits_class('nativesdk', d) \
282 and not bb.data.inherits_class('native', d):
283 try:
284 update_useradd_static_config(d)
285 except bb.build.FuncFailed as f:
286 bb.debug(1, "Skipping recipe %s: %s" % (d.getVar('PN', True), f))
287 raise bb.parse.SkipPackage(f)
288}