Skip to contentSkip to conversation

Improvements for useradd-staticids.bbclass

PATCH Superseded Peter Kjellerstedt 2 participants 14 messages Nov 4, 2015 – Nov 24, 2015

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover Improvements for useradd-staticids.bbclass

This series of patches aims to improve useradd-staticids.bbclass.

We are currently using useradd-staticids.bbclass to make sure all users and groups have well defined IDs. So far we have had the definitions of the users both in the recipes and in the passwd file used by useradd-staticids.bbclass. Since we have a huge number of recipes that create users, having to duplicate the definitions all over the place has turned out to be a burden we should be able to avoid.

So the current plan for us is to have one passwd file per layer with the definitions of all users that layer needs. These definitions do not include the static IDs for the users. Instead the static IDs for the users are specified in a distro specific passwd-static file. There is also a distro specific group-static file for the group IDs. With that in place it should be enough to define a user as:

USERADD_PARAM_${PN} = "--system foobar"

in a recipe and let useradd-staticids.bbclass handle the specifics for how that user should be defined.

The above worked fine for all users that had a primary group with the same name as the user. However, it turned out that for users that wanted some other primary group, specifying it in the passwd file was not enough. We still had to add --gid <some group> in the recipe where <some group> had to match what was specified in the passwd file. This was less than optimal, and somewhat defeated the setup.

It also turned out that for users with a primary group that does not match the user name, useradd-staticids.bbclass would still add the creation of a group with the same name as the user (when it parsed the passwd-static file) and the add another creation of the correct group (when it parsed the passwd file).

So after spending quite a lot of time on trying to decode how rewrite_useradd() calculated the --gid option, I came up with this series of changes that should correct the problems described above and make the code easier to understand while (hopefully) maintaining compatibility with the old code.

I fully understand that this is very late for Jethro and do not really expect it to make it into 2.0.0, but if at all possible I hope it can make it since that would make my life much easier. :)

//Peter

The following changes since commit fc45deac89ef63ca1c44e763c38ced7dfd72cbe1:

build-appliance-image: Update to jethro head revision (2015-11-03 14:03:03 +0000)

are available in the git repository at:

git://git.yoctoproject.org/poky-contrib pkj/useradd_improvements
http://git.yoctoproject.org/cgit.cgi/poky-contrib/log/?h=pkj/useradd_improvements

Peter Kjellerstedt (5):
useradd-staticids.bbclass: Treat mutually exclusive options as such useradd-staticids.bbclass: Make --no-user-group have effect useradd-staticids.bbclass: Simplify some logic useradd-staticids.bbclass: Simplify the logic for when to add groups useradd-staticids.bbclass: Read passwd/group files before parsing

 meta/classes/useradd-staticids.bbclass | 192 ++++++++++++++++++---------------
 1 file changed, 103 insertions(+), 89 deletions(-)
Signature · 1 line
2.1.0
#1 lore raw

PATCH 1/5 useradd-staticids.bbclass: Treat mutually exclusive options as such

The useradd options --create-home/--no-create-home and --user-group/--no-user-group are mutually exclusive and should be treated as such.

---
 meta/classes/useradd-staticids.bbclass | 27 ++++++++++++++-------------
 1 file changed, 14 insertions(+), 13 deletions(-)
meta/classes/useradd-staticids.bbclass +14 -13
index 924d6ea..9d59aca 100644
@@ -37,21 +37,21 @@ def update_useradd_static_config(d):
         parser.add_argument("-k", "--skel", metavar="SKEL_DIR", help="use this alternative skeleton directory")
         parser.add_argument("-K", "--key", metavar="KEY=VALUE", help="override /etc/login.defs defaults")
         parser.add_argument("-l", "--no-log-init", help="do not add the user to the lastlog and faillog databases", action="store_true")
-        parser.add_argument("-m", "--create-home", help="create the user's home directory", action="store_true")
-        parser.add_argument("-M", "--no-create-home", help="do not create the user's home directory", action="store_true")
-        parser.add_argument("-N", "--no-user-group", help="do not create a group with the same name as the user", action="store_true")
+        parser.add_argument("-m", "--create-home", help="create the user's home directory", action="store_const", const=True)
+        parser.add_argument("-M", "--no-create-home", dest="create_home", help="do not create the user's home directory", action="store_const", const=False)
+        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)
         parser.add_argument("-o", "--non-unique", help="allow to create users with duplicate (non-unique UID)", action="store_true")
         parser.add_argument("-p", "--password", metavar="PASSWORD", help="encrypted password of the new account")
         parser.add_argument("-R", "--root", metavar="CHROOT_DIR", help="directory to chroot into")
         parser.add_argument("-r", "--system", help="create a system account", action="store_true")
         parser.add_argument("-s", "--shell", metavar="SHELL", help="login shell of the new account")
         parser.add_argument("-u", "--uid", metavar="UID", help="user ID of the new account")
-        parser.add_argument("-U", "--user-group", help="create a group with the same name as the user", action="store_true")
+        parser.add_argument("-U", "--user-group", help="create a group with the same name as the user", action="store_const", const=True)
         parser.add_argument("LOGIN", help="Login name of the new user")
 
         # Return a list of configuration files based on either the default
         # files/passwd or the contents of USERADD_UID_TABLES
-        # paths are resulved via BBPATH
+        # paths are resolved via BBPATH
         def get_passwd_list(d):
             str = ""
             bbpath = d.getVar('BBPATH', True)
@@ -106,7 +106,8 @@ def update_useradd_static_config(d):
                             # So if the implicit username-group creation is on, then the implicit groupname (LOGIN)
                             # is used, and we disable the user_group option.
                             #
-                            uaargs.groupname = [uaargs.gid, uaargs.LOGIN][not uaargs.gid or uaargs.user_group]
+                            user_group = uaargs.user_group is None or uaargs.user_group is True
+                            uaargs.groupname = [uaargs.gid, uaargs.LOGIN][not uaargs.gid or user_group]
                             uaargs.groupid = [uaargs.gid, uaargs.groupname][not uaargs.gid]
                             uaargs.groupid = [field[3], uaargs.groupid][not field[3]]
 
@@ -120,7 +121,7 @@ def update_useradd_static_config(d):
                                     # We don't have a number, so we have to add a name
                                     bb.debug(1, "Adding group %s!" % (uaargs.groupname))
                                     uaargs.gid = uaargs.groupid
-                                    uaargs.user_group = False
+                                    uaargs.user_group = None
                                     groupadd = d.getVar("GROUPADD_PARAM_%s" % pkg, True)
                                     newgroup = "%s %s" % (['', ' --system'][uaargs.system], uaargs.groupname)
                                     if groupadd:
@@ -131,7 +132,7 @@ def update_useradd_static_config(d):
                                     # We have a group name and a group number to assign it to
                                     bb.debug(1, "Adding group %s  gid (%s)!" % (uaargs.groupname, uaargs.groupid))
                                     uaargs.gid = uaargs.groupid
-                                    uaargs.user_group = False
+                                    uaargs.user_group = None
                                     groupadd = d.getVar("GROUPADD_PARAM_%s" % pkg, True)
                                     newgroup = "-g %s %s" % (uaargs.gid, uaargs.groupname)
                                     if groupadd:
@@ -161,16 +162,16 @@ def update_useradd_static_config(d):
             newparam += ['', ' --skel %s' % uaargs.skel][uaargs.skel != None]
             newparam += ['', ' --key %s' % uaargs.key][uaargs.key != None]
             newparam += ['', ' --no-log-init'][uaargs.no_log_init]
-            newparam += ['', ' --create-home'][uaargs.create_home]
-            newparam += ['', ' --no-create-home'][uaargs.no_create_home]
-            newparam += ['', ' --no-user-group'][uaargs.no_user_group]
+            newparam += ['', ' --create-home'][uaargs.create_home is True]
+            newparam += ['', ' --no-create-home'][uaargs.create_home is False]
+            newparam += ['', ' --no-user-group'][uaargs.user_group is False]
             newparam += ['', ' --non-unique'][uaargs.non_unique]
             newparam += ['', ' --password %s' % uaargs.password][uaargs.password != None]
             newparam += ['', ' --root %s' % uaargs.root][uaargs.root != None]
             newparam += ['', ' --system'][uaargs.system]
             newparam += ['', ' --shell %s' % uaargs.shell][uaargs.shell != None]
             newparam += ['', ' --uid %s' % uaargs.uid][uaargs.uid != None]
-            newparam += ['', ' --user-group'][uaargs.user_group]
+            newparam += ['', ' --user-group'][uaargs.user_group is True]
             newparam += ' %s' % uaargs.LOGIN
 
             newparams.append(newparam)
@@ -192,7 +193,7 @@ def update_useradd_static_config(d):
 
         # Return a list of configuration files based on either the default
         # files/group or the contents of USERADD_GID_TABLES
-        # paths are resulved via BBPATH
+        # paths are resolved via BBPATH
         def get_group_list(d):
             str = ""
             bbpath = d.getVar('BBPATH', True)
Signature · 1 line
2.1.0
#2 lore raw

PATCH 2/5 useradd-staticids.bbclass: Make --no-user-group have effect

In reply to Peter Kjellerstedt

If --no-user-group is specified in USERADD_PARAM_${PN} for a user and no --gid is specified, then we should not assume that the group name for the user is the user name.

---
 meta/classes/useradd-staticids.bbclass | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
meta/classes/useradd-staticids.bbclass +1 -1
index 9d59aca..c2e6579 100644
@@ -107,7 +107,7 @@ def update_useradd_static_config(d):
                             # is used, and we disable the user_group option.
                             #
                             user_group = uaargs.user_group is None or uaargs.user_group is True
-                            uaargs.groupname = [uaargs.gid, uaargs.LOGIN][not uaargs.gid or user_group]
+                            uaargs.groupname = [uaargs.LOGIN, uaargs.gid][not user_group]
                             uaargs.groupid = [uaargs.gid, uaargs.groupname][not uaargs.gid]
                             uaargs.groupid = [field[3], uaargs.groupid][not field[3]]
 
Signature · 1 line
2.1.0
#3 lore raw

PATCH 3/5 useradd-staticids.bbclass: Simplify some logic

In reply to Peter Kjellerstedt

The [<on_true>, <on_false>][not <condition>] construct may solve the problem of implementing a conditional operator, but it is not very readable. At least I find this:

uaargs.groupid = field[3] or uaargs.gid or uaargs.groupname

a lot more readable than this:

uaargs.groupid = [uaargs.gid, uaargs.groupname][not uaargs.gid] uaargs.groupid = [field[3], uaargs.groupid][not field[3]]

Also, the official conditional operator since Python 2.5 (<on_true> if <condition> else <on_false>) does not evaluate both <on_false> and <on_true> as [<on_true>, <on_false>][not <condition>] does.

---
 meta/classes/useradd-staticids.bbclass | 15 +++++++--------
 1 file changed, 7 insertions(+), 8 deletions(-)
meta/classes/useradd-staticids.bbclass +7 -8
index c2e6579..0e855e9 100644
@@ -97,7 +97,7 @@ def update_useradd_static_config(d):
                         if field[0] == uaargs.LOGIN:
                             if uaargs.uid and field[2] and (uaargs.uid != field[2]):
                                 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]))
-                            uaargs.uid = [field[2], uaargs.uid][not field[2]]
+                            uaargs.uid = field[2] or uaargs.uid
 
                             # Determine the possible groupname
                             # Unless the group name (or gid) is specified, we assume that the LOGIN is the groupname
@@ -107,9 +107,8 @@ def update_useradd_static_config(d):
                             # is used, and we disable the user_group option.
                             #
                             user_group = uaargs.user_group is None or uaargs.user_group is True
-                            uaargs.groupname = [uaargs.LOGIN, uaargs.gid][not user_group]
-                            uaargs.groupid = [uaargs.gid, uaargs.groupname][not uaargs.gid]
-                            uaargs.groupid = [field[3], uaargs.groupid][not field[3]]
+                            uaargs.groupname = uaargs.LOGIN if user_group else uaargs.gid
+                            uaargs.groupid = field[3] or uaargs.gid or uaargs.groupname
 
                             if not uaargs.gid or uaargs.gid != uaargs.groupid:
                                 if (uaargs.groupid and uaargs.groupid.isdigit()) and (uaargs.groupname and uaargs.groupname.isdigit()) and (uaargs.groupid != uaargs.groupname):
@@ -123,7 +122,7 @@ def update_useradd_static_config(d):
                                     uaargs.gid = uaargs.groupid
                                     uaargs.user_group = None
                                     groupadd = d.getVar("GROUPADD_PARAM_%s" % pkg, True)
-                                    newgroup = "%s %s" % (['', ' --system'][uaargs.system], uaargs.groupname)
+                                    newgroup = "%s %s" % (' --system' if uaargs.system else '', uaargs.groupname)
                                     if groupadd:
                                         d.setVar("GROUPADD_PARAM_%s" % pkg, "%s ; %s" % (groupadd, newgroup))
                                     else:
@@ -140,9 +139,9 @@ def update_useradd_static_config(d):
                                     else:
                                         d.setVar("GROUPADD_PARAM_%s" % pkg, newgroup)
 
-                            uaargs.comment = ["'%s'" % field[4], uaargs.comment][not field[4]]
-                            uaargs.home_dir = [field[5], uaargs.home_dir][not field[5]]
-                            uaargs.shell = [field[6], uaargs.shell][not field[6]]
+                            uaargs.comment = "'%s'" % field[4] if field[4] else uaargs.comment
+                            uaargs.home_dir = field[5] or uaargs.home_dir
+                            uaargs.shell = field[6] or uaargs.shell
                             break
 
             # Should be an error if a specific option is set...
Signature · 1 line
2.1.0
#4 lore raw

PATCH 4/5 useradd-staticids.bbclass: Simplify the logic for when to add groups

In reply to Peter Kjellerstedt

The original code was near impossible to follow, and missed a couple of cases. For example, if one added the following line to the passwd file specified in USERADD_UID_TABLES:

foobar:x:12345:nogroup::/:/bin/sh

and then specified the user as:

USERADD_PARAM_${PN} = "--system foobar"

one would then assume that the foobar user would be created with the primary group set to nogroup. However, it was not (the primary group would be foobar), and the only way to get it correct was to explicitly add --gid nogroup to the USERADD_PARAM_${PN}.

---
 meta/classes/useradd-staticids.bbclass | 36 +++++++++++++++-------------------
 1 file changed, 16 insertions(+), 20 deletions(-)
meta/classes/useradd-staticids.bbclass +16 -20
index 0e855e9..df4902e 100644
@@ -110,30 +110,26 @@ def update_useradd_static_config(d):
                             uaargs.groupname = uaargs.LOGIN if user_group else uaargs.gid
                             uaargs.groupid = field[3] or uaargs.gid or uaargs.groupname
 
-                            if not uaargs.gid or uaargs.gid != uaargs.groupid:
-                                if (uaargs.groupid and uaargs.groupid.isdigit()) and (uaargs.groupname and uaargs.groupname.isdigit()) and (uaargs.groupid != uaargs.groupname):
+                            if uaargs.groupid and uaargs.gid != uaargs.groupid:
+                                newgroup = None
+                                if not uaargs.groupid.isdigit():
+                                    # We don't have a group number, so we have to add a name
+                                    bb.debug(1, "Adding group %s!" % uaargs.groupid)
+                                    newgroup = "%s %s" % (' --system' if uaargs.system else '', uaargs.groupid)
+                                elif uaargs.groupname and not uaargs.groupname.isdigit():
+                                    # We have a group name and a group number to assign it to
+                                    bb.debug(1, "Adding group %s (gid %s)!" % (uaargs.groupname, uaargs.groupid))
+                                    newgroup = "-g %s %s" % (uaargs.groupid, uaargs.groupname)
+                                else:
                                     # We want to add a group, but we don't know it's name... so we can't add the group...
                                     # We have to assume the group has previously been added or we'll fail on the adduser...
                                     # Note: specifying the actual gid is very rare in OE, usually the group name is specified.
-                                    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))
-                                elif (uaargs.groupid and not uaargs.groupid.isdigit()) and uaargs.groupid == uaargs.groupname:
-                                    # We don't have a number, so we have to add a name
-                                    bb.debug(1, "Adding group %s!" % (uaargs.groupname))
-                                    uaargs.gid = uaargs.groupid
-                                    uaargs.user_group = None
-                                    groupadd = d.getVar("GROUPADD_PARAM_%s" % pkg, True)
-                                    newgroup = "%s %s" % (' --system' if uaargs.system else '', uaargs.groupname)
-                                    if groupadd:
-                                        d.setVar("GROUPADD_PARAM_%s" % pkg, "%s ; %s" % (groupadd, newgroup))
-                                    else:
-                                        d.setVar("GROUPADD_PARAM_%s" % pkg, newgroup)
-                                elif uaargs.groupname and (uaargs.groupid and uaargs.groupid.isdigit()):
-                                    # We have a group name and a group number to assign it to
-                                    bb.debug(1, "Adding group %s  gid (%s)!" % (uaargs.groupname, uaargs.groupid))
-                                    uaargs.gid = uaargs.groupid
-                                    uaargs.user_group = None
+                                    bb.warn("%s: Changing gid for login %s to %s, verify configuration files!" % (d.getVar('PN', True), uaargs.LOGIN, uaargs.groupid))
+
+                                uaargs.gid = uaargs.groupid
+                                uaargs.user_group = None
+                                if newgroup:
                                     groupadd = d.getVar("GROUPADD_PARAM_%s" % pkg, True)
-                                    newgroup = "-g %s %s" % (uaargs.gid, uaargs.groupname)
                                     if groupadd:
                                         d.setVar("GROUPADD_PARAM_%s" % pkg, "%s ; %s" % (groupadd, newgroup))
                                     else:
Signature · 1 line
2.1.0
#5 lore raw

PATCH 5/5 useradd-staticids.bbclass: Read passwd/group files before parsing

In reply to Peter Kjellerstedt

Read and merge the passwd/group files before parsing the user and group definitions. This means they will only be read once per recipe. This solves a problem where if a user was definied in multiple files, it could generate group definitions for groups that should not be created. E.g., if the first passwd file read defines a user as:

foobar::1234::::

and the second passwd file defines it as:

foobar:::nogroup:The foobar user:/:/bin/sh

then a foobar group would be created even if the user will use the nogroup as its primary group.

---
 meta/classes/useradd-staticids.bbclass | 168 ++++++++++++++++++---------------
 1 file changed, 93 insertions(+), 75 deletions(-)
meta/classes/useradd-staticids.bbclass +93 -75
index df4902e..a9b506d 100644
@@ -22,6 +22,30 @@ def update_useradd_static_config(d):
         and return it as a list"""
         return list(itertools.islice(itertools.chain(iterable, itertools.repeat(obj)), length))
 
+    def merge_files(file_list, exp_fields):
+        """Read each passwd/group file in file_list, split each line and create
+        a dictionary with the user/group names as keys and the split lines as
+        values. If the user/group name already exists in the dictionary, then
+        update any fields in the list with the values from the new list (if they
+        are set)."""
+        id_table = dict()
+        for conf in file_list.split():
+            if os.path.exists(conf):
+                f = open(conf, "r")
+                for line in f:
+                    if line.startswith('#'):
+                        continue
+                    # Make sure there always are at least exp_fields elements in
+                    # the field list. This allows for leaving out trailing
+                    # colons in the files.
+                    fields = list_extend(line.rstrip().split(":"), exp_fields)
+                    if fields[0] not in id_table:
+                        id_table[fields[0]] = fields
+                    else:
+                        id_table[fields[0]] = list(itertools.imap(lambda x, y: x or y, fields, id_table[fields[0]]))
+
+        return id_table
+
     # We parse and rewrite the useradd components
     def rewrite_useradd(params):
         # The following comes from --help on useradd from shadow
@@ -63,6 +87,7 @@ def update_useradd_static_config(d):
             return str
 
         newparams = []
+        users = None
         for param in re.split('''[ \t]*;[ \t]*(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', params):
             param = param.strip()
             if not param:
@@ -72,10 +97,9 @@ def update_useradd_static_config(d):
             except:
                 raise bb.build.FuncFailed("%s: Unable to parse arguments for USERADD_PARAM_%s: '%s'" % (d.getVar('PN', True), pkg, param))
 
-            # files/passwd or the contents of USERADD_UID_TABLES
+            # Read all passwd files specified in USERADD_UID_TABLES or files/passwd
             # Use the standard passwd layout:
             #  username:password:user_id:group_id:comment:home_directory:login_shell
-            # (we want to process in reverse order, as 'last found' in the list wins)
             #
             # If a field is left blank, the original value will be used.  The 'username'
             # field is required.
@@ -84,61 +108,57 @@ def update_useradd_static_config(d):
             # in the useradd command may introduce a security hole.  It's assumed that
             # all new users get the default ('*' which prevents login) until the user is
             # specifically configured by the system admin.
-            for conf in get_passwd_list(d).split()[::-1]:
-                if os.path.exists(conf):
-                    f = open(conf, "r")
-                    for line in f:
-                        if line.startswith('#'):
-                            continue
-                        # Make sure there always are at least seven elements in
-                        # the field list. This allows for leaving out trailing
-                        # colons in the passwd file.
-                        field = list_extend(line.rstrip().split(":"), 7)
-                        if field[0] == uaargs.LOGIN:
-                            if uaargs.uid and field[2] and (uaargs.uid != field[2]):
-                                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]))
-                            uaargs.uid = field[2] or uaargs.uid
-
-                            # Determine the possible groupname
-                            # Unless the group name (or gid) is specified, we assume that the LOGIN is the groupname
-                            #
-                            # By default the system has creation of the matching groups enabled
-                            # So if the implicit username-group creation is on, then the implicit groupname (LOGIN)
-                            # is used, and we disable the user_group option.
-                            #
-                            user_group = uaargs.user_group is None or uaargs.user_group is True
-                            uaargs.groupname = uaargs.LOGIN if user_group else uaargs.gid
-                            uaargs.groupid = field[3] or uaargs.gid or uaargs.groupname
-
-                            if uaargs.groupid and uaargs.gid != uaargs.groupid:
-                                newgroup = None
-                                if not uaargs.groupid.isdigit():
-                                    # We don't have a group number, so we have to add a name
-                                    bb.debug(1, "Adding group %s!" % uaargs.groupid)
-                                    newgroup = "%s %s" % (' --system' if uaargs.system else '', uaargs.groupid)
-                                elif uaargs.groupname and not uaargs.groupname.isdigit():
-                                    # We have a group name and a group number to assign it to
-                                    bb.debug(1, "Adding group %s (gid %s)!" % (uaargs.groupname, uaargs.groupid))
-                                    newgroup = "-g %s %s" % (uaargs.groupid, uaargs.groupname)
-                                else:
-                                    # We want to add a group, but we don't know it's name... so we can't add the group...
-                                    # We have to assume the group has previously been added or we'll fail on the adduser...
-                                    # Note: specifying the actual gid is very rare in OE, usually the group name is specified.
-                                    bb.warn("%s: Changing gid for login %s to %s, verify configuration files!" % (d.getVar('PN', True), uaargs.LOGIN, uaargs.groupid))
-
-                                uaargs.gid = uaargs.groupid
-                                uaargs.user_group = None
-                                if newgroup:
-                                    groupadd = d.getVar("GROUPADD_PARAM_%s" % pkg, True)
-                                    if groupadd:
-                                        d.setVar("GROUPADD_PARAM_%s" % pkg, "%s ; %s" % (groupadd, newgroup))
-                                    else:
-                                        d.setVar("GROUPADD_PARAM_%s" % pkg, newgroup)
-
-                            uaargs.comment = "'%s'" % field[4] if field[4] else uaargs.comment
-                            uaargs.home_dir = field[5] or uaargs.home_dir
-                            uaargs.shell = field[6] or uaargs.shell
-                            break
+            if not users:
+                users = merge_files(get_passwd_list(d), 7)
+
+            if uaargs.LOGIN not in users:
+                continue
+
+            field = users[uaargs.LOGIN]
+
+            if uaargs.uid and field[2] and (uaargs.uid != field[2]):
+                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]))
+            uaargs.uid = field[2] or uaargs.uid
+
+            # Determine the possible groupname
+            # Unless the group name (or gid) is specified, we assume that the LOGIN is the groupname
+            #
+            # By default the system has creation of the matching groups enabled
+            # So if the implicit username-group creation is on, then the implicit groupname (LOGIN)
+            # is used, and we disable the user_group option.
+            #
+            user_group = uaargs.user_group is None or uaargs.user_group is True
+            uaargs.groupname = uaargs.LOGIN if user_group else uaargs.gid
+            uaargs.groupid = field[3] or uaargs.gid or uaargs.groupname
+
+            if uaargs.groupid and uaargs.gid != uaargs.groupid:
+                newgroup = None
+                if not uaargs.groupid.isdigit():
+                    # We don't have a group number, so we have to add a name
+                    bb.debug(1, "Adding group %s!" % uaargs.groupid)
+                    newgroup = "%s %s" % (' --system' if uaargs.system else '', uaargs.groupid)
+                elif uaargs.groupname and not uaargs.groupname.isdigit():
+                    # We have a group name and a group number to assign it to
+                    bb.debug(1, "Adding group %s (gid %s)!" % (uaargs.groupname, uaargs.groupid))
+                    newgroup = "-g %s %s" % (uaargs.groupid, uaargs.groupname)
+                else:
+                    # We want to add a group, but we don't know it's name... so we can't add the group...
+                    # We have to assume the group has previously been added or we'll fail on the adduser...
+                    # Note: specifying the actual gid is very rare in OE, usually the group name is specified.
+                    bb.warn("%s: Changing gid for login %s to %s, verify configuration files!" % (d.getVar('PN', True), uaargs.LOGIN, uaargs.groupid))
+
+                uaargs.gid = uaargs.groupid
+                uaargs.user_group = None
+                if newgroup:
+                    groupadd = d.getVar("GROUPADD_PARAM_%s" % pkg, True)
+                    if groupadd:
+                        d.setVar("GROUPADD_PARAM_%s" % pkg, "%s; %s" % (groupadd, newgroup))
+                    else:
+                        d.setVar("GROUPADD_PARAM_%s" % pkg, newgroup)
+
+            uaargs.comment = "'%s'" % field[4] if field[4] else uaargs.comment
+            uaargs.home_dir = field[5] or uaargs.home_dir
+            uaargs.shell = field[6] or uaargs.shell
 
             # Should be an error if a specific option is set...
             if d.getVar('USERADD_ERROR_DYNAMIC', True) == '1' and not ((uaargs.uid and uaargs.uid.isdigit()) and uaargs.gid):
@@ -171,7 +191,7 @@ def update_useradd_static_config(d):
 
             newparams.append(newparam)
 
-        return " ;".join(newparams).strip()
+        return ";".join(newparams).strip()
 
     # We parse and rewrite the groupadd components
     def rewrite_groupadd(params):
@@ -200,6 +220,7 @@ def update_useradd_static_config(d):
             return str
 
         newparams = []
+        groups = None
         for param in re.split('''[ \t]*;[ \t]*(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', params):
             param = param.strip()
             if not param:
@@ -210,7 +231,7 @@ def update_useradd_static_config(d):
             except:
                 raise bb.build.FuncFailed("%s: Unable to parse arguments for GROUPADD_PARAM_%s: '%s'" % (d.getVar('PN', True), pkg, param))
 
-            # Need to iterate over layers and open the right file(s)
+            # Read all group files specified in USERADD_GID_TABLES or files/group
             # Use the standard group layout:
             #  groupname:password:group_id:group_members
             #
@@ -219,21 +240,18 @@ def update_useradd_static_config(d):
             #
             # Note: similar to the passwd file, the 'password' filed is ignored
             # Note: group_members is ignored, group members must be configured with the GROUPMEMS_PARAM
-            for conf in get_group_list(d).split()[::-1]:
-                if os.path.exists(conf):
-                    f = open(conf, "r")
-                    for line in f:
-                        if line.startswith('#'):
-                            continue
-                        # Make sure there always are at least four elements in
-                        # the field list. This allows for leaving out trailing
-                        # colons in the group file.
-                        field = list_extend(line.rstrip().split(":"), 4)
-                        if field[0] == gaargs.GROUP and field[2]:
-                            if gaargs.gid and (gaargs.gid != field[2]):
-                                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]))
-                            gaargs.gid = field[2]
-                            break
+            if not groups:
+                groups = merge_files(get_group_list(d), 4)
+
+            if gaargs.GROUP not in groups:
+                continue
+
+            field = groups[gaargs.GROUP]
+
+            if field[2]:
+                if gaargs.gid and (gaargs.gid != field[2]):
+                    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]))
+                gaargs.gid = field[2]
 
             if d.getVar('USERADD_ERROR_DYNAMIC', True) == '1' and not (gaargs.gid and gaargs.gid.isdigit()):
                 #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))
@@ -251,7 +269,7 @@ def update_useradd_static_config(d):
 
             newparams.append(newparam)
 
-        return " ;".join(newparams).strip()
+        return ";".join(newparams).strip()
 
     # Load and process the users and groups, rewriting the adduser/addgroup params
     useradd_packages = d.getVar('USERADD_PACKAGES', True)
Signature · 1 line
2.1.0
#6 lore raw

Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 6 lines · Peter Kjellerstedt

Read and merge the passwd/group files before parsing the user and group definitions. This means they will only be read once per recipe. This solves a problem where if a user was definied in multiple files, it could generate group definitions for groups that should not be created. E.g., if the first passwd file read defines a user as:

Quoted 8 lines

foobar::1234::::

and the second passwd file defines it as:

foobar:::nogroup:The foobar user:/:/bin/sh

then a foobar group would be created even if the user will use the nogroup as its primary group.

One minor thing

meta/classes/useradd-staticids.bbclass def update_useradd_static_config(d): · line 275

Quoted 10 lines
meta/classes/useradd-staticids.bbclass +1 -1
@@ -251,7 +269,7 @@ def update_useradd_static_config(d):
 
             newparams.append(newparam)
 
-        return " ;".join(newparams).strip()
+        return ";".join(newparams).strip()
 
     # Load and process the users and groups, rewriting the adduser/addgroup params
     useradd_packages = d.getVar('USERADD_PACKAGES', True)

The space was required because you could generate a user/group add line that ended with a string. Without the space, you could end up merging two sets of arguments causing a failure condition.

So I think that it should be retained unless there is a specific reason you believe it should be removed.

#7 lore raw

Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 40 lines

-----Original Message-----
From: Mark Hatle [mailto:[email protected]]
Sent: den 4 november 2015 01:33
To: Peter Kjellerstedt; [email protected]
Subject: Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 6 lines · Peter Kjellerstedt

Read and merge the passwd/group files before parsing the user and group definitions. This means they will only be read once per recipe. This solves a problem where if a user was definied in multiple files, it could generate group definitions for groups that should not be created. E.g., if the first passwd file read defines a user as:

Quoted 8 lines

foobar::1234::::

and the second passwd file defines it as:

foobar:::nogroup:The foobar user:/:/bin/sh

then a foobar group would be created even if the user will use the nogroup as its primary group.

One minor thing

meta/classes/useradd-staticids.bbclass def update_useradd_static_config(d): · line 275

Quoted 10 lines
meta/classes/useradd-staticids.bbclass +1 -1
@@ -251,7 +269,7 @@ def update_useradd_static_config(d):
 
             newparams.append(newparam)
 
-        return " ;".join(newparams).strip()
+        return ";".join(newparams).strip()
 
     # Load and process the users and groups, rewriting the adduser/addgroup params
     useradd_packages = d.getVar('USERADD_PACKAGES', True)

The space was required because you could generate a user/group add line that ended with a string. Without the space, you could end up merging two sets of arguments causing a failure condition.

Quoted 2 lines

So I think that it should be retained unless there is a specific reason you believe it should be removed.

I cannot see how that space can make any difference. Each set of useradd/grouppadd options added to newparams has the user/group name at the end of the string. And if that somehow interferes with the semicolon, then the code in useradd.bbclass which simply does "cut -d ';'" to split the useradd/groupadd line would break already.

Actually, now that I think about it, I do wonder why useradd-staticids.bbclass use this advanced variant to split the useradd/groupadd lines:

        for param in re.split('''[ \t]*;[ \t]*(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', params):

when this would do the job just as well:

for param in params.split(';'):

given that that is what useradd.bbclass does. It looks as if tries to support something like --comment "something with a ; in it", but using that would break in useradd.bbclass anyway...

//Peter

#8 lore raw

Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 40 lines · Peter Kjellerstedt
Quoted 40 lines

-----Original Message-----
From: Mark Hatle [mailto:[email protected]]
Sent: den 4 november 2015 01:33
To: Peter Kjellerstedt; [email protected]
Subject: Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 6 lines · Peter Kjellerstedt

Read and merge the passwd/group files before parsing the user and group definitions. This means they will only be read once per recipe. This solves a problem where if a user was definied in multiple files, it could generate group definitions for groups that should not be created. E.g., if the first passwd file read defines a user as:

Quoted 8 lines

foobar::1234::::

and the second passwd file defines it as:

foobar:::nogroup:The foobar user:/:/bin/sh

then a foobar group would be created even if the user will use the nogroup as its primary group.

One minor thing

meta/classes/useradd-staticids.bbclass def update_useradd_static_config(d): · line 275

Quoted 10 lines
meta/classes/useradd-staticids.bbclass +1 -1
@@ -251,7 +269,7 @@ def update_useradd_static_config(d):
 
             newparams.append(newparam)
 
-        return " ;".join(newparams).strip()
+        return ";".join(newparams).strip()
 
     # Load and process the users and groups, rewriting the adduser/addgroup params
     useradd_packages = d.getVar('USERADD_PACKAGES', True)

The space was required because you could generate a user/group add line that ended with a string. Without the space, you could end up merging two sets of arguments causing a failure condition.

Quoted 8 lines
Quoted 2 lines

So I think that it should be retained unless there is a specific reason you believe it should be removed.

I cannot see how that space can make any difference. Each set of useradd/grouppadd options added to newparams has the user/group name at the end of the string. And if that somehow interferes with the semicolon, then the code in useradd.bbclass which simply does "cut -d ';'" to split the useradd/groupadd line would break already.

The contents when originally parsed my be run as arguments to a shell script or as parameters to these functions.

In the shell script world not have a space can confuse the argument parsing into thinking the ; is part of the argument.

You don't have that in the python world with the split behavior.

Quoted 5 lines

Actually, now that I think about it, I do wonder why useradd-staticids.bbclass use this advanced variant to split the useradd/groupadd lines:

        for param in re.split('''[ \t]*;[ \t]*(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', params):

It is perfectly legal to allow a ';' in the middle of a parameter (that allows it), a parameter that is quoted.

Something like:

adduser -c "This user;that user;all users" -d /home/allusers alluser

it's odd, but I've certainly seen people put ';' in the comment before.. and it is legal in other palces, like the home dir and such -- just not advised.

Quoted 7 lines

when this would do the job just as well:

for param in params.split(';'):

given that that is what useradd.bbclass does. It looks as if tries to support something like --comment "something with a ; in it", but using that would break in useradd.bbclass anyway...

Then the useradd class is broken in this case. The --comment processing needs to work, it's just rarely used in the normal case, but very much used in the "lets take a previously generated passwd file and reuse it" case of the adduser-static.

Quoted 2 lines

//Peter

#9 lore raw

Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 59 lines

-----Original Message-----
From: Mark Hatle [mailto:[email protected]]
Sent: den 6 november 2015 21:14
To: Peter Kjellerstedt
Cc: [email protected]
Subject: Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 41 lines · Peter Kjellerstedt
Quoted 41 lines

-----Original Message-----
From: Mark Hatle [mailto:[email protected]]
Sent: den 4 november 2015 01:33
To: Peter Kjellerstedt; [email protected]
Subject: Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 7 lines · Peter Kjellerstedt

Read and merge the passwd/group files before parsing the user and group definitions. This means they will only be read once per recipe. This solves a problem where if a user was definied in multiple files, it could generate group definitions for groups that should not be created. E.g., if the first passwd file read defines a user as:

Quoted 8 lines

foobar::1234::::

and the second passwd file defines it as:

foobar:::nogroup:The foobar user:/:/bin/sh

then a foobar group would be created even if the user will use the nogroup as its primary group.

One minor thing

meta/classes/useradd-staticids.bbclass def update_useradd_static_config(d): · line 275

Quoted 10 lines
meta/classes/useradd-staticids.bbclass +1 -1
@@ -251,7 +269,7 @@ def update_useradd_static_config(d):
 
             newparams.append(newparam)
 
-        return " ;".join(newparams).strip()
+        return ";".join(newparams).strip()
 
     # Load and process the users and groups, rewriting the adduser/addgroup params
     useradd_packages = d.getVar('USERADD_PACKAGES', True)

The space was required because you could generate a user/group add line that ended with a string. Without the space, you could end up merging two sets of arguments causing a failure condition.

Quoted 8 lines
Quoted 2 lines

So I think that it should be retained unless there is a specific reason you believe it should be removed.

I cannot see how that space can make any difference. Each set of useradd/grouppadd options added to newparams has the user/group name at the end of the string. And if that somehow interferes with the semicolon, then the code in useradd.bbclass which simply does "cut -d ';'" to split the useradd/groupadd line would break already.

Quoted 5 lines

The contents when originally parsed my be run as arguments to a shell script or as parameters to these functions.

In the shell script world not have a space can confuse the argument parsing into thinking the ; is part of the argument.

No shell I have heard of (bash, zsh and dash comes to mind) would be affected by the lack of a space before the semicolon. Moreover, this is never actually parsed by a shell (except as part of a variable value). The semicolon is used by useradd.bbclass to split the variables, after which it lets the shell evaluate the part before the semicolon (which will ignore any trailing whitespace).

Quoted 10 lines

You don't have that in the python world with the split behavior.

Quoted 5 lines

Actually, now that I think about it, I do wonder why useradd-staticids.bbclass use this advanced variant to split the useradd/groupadd lines:

        for param in re.split('''[ \t]*;[ \t]*(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', params):

It is perfectly legal to allow a ';' in the middle of a parameter (that allows it), a parameter that is quoted.

Sure, and the code above handles some cases, but definitely not all. E.g., this would not be parsed as intended by useradd-staticids.bbclass:

USERADD_PARAMS_${PN} += "-c Comment\ with\ an\ \'\ in\ it oddcomment; \
-c Other\ odd \'\ comment otheruser"

but it would be handled correctly by useradd.bbclass...

Quoted 7 lines

Something like:

adduser -c "This user;that user;all users" -d /home/allusers alluser

it's odd, but I've certainly seen people put ';' in the comment before.. and it is legal in other palces, like the home dir and such -- just not advised.

It may be legal, but it has never been supported by the adduser.bbclass. And thus it has never worked in practice to take an existing passwd file that contains a semicolon in the comment field and expect it to work as input to adduser-staticids.bbclass.

Moreover, neither adduser.bbclass nor adduser-staticids.bbclass will handle a semicolon correctly in any other field. And let's not get started on other special characters like ", \, $ and > which could wreak havoc on both classes in a correctly crafted passwd file.

Quoted 4 lines
Quoted 4 lines

when this would do the job just as well:

for param in params.split(';'):

Quoted 10 lines
Quoted 3 lines

given that that is what useradd.bbclass does. It looks as if tries to support something like --comment "something with a ; in it", but using that would break in useradd.bbclass anyway...

Then the useradd class is broken in this case. The --comment processing needs to work, it's just rarely used in the normal case, but very much used in the "lets take a previously generated passwd file and reuse it" case of the adduser-static.

Quoted 1 line

//Peter

So, from reading the code in both adduser.bbclass and adduser-staticids.bbclass, having spaces or no spaces before the semicolon in the USERADD_PARAM_${PN} variable cannot make any difference to how the users are created in the end. Thus it should be safe to remove them.

//Peter

#10 lore raw

Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 65 lines · Peter Kjellerstedt
Quoted 59 lines

-----Original Message-----
From: Mark Hatle [mailto:[email protected]]
Sent: den 6 november 2015 21:14
To: Peter Kjellerstedt
Cc: [email protected]
Subject: Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 41 lines · Peter Kjellerstedt
Quoted 41 lines

-----Original Message-----
From: Mark Hatle [mailto:[email protected]]
Sent: den 4 november 2015 01:33
To: Peter Kjellerstedt; [email protected]
Subject: Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 7 lines · Peter Kjellerstedt

Read and merge the passwd/group files before parsing the user and group definitions. This means they will only be read once per recipe. This solves a problem where if a user was definied in multiple files, it could generate group definitions for groups that should not be created. E.g., if the first passwd file read defines a user as:

Quoted 8 lines

foobar::1234::::

and the second passwd file defines it as:

foobar:::nogroup:The foobar user:/:/bin/sh

then a foobar group would be created even if the user will use the nogroup as its primary group.

One minor thing

meta/classes/useradd-staticids.bbclass def update_useradd_static_config(d): · line 275

Quoted 10 lines
meta/classes/useradd-staticids.bbclass +1 -1
@@ -251,7 +269,7 @@ def update_useradd_static_config(d):
 
             newparams.append(newparam)
 
-        return " ;".join(newparams).strip()
+        return ";".join(newparams).strip()
 
     # Load and process the users and groups, rewriting the adduser/addgroup params
     useradd_packages = d.getVar('USERADD_PACKAGES', True)

The space was required because you could generate a user/group add line that ended with a string. Without the space, you could end up merging two sets of arguments causing a failure condition.

Quoted 8 lines
Quoted 2 lines

So I think that it should be retained unless there is a specific reason you believe it should be removed.

I cannot see how that space can make any difference. Each set of useradd/grouppadd options added to newparams has the user/group name at the end of the string. And if that somehow interferes with the semicolon, then the code in useradd.bbclass which simply does "cut -d ';'" to split the useradd/groupadd line would break already.

Quoted 5 lines

The contents when originally parsed my be run as arguments to a shell script or as parameters to these functions.

In the shell script world not have a space can confuse the argument parsing into thinking the ; is part of the argument.

Quoted 6 lines

No shell I have heard of (bash, zsh and dash comes to mind) would be affected by the lack of a space before the semicolon. Moreover, this is never actually parsed by a shell (except as part of a variable value). The semicolon is used by useradd.bbclass to split the variables, after which it lets the shell evaluate the part before the semicolon (which will ignore any trailing whitespace).

I've seen broken shells in the past where you would do something like:

/bin/echo foo;/bin/echo bar

and get: "/bin echo foo;/bin/echo bar" since it treated the middle item as a single command. I'm not saying it wasn't a bug in the shell or system -- just that I've been burned by it in the past and because of this, I try not to rely on it.. (when adding a space solves the issue.)

Quoted 11 lines
Quoted 10 lines

You don't have that in the python world with the split behavior.

Quoted 5 lines

Actually, now that I think about it, I do wonder why useradd-staticids.bbclass use this advanced variant to split the useradd/groupadd lines:

        for param in re.split('''[ \t]*;[ \t]*(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', params):

It is perfectly legal to allow a ';' in the middle of a parameter (that allows it), a parameter that is quoted.

Quoted 7 lines

Sure, and the code above handles some cases, but definitely not all. E.g., this would not be parsed as intended by useradd-staticids.bbclass:

USERADD_PARAMS_${PN} += "-c Comment\ with\ an\ \'\ in\ it oddcomment; \
-c Other\ odd \'\ comment otheruser"

but it would be handled correctly by useradd.bbclass...

In this case, we need to emulate a reasonable set of argument processing. If there is something built into bitbake/oe then we can use it. The re.split though was a good approximation of the common configurations I was seeing at the time. (Specifically quotes parameters for spaces and ;)

Quoted 4 lines
Quoted 4 lines

Something like:

adduser -c "This user;that user;all users" -d /home/allusers alluser

Quoted 8 lines
Quoted 3 lines

it's odd, but I've certainly seen people put ';' in the comment before.. and it is legal in other palces, like the home dir and such -- just not advised.

It may be legal, but it has never been supported by the adduser.bbclass. And thus it has never worked in practice to take an existing passwd file that contains a semicolon in the comment field and expect it to work as input to adduser-staticids.bbclass.

Then that is a bug we should fix. At one time this was working (perhaps not in
OE, but locally?) Since I did have a customer who had both spaces and ';' in
their comment field. (This is how I originally found the problem and needed to figure out a regex that worked in more cases.)

Quoted 4 lines

Moreover, neither adduser.bbclass nor adduser-staticids.bbclass will handle a semicolon correctly in any other field. And let's not get started on other special characters like ", \, $ and > which could wreak havoc on both classes in a correctly crafted passwd file.

I realize there are may corner cases here. We need to try to support the reasonable ones and prevent the others. If that list should be avoided in certain cases -- then we should enhance the system catch things "not to do". But using ';' in the comment is fairly common in some environments.

Quoted 13 lines
Quoted 13 lines
Quoted 7 lines

when this would do the job just as well:

for param in params.split(';'):

given that that is what useradd.bbclass does. It looks as if tries to support something like --comment "something with a ; in it", but using that would break in useradd.bbclass anyway...

Then the useradd class is broken in this case. The --comment processing needs to work, it's just rarely used in the normal case, but very much used in the "lets take a previously generated passwd file and reuse it" case of the adduser-static.

Quoted 7 lines
Quoted 1 line
Quoted 1 line

//Peter

So, from reading the code in both adduser.bbclass and adduser-staticids.bbclass, having spaces or no spaces before the semicolon in the USERADD_PARAM_${PN} variable cannot make any difference to how the users are created in the end. Thus it should be safe to remove them.

The (initial) generated adduser/addgroup/etc command is dumped into the pre/post install script section of the packages. So when the package manager runs it needs to execute the shell script. This is where I've seen the problem of the ';' in the past...

Adduser and adduser-static should be synced to use the same delimitation mechanism. And for things like a ; in the comment, both should equally support it. We've got a mismatch and that is definitely a bug.

--Mark

Quoted 2 lines

//Peter

#11 lore raw

Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 84 lines

-----Original Message-----
From: [email protected] [mailto:[email protected]] On Behalf Of Mark Hatle
Sent: den 10 november 2015 17:07
To: Peter Kjellerstedt
Cc: [email protected]
Subject: Re: [OE-core] [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 66 lines · Peter Kjellerstedt
Quoted 60 lines

-----Original Message-----
From: Mark Hatle [mailto:[email protected]]
Sent: den 6 november 2015 21:14
To: Peter Kjellerstedt
Cc: [email protected]
Subject: Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 44 lines · Peter Kjellerstedt
Quoted 41 lines

-----Original Message-----
From: Mark Hatle [mailto:[email protected]]
Sent: den 4 november 2015 01:33
To: Peter Kjellerstedt; [email protected]
Subject: Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 7 lines · Peter Kjellerstedt

Read and merge the passwd/group files before parsing the user and group definitions. This means they will only be read once per recipe. This solves a problem where if a user was definied in multiple files, it could generate group definitions for groups that should not be created. E.g., if the first passwd file read defines a user as:

Quoted 8 lines

foobar::1234::::

and the second passwd file defines it as:

foobar:::nogroup:The foobar user:/:/bin/sh

then a foobar group would be created even if the user will use the nogroup as its primary group.

One minor thing

meta/classes/useradd-staticids.bbclass def update_useradd_static_config(d): · line 275

Quoted 10 lines
meta/classes/useradd-staticids.bbclass +1 -1
@@ -251,7 +269,7 @@ def update_useradd_static_config(d):
 
             newparams.append(newparam)
 
-        return " ;".join(newparams).strip()
+        return ";".join(newparams).strip()
 
     # Load and process the users and groups, rewriting the adduser/addgroup params
     useradd_packages = d.getVar('USERADD_PACKAGES', True)

The space was required because you could generate a user/group add line that ended with a string. Without the space, you could end up merging two sets of arguments causing a failure condition.

Quoted 2 lines

So I think that it should be retained unless there is a specific reason you believe it should be removed.

Quoted 6 lines

I cannot see how that space can make any difference. Each set of useradd/grouppadd options added to newparams has the user/group name at the end of the string. And if that somehow interferes with the semicolon, then the code in useradd.bbclass which simply does "cut -d ';'" to split the useradd/groupadd line would break already.

Quoted 5 lines

The contents when originally parsed my be run as arguments to a shell script or as parameters to these functions.

In the shell script world not have a space can confuse the argument parsing into thinking the ; is part of the argument.

Quoted 6 lines

No shell I have heard of (bash, zsh and dash comes to mind) would be affected by the lack of a space before the semicolon. Moreover, this is never actually parsed by a shell (except as part of a variable value). The semicolon is used by useradd.bbclass to split the variables, after which it lets the shell evaluate the part before the semicolon (which will ignore any trailing whitespace).

Quoted 8 lines

I've seen broken shells in the past where you would do something like:

/bin/echo foo;/bin/echo bar

and get: "/bin echo foo;/bin/echo bar" since it treated the middle item as a single command. I'm not saying it wasn't a bug in the shell or system -- just that I've been burned by it in the past and because of this, I try not to rely on it.. (when adding a space solves the issue.)

Ok, sounds weird, but I will take your word for it.

Quoted 18 lines
Quoted 18 lines
Quoted 10 lines

You don't have that in the python world with the split behavior.

Quoted 5 lines

Actually, now that I think about it, I do wonder why useradd-staticids.bbclass use this advanced variant to split the useradd/groupadd lines:

        for param in re.split('''[ \t]*;[ \t]*(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', params):

It is perfectly legal to allow a ';' in the middle of a parameter (that allows it), a parameter that is quoted.

Sure, and the code above handles some cases, but definitely not all. E.g., this would not be parsed as intended by useradd- staticids.bbclass:

USERADD_PARAMS_${PN} += "-c Comment\ with\ an\ \'\ in\ it oddcomment; \
-c Other\ odd \'\ comment otheruser"

Quoted 7 lines
Quoted 1 line

but it would be handled correctly by useradd.bbclass...

In this case, we need to emulate a reasonable set of argument processing. If there is something built into bitbake/oe then we can use it. The re.split though was a good approximation of the common configurations I was seeing at the time. (Specifically quotes parameters for spaces and ;)

Normally I would suggest shlex.split(). It is already used by both BitBake and OE-Core. Unfortunately, it cannot be used in this case as it cannot distinguish between an escaped/quoted semicolon and one that is not escaped/quoted. This is because it is designed to split one command line, not multiple lines.

So the split of multiple commands would probably still have to be done using a regular expression, extended to support escaping.

shlex.split() can be used for the second split though (where the command is fed to the parser).

We would also need the opposite to construct a command line with all options properly quoted. Unfortunately, shlex.quote() was not added until Python 3.3. However, there is an unofficial pipes.quote() that is already used by OE-Core, so I assume it is ok to use.

Quoted 51 lines
Quoted 4 lines
Quoted 4 lines

Something like:

adduser -c "This user;that user;all users" -d /home/allusers alluser

Quoted 8 lines
Quoted 3 lines

it's odd, but I've certainly seen people put ';' in the comment before.. and it is legal in other palces, like the home dir and such -- just not advised.

It may be legal, but it has never been supported by the adduser.bbclass. And thus it has never worked in practice to take an existing passwd file that contains a semicolon in the comment field and expect it to work as input to adduser-staticids.bbclass.

Then that is a bug we should fix. At one time this was working
(perhaps not in OE, but locally?) Since I did have a customer who
had both spaces and ';' in their comment field. (This is how I originally found the problem and needed to figure out a regex that worked in more cases.)

Quoted 4 lines

Moreover, neither adduser.bbclass nor adduser-staticids.bbclass will handle a semicolon correctly in any other field. And let's not get started on other special characters like ", \, $ and > which could wreak havoc on both classes in a correctly crafted passwd file.

I realize there are may corner cases here. We need to try to support the reasonable ones and prevent the others. If that list should be avoided in certain cases -- then we should enhance the system catch things "not to do". But using ';' in the comment is fairly common in some environments.

Quoted 13 lines
Quoted 13 lines
Quoted 7 lines

when this would do the job just as well:

for param in params.split(';'):

given that that is what useradd.bbclass does. It looks as if tries to support something like --comment "something with a ; in it", but using that would break in useradd.bbclass anyway...

Then the useradd class is broken in this case. The --comment processing needs to work, it's just rarely used in the normal case, but very much used in the "lets take a previously generated passwd file and reuse it" case of the adduser-static.

Quoted 7 lines
Quoted 1 line
Quoted 1 line

//Peter

So, from reading the code in both adduser.bbclass and adduser-staticids.bbclass, having spaces or no spaces before the semicolon in the USERADD_PARAM_${PN} variable cannot make any difference to how the users are created in the end. Thus it should be safe to remove them.

Quoted 8 lines

The (initial) generated adduser/addgroup/etc command is dumped into the pre/post install script section of the packages. So when the package manager runs it needs to execute the shell script. This is where I've seen the problem of the ';' in the past...

Adduser and adduser-static should be synced to use the same delimitation mechanism. And for things like a ; in the comment, both should equally support it. We've got a mismatch and that is definitely a bug.

I agree that the correct thing to do is to make them support the same mechanism. However, this would require quite some more work, especially with the useradd.bbclass, and as it does not affect the changes in my patches, do you think the patches can be accepted as they are, and we can work on improving the parsing afterwards?

Quoted 3 lines

--Mark

Quoted 1 line

//Peter

//Peter

#12 lore raw

Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

*ping*

//Peter

Quoted 248 lines

-----Original Message-----
From: [email protected] [mailto:[email protected]] On Behalf Of Peter Kjellerstedt
Sent: den 13 november 2015 13:52
To: Mark Hatle
Cc: [email protected]
Subject: Re: [OE-core] [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 3 lines

-----Original Message-----
From: [email protected] [mailto:[email protected]] On Behalf

Of

Quoted 7 lines

Mark Hatle
Sent: den 10 november 2015 17:07
To: Peter Kjellerstedt
Cc: [email protected]
Subject: Re: [OE-core] [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 19 lines
Quoted 18 lines · Peter Kjellerstedt
Quoted 18 lines

-----Original Message-----
From: Mark Hatle [mailto:[email protected]]
Sent: den 6 november 2015 21:14
To: Peter Kjellerstedt
Cc: [email protected]
Subject: Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 9 lines · Peter Kjellerstedt
Quoted 9 lines

-----Original Message-----
From: Mark Hatle [mailto:[email protected]]
Sent: den 4 november 2015 01:33
To: Peter Kjellerstedt; [email protected]
Subject: Re: [PATCH 5/5] useradd-staticids.bbclass: Read passwd/group files before parsing

Quoted 1 line · Peter Kjellerstedt

Read and merge the passwd/group files before parsing the user

and

Quoted 17 lines
Quoted 17 lines
Quoted 17 lines
Quoted 17 lines
Quoted 17 lines
Quoted 6 lines

group definitions. This means they will only be read once per recipe. This solves a problem where if a user was definied in multiple files, it could generate group definitions for groups that should not be created. E.g., if the first passwd file read defines a user as:

Quoted 8 lines

foobar::1234::::

and the second passwd file defines it as:

foobar:::nogroup:The foobar user:/:/bin/sh

then a foobar group would be created even if the user will use the nogroup as its primary group.

One minor thing

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

Review def update_useradd_static_config(d): · line 274

Quoted 8 lines
(quoted diff) +1 -1
@@ -251,7 +269,7 @@ def update_useradd_static_config(d):
 
             newparams.append(newparam)
 
-        return " ;".join(newparams).strip()
+        return ";".join(newparams).strip()
 
     # Load and process the users and groups, rewriting the

adduser/addgroup params

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

Review def update_useradd_static_config(d): · line 275

Quoted 2 lines
(quoted diff) +0 -0
     useradd_packages = d.getVar('USERADD_PACKAGES', True)

The space was required because you could generate a user/group add line that ended with a string. Without the space, you could end up merging two sets of arguments causing a failure

condition.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 3 lines

So I think that it should be retained unless there is a specific reason you believe it should be removed.

I cannot see how that space can make any difference. Each set of useradd/grouppadd options added to newparams has the user/group name at the end of the string. And if that somehow interferes

with

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 3 lines

the semicolon, then the code in useradd.bbclass which simply does "cut -d ';'" to split the useradd/groupadd line would break already.

The contents when originally parsed my be run as arguments to a shell script or as parameters to these functions.

In the shell script world not have a space can confuse the

argument

Quoted 3 lines
Quoted 3 lines
Quoted 1 line

parsing into thinking the ; is part of the argument.

No shell I have heard of (bash, zsh and dash comes to mind) would

be

Quoted 1 line
Quoted 1 line

affected by the lack of a space before the semicolon. Moreover,

this

Quoted 6 lines
Quoted 4 lines

is never actually parsed by a shell (except as part of a variable value). The semicolon is used by useradd.bbclass to split the variables, after which it lets the shell evaluate the part before the semicolon (which will ignore any trailing whitespace).

I've seen broken shells in the past where you would do something

like:

Quoted 5 lines

/bin/echo foo;/bin/echo bar

and get: "/bin echo foo;/bin/echo bar" since it treated the middle item as a single command. I'm not saying it wasn't a bug in the

shell

Quoted 2 lines

or system -- just that I've been burned by it in the past and because of this, I try not to rely on it.. (when adding a space solves the

issue.)

Ok, sounds weird, but I will take your word for it.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

You don't have that in the python world with the split behavior.

Quoted 5 lines

Actually, now that I think about it, I do wonder why useradd-staticids.bbclass use this advanced variant to split the useradd/groupadd lines:

        for param in re.split('''[ \t]*;[

\t]*(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', params):

Quoted 5 lines
Quoted 5 lines
Quoted 3 lines

It is perfectly legal to allow a ';' in the middle of a parameter (that allows it), a parameter that is quoted.

Sure, and the code above handles some cases, but definitely not

all.

Quoted 4 lines
Quoted 4 lines

E.g., this would not be parsed as intended by useradd- staticids.bbclass:

USERADD_PARAMS_${PN} += "-c Comment\ with\ an\ \'\ in\ it

oddcomment; \

Quoted 9 lines
Quoted 3 lines

-c Other\ odd \'\ comment otheruser"

but it would be handled correctly by useradd.bbclass...

In this case, we need to emulate a reasonable set of argument processing. If there is something built into bitbake/oe then we can use it. The re.split though was a good approximation of the common configurations I was seeing at the time. (Specifically quotes parameters for spaces and ;)

Normally I would suggest shlex.split(). It is already used by both BitBake and OE-Core. Unfortunately, it cannot be used in this case as it cannot distinguish between an escaped/quoted semicolon and one that is not escaped/quoted. This is because it is designed to split one command line, not multiple lines.

So the split of multiple commands would probably still have to be done using a regular expression, extended to support escaping.

shlex.split() can be used for the second split though (where the command is fed to the parser).

We would also need the opposite to construct a command line with all options properly quoted. Unfortunately, shlex.quote() was not added until Python 3.3. However, there is an unofficial pipes.quote() that is already used by OE-Core, so I assume it is ok to use.

Quoted 3 lines
Quoted 3 lines
Quoted 3 lines

Something like:

adduser -c "This user;that user;all users" -d /home/allusers

alluser

Quoted 7 lines
Quoted 7 lines
Quoted 4 lines

it's odd, but I've certainly seen people put ';' in the comment before.. and it is legal in other palces, like the home dir and such -- just not advised.

It may be legal, but it has never been supported by the adduser.bbclass. And thus it has never worked in practice to take

an

Quoted 10 lines
Quoted 2 lines

existing passwd file that contains a semicolon in the comment field and expect it to work as input to adduser-staticids.bbclass.

Then that is a bug we should fix. At one time this was working
(perhaps not in OE, but locally?) Since I did have a customer who
had both spaces and ';' in their comment field. (This is how I originally found the problem and needed to figure out a regex that worked in more cases.)

Quoted 1 line

Moreover, neither adduser.bbclass nor adduser-staticids.bbclass

will

Quoted 4 lines
Quoted 3 lines

handle a semicolon correctly in any other field. And let's not get started on other special characters like ", \, $ and > which could wreak havoc on both classes in a correctly crafted passwd file.

Quoted 11 lines

I realize there are may corner cases here. We need to try to support the reasonable ones and prevent the others. If that list should be avoided in certain cases -- then we should enhance the system catch things "not to do". But using ';' in the comment is fairly common in some environments.

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

when this would do the job just as well:

for param in params.split(';'):

given that that is what useradd.bbclass does. It looks as if

tries

Quoted 1 line
Quoted 1 line
Quoted 1 line
Quoted 1 line

to support something like --comment "something with a ; in it",

but

Quoted 9 lines
Quoted 9 lines
Quoted 8 lines
Quoted 1 line

using that would break in useradd.bbclass anyway...

Then the useradd class is broken in this case. The --comment processing needs to work, it's just rarely used in the normal case, but very much used in the "lets take a previously generated passwd file and reuse it" case of the adduser-static.

Quoted 1 line

//Peter

Quoted 7 lines
Quoted 5 lines

So, from reading the code in both adduser.bbclass and adduser-staticids.bbclass, having spaces or no spaces before the semicolon in the USERADD_PARAM_${PN} variable cannot make any difference to how the users are created in the end. Thus it should be safe to remove them.

The (initial) generated adduser/addgroup/etc command is dumped into

the

Quoted 2 lines

pre/post install script section of the packages. So when the package manager runs it needs to execute the shell script. This is where

I've

Quoted 3 lines

seen the problem of the ';' in the past...

Adduser and adduser-static should be synced to use the same

delimitation

Quoted 1 line

mechanism. And for things like a ; in the comment, both should

equally

Quoted 1 line

support it. We've got a mismatch and that is definitely a bug.

I agree that the correct thing to do is to make them support the same mechanism. However, this would require quite some more work, especially with the useradd.bbclass, and as it does not affect the changes in my patches, do you think the patches can be accepted as they are, and we can work on improving the parsing afterwards?

Quoted 3 lines

--Mark

Quoted 1 line

//Peter

//Peter

--
_______________________________________________
Openembedded-core mailing list
[email protected]
http://lists.openembedded.org/mailman/listinfo/openembedded-core

Acked-by on the v1 series
#13 lore raw
In reply to Peter Kjellerstedt

I looked over this series (I have not tried it, but) everything looks ok to me.
I did make one comment on a minor hunk -- but otherwise I don't see any issues.

The python style police might have some further comments.

Quoted 66 lines · Peter Kjellerstedt

This series of patches aims to improve useradd-staticids.bbclass.

We are currently using useradd-staticids.bbclass to make sure all users and groups have well defined IDs. So far we have had the definitions of the users both in the recipes and in the passwd file used by useradd-staticids.bbclass. Since we have a huge number of recipes that create users, having to duplicate the definitions all over the place has turned out to be a burden we should be able to avoid.

So the current plan for us is to have one passwd file per layer with the definitions of all users that layer needs. These definitions do not include the static IDs for the users. Instead the static IDs for the users are specified in a distro specific passwd-static file. There is also a distro specific group-static file for the group IDs. With that in place it should be enough to define a user as:

USERADD_PARAM_${PN} = "--system foobar"

in a recipe and let useradd-staticids.bbclass handle the specifics for how that user should be defined.

The above worked fine for all users that had a primary group with the same name as the user. However, it turned out that for users that wanted some other primary group, specifying it in the passwd file was not enough. We still had to add --gid <some group> in the recipe where <some group> had to match what was specified in the passwd file. This was less than optimal, and somewhat defeated the setup.

It also turned out that for users with a primary group that does not match the user name, useradd-staticids.bbclass would still add the creation of a group with the same name as the user (when it parsed the passwd-static file) and the add another creation of the correct group (when it parsed the passwd file).

So after spending quite a lot of time on trying to decode how rewrite_useradd() calculated the --gid option, I came up with this series of changes that should correct the problems described above and make the code easier to understand while (hopefully) maintaining compatibility with the old code.

I fully understand that this is very late for Jethro and do not really expect it to make it into 2.0.0, but if at all possible I hope it can make it since that would make my life much easier. :)

//Peter

The following changes since commit fc45deac89ef63ca1c44e763c38ced7dfd72cbe1:

build-appliance-image: Update to jethro head revision (2015-11-03 14:03:03 +0000)

are available in the git repository at:

git://git.yoctoproject.org/poky-contrib pkj/useradd_improvements
http://git.yoctoproject.org/cgit.cgi/poky-contrib/log/?h=pkj/useradd_improvements

Peter Kjellerstedt (5):
useradd-staticids.bbclass: Treat mutually exclusive options as such useradd-staticids.bbclass: Make --no-user-group have effect useradd-staticids.bbclass: Simplify some logic useradd-staticids.bbclass: Simplify the logic for when to add groups useradd-staticids.bbclass: Read passwd/group files before parsing

 meta/classes/useradd-staticids.bbclass | 192 ++++++++++++++++++---------------
 1 file changed, 103 insertions(+), 89 deletions(-)