Skip to contentSkip to conversation

Pygrub security enhancements and bugfixes

PATCH In review Alejandro Vallejo 3 participants 22 messages Nov 6, 2023 – Nov 23, 2023

lore
Share & tools
lore
#0 lore raw

cover Pygrub security enhancements and bugfixes

A few extra bugfixes and security enhancements for pygrub.

The biggest security enhacement is the removal of filesystem permissions from the depriv thread of pygrub. This is possible on newer versions of e2fsprogs, as it has an interface to consume file descriptors rather than file paths.

Bug fixes
=========

Patch 1: Properly confines the mount namespace in Linux systems and
corrects an incorrect statement about older Linux kernels being buggy with them. With this patch, mounts done inside the namespace disappear altogether after the last process is killed.
Patch 2: Fixes a bug preventing setting the LIMIT_FSIZE override

Security enhancements
=====================

Patch 3: Limits the amount of memory pygrub can chew
Patch 4: Tweaks libfsimage to support a new interface ( fdopen() ) which
allows passing file descriptors rather than paths
Patch 5: Modifies the python bindings to grant access to the new interface Patch 6: Modifies pygrub to open every required file before depriv.

Alejandro Vallejo (6):
tools/pygrub: Set mount propagation to private recursively tools/pygrub: Fix bug in LIMIT_FSIZE env variable override tools/pygrub: Restrict depriv operation with RLIMIT_AS tools/libfsimage: Add an fdopen() interface to libfsimage tools/pygrub: Expose libfsimage's fdopen() to python tools/pygrub: Hook libfsimage's fdopen() to pygrub

 docs/man/xl.cfg.5.pod.in                    |   6 +-
 tools/libfsimage/common/fsimage.c           |  42 ++++++--
 tools/libfsimage/common/fsimage_grub.c      |   2 +-
 tools/libfsimage/common/fsimage_plugin.c    |   4 +-
 tools/libfsimage/common/fsimage_priv.h      |   3 +-
 tools/libfsimage/common/mapfile-GNU         |   2 +
 tools/libfsimage/common/mapfile-SunOS       |   2 +
 tools/libfsimage/common/xenfsimage.h        |   3 +
 tools/libfsimage/common/xenfsimage_plugin.h |   2 +-
 tools/libfsimage/ext2fs-lib/ext2fs-lib.c    |  14 ++-
 tools/pygrub/src/ExtLinuxConf.py            |  20 ++--
 tools/pygrub/src/GrubConf.py                |  29 ++---
 tools/pygrub/src/LiloConf.py                |  20 ++--
 tools/pygrub/src/fsimage/fsimage.c          |  33 ++++++
 tools/pygrub/src/pygrub                     | 113 +++++++-------------
 15 files changed, 173 insertions(+), 122 deletions(-)
Signature · 1 line
2.34.1
#1 lore raw

PATCH 1/6 tools/pygrub: Set mount propagation to private recursively

This is important in order for every mount done inside a mount namespace to go away after the namespace itself goes away. The comment referring to unreliability in Linux 4.19 was just wrong.

This patch sets the story straight and makes the depriv pygrub a bit more confined should a layer of the onion be vulnerable.

---
 tools/pygrub/src/pygrub | 14 +++++++++-----
 1 file changed, 9 insertions(+), 5 deletions(-)
tools/pygrub/src/pygrub +9 -5
index 541e562327..08540ad288 100755
@@ -55,6 +55,12 @@ def unshare(flags):
     if unshare(flags) < 0:
         raise OSError(ctypes.get_errno(), os.strerror(ctypes.get_errno()))
 
+    # It's very typical for systemd to mount / with MS_SHARED. That means
+    # any events in the new namespace get propagated back to the parent.
+    #
+    # Undo it so that every mount done in the NS stay confined within it.
+    subprocess.check_output(["mount", "--make-rprivate", "/"])
+
 def bind_mount(src, dst, options):
     open(dst, "a").close() # touch
 
@@ -113,11 +119,9 @@ def depriv(output_directory, output, device, uid, path_kernel, path_ramdisk):
             if rc != 0 or os.path.getsize(path) == 0:
                 os.unlink(path)
 
-        # Normally, unshare(CLONE_NEWNS) will ensure this is not required.
-        # However, this syscall doesn't exist in *BSD systems and doesn't
-        # auto-unmount everything on older Linux kernels (At least as of
-        # Linux 4.19, but it seems fixed in 5.15). Either way,
-        # recursively unmount everything if needed. Quietly.
+        # Unshare(CLONE_NEWNS) ensures this is not required, but that's not
+        # present on *BSD, so recursively unmount everything if needed.
+        # Quietly.
         with open('/dev/null', 'w') as devnull:
             subprocess.call(["umount", "-f", chroot + device_path],
                             stdout=devnull, stderr=devnull)
Signature · 1 line
2.34.1
Acked-by on v1 1/6
#2 lore raw

Re: [PATCH 1/6] tools/pygrub: Set mount propagation to private recursively

Quoted 8 lines · Alejandro Vallejo

This is important in order for every mount done inside a mount namespace to go away after the namespace itself goes away. The comment referring to unreliability in Linux 4.19 was just wrong.

This patch sets the story straight and makes the depriv pygrub a bit more confined should a layer of the onion be vulnerable.

#3 lore raw

Re: [PATCH 1/6] tools/pygrub: Set mount propagation to private recursively

Quoted 10 lines · Andrew Cooper
Quoted 8 lines · Alejandro Vallejo

This is important in order for every mount done inside a mount namespace to go away after the namespace itself goes away. The comment referring to unreliability in Linux 4.19 was just wrong.

This patch sets the story straight and makes the depriv pygrub a bit more confined should a layer of the onion be vulnerable.

Sorry, wants

Fixes e0342ae5556f ("tools/pygrub: Deprivilege pygrub")

too.  Will fix on commit.

~Andrew

#4 lore raw

Re: [PATCH 1/6] tools/pygrub: Set mount propagation to private recursively

Quoted 12 lines · Andrew Cooper
Quoted 10 lines · Andrew Cooper
Quoted 8 lines · Alejandro Vallejo

This is important in order for every mount done inside a mount namespace to go away after the namespace itself goes away. The comment referring to unreliability in Linux 4.19 was just wrong.

This patch sets the story straight and makes the depriv pygrub a bit more confined should a layer of the onion be vulnerable.

Quoted 7 lines

Sorry, wants

Fixes e0342ae5556f ("tools/pygrub: Deprivilege pygrub")

too.  Will fix on commit.

~Andrew

Sounds good.

Cheers,
Alejandro

#5 lore raw

PATCH 2/6 tools/pygrub: Fix bug in LIMIT_FSIZE env variable override

In reply to Alejandro Vallejo

The env variable must be interpreted as an integer. As it is, the override logic simply causes an exception.

---
 tools/pygrub/src/pygrub | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/pygrub/src/pygrub +1 -1
index 08540ad288..327cf51774 100755
@@ -89,7 +89,7 @@ def downgrade_rlimits():
     # write permissions are bound.
     fsize = LIMIT_FSIZE
     if "PYGRUB_MAX_FILE_SIZE_MB" in os.environ.keys():
-        fsize = os.environ["PYGRUB_MAX_FILE_SIZE_MB"] << 20
+        fsize = int(os.environ["PYGRUB_MAX_FILE_SIZE_MB"]) << 20
 
     resource.setrlimit(resource.RLIMIT_FSIZE, (fsize, fsize))
 
Signature · 1 line
2.34.1
#6 lore raw

PATCH 1/1 tools/pygrub: Fix expression before it's copied elsewhere

This has an identical meaning, and is the more pythonic way of writing it.

---
CC: Wei Liu <[email protected]>
CC: Anthony PERARD <[email protected]>
CC: Alejandro Vallejo <[email protected]>

---
 tools/pygrub/src/pygrub | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/pygrub/src/pygrub +1 -1
index 327cf51774fc..2c06684d6532 100755
@@ -88,7 +88,7 @@ def downgrade_rlimits():
     # filesystem we set RLIMIT_FSIZE to a high bound, so that the file
     # write permissions are bound.
     fsize = LIMIT_FSIZE
-    if "PYGRUB_MAX_FILE_SIZE_MB" in os.environ.keys():
+    if "PYGRUB_MAX_FILE_SIZE_MB" in os.environ:
         fsize = int(os.environ["PYGRUB_MAX_FILE_SIZE_MB"]) << 20
 
     resource.setrlimit(resource.RLIMIT_FSIZE, (fsize, fsize))
Signature · 1 line
2.30.2
#7 lore raw

Re: [PATCH v2.5/6] tools/pygrub: Fix expression before it's copied elsewhere

Quoted 16 lines · Andrew Cooper

This has an identical meaning, and is the more pythonic way of writing it.

---
CC: Wei Liu <[email protected]>
CC: Anthony PERARD <[email protected]>
CC: Alejandro Vallejo <[email protected]>

---
  tools/pygrub/src/pygrub | 2 +-
  1 file changed, 1 insertion(+), 1 deletion(-)
tools/pygrub/src/pygrub +0 -0
index 327cf51774fc..2c06684d6532 100755

tools/pygrub/src/pygrub def downgrade_rlimits(): · line 94

Quoted 8 lines
tools/pygrub/src/pygrub +1 -1
@@ -88,7 +88,7 @@ def downgrade_rlimits():
      # filesystem we set RLIMIT_FSIZE to a high bound, so that the file
      # write permissions are bound.
      fsize = LIMIT_FSIZE
-    if "PYGRUB_MAX_FILE_SIZE_MB" in os.environ.keys():
+    if "PYGRUB_MAX_FILE_SIZE_MB" in os.environ:
          fsize = int(os.environ["PYGRUB_MAX_FILE_SIZE_MB"]) << 20
 
      resource.setrlimit(resource.RLIMIT_FSIZE, (fsize, fsize))

LGTM.

Cheers,
Alejandro

#8 lore raw

Re: [PATCH v2.5/6] tools/pygrub: Fix expression before it's copied elsewhere

Quoted 13 lines · Alejandro Vallejo
Quoted 12 lines · Andrew Cooper

This has an identical meaning, and is the more pythonic way of writing it.

---
CC: Wei Liu <[email protected]>
CC: Anthony PERARD <[email protected]>
CC: Alejandro Vallejo <[email protected]>
---
  tools/pygrub/src/pygrub | 2 +-

  1 file changed, 1 insertion(+), 1 deletion(-)
Quoted 14 lines
Quoted 7 lines
tools/pygrub/src/pygrub +0 -0
index 327cf51774fc..2c06684d6532 100755
@@ -88,7 +88,7 @@ def downgrade_rlimits():
       # filesystem we set RLIMIT_FSIZE to a high bound, so that the file
       # write permissions are bound.
Quoted 5 lines

      fsize = LIMIT_FSIZE
-    if "PYGRUB_MAX_FILE_SIZE_MB" in os.environ.keys():
+    if "PYGRUB_MAX_FILE_SIZE_MB" in os.environ:
          fsize = int(os.environ["PYGRUB_MAX_FILE_SIZE_MB"]) << 20 resource.setrlimit(resource.RLIMIT_FSIZE, (fsize, fsize))

LGTM.

Can I take that as a R-by then?

~Andrew

author Reviewed-by
#9 lore raw

Re: [PATCH v2.5/6] tools/pygrub: Fix expression before it's copied elsewhere

In reply to Alejandro Vallejo
Quoted 27 lines · Alejandro Vallejo
Quoted 18 lines · Andrew Cooper

This has an identical meaning, and is the more pythonic way of writing it.

---
CC: Wei Liu <[email protected]>
CC: Anthony PERARD <[email protected]>
CC: Alejandro Vallejo <[email protected]>
---
  tools/pygrub/src/pygrub | 2 +-

  1 file changed, 1 insertion(+), 1 deletion(-)
tools/pygrub/src/pygrub +0 -0
index 327cf51774fc..2c06684d6532 100755
@@ -88,7 +88,7 @@ def downgrade_rlimits():
       # filesystem we set RLIMIT_FSIZE to a high bound, so that the file
       # write permissions are bound.
Quoted 5 lines

      fsize = LIMIT_FSIZE
-    if "PYGRUB_MAX_FILE_SIZE_MB" in os.environ.keys():
+    if "PYGRUB_MAX_FILE_SIZE_MB" in os.environ:
          fsize = int(os.environ["PYGRUB_MAX_FILE_SIZE_MB"]) << 20 resource.setrlimit(resource.RLIMIT_FSIZE, (fsize, fsize))

LGTM.

Quoted 2 lines

Cheers,
Alejandro

... and

Cheers,
Alejandro

#10 lore raw

Re: [PATCH 2/6] tools/pygrub: Fix bug in LIMIT_FSIZE env variable override

In reply to Alejandro Vallejo
Quoted 2 lines · Alejandro Vallejo

The env variable must be interpreted as an integer. As it is, the override logic simply causes an exception.

Fixes e0342ae5556f ("tools/pygrub: Deprivilege pygrub")
Quoted 10 lines
---
 tools/pygrub/src/pygrub | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/pygrub/src/pygrub +0 -0
index 08540ad288..327cf51774 100755

tools/pygrub/src/pygrub def downgrade_rlimits(): · line 95

Quoted 8 lines
tools/pygrub/src/pygrub +1 -1
@@ -89,7 +89,7 @@ def downgrade_rlimits():
     # write permissions are bound.
     fsize = LIMIT_FSIZE
     if "PYGRUB_MAX_FILE_SIZE_MB" in os.environ.keys():
-        fsize = os.environ["PYGRUB_MAX_FILE_SIZE_MB"] << 20
+        fsize = int(os.environ["PYGRUB_MAX_FILE_SIZE_MB"]) << 20
 
     resource.setrlimit(resource.RLIMIT_FSIZE, (fsize, fsize))
 

This change on its own is correct, so Acked-by: Andrew Cooper <[email protected]>

However, there's a bug/misfeature which you've copied in patch 3, so I've inserted a patch 2.5 to try and fix it in a nice order.  It's probably a little rude to merge the pythonic-fix into this functional fix.

~Andrew

#11 lore raw

PATCH 3/6 tools/pygrub: Restrict depriv operation with RLIMIT_AS

In reply to Alejandro Vallejo

Prevents the depriv pygrub from consuming more than a fixed amount of memory.

---
 tools/pygrub/src/pygrub | 10 ++++++++++
 1 file changed, 10 insertions(+)
tools/pygrub/src/pygrub +10 -0
index 327cf51774..b96bdfd849 100755
@@ -39,6 +39,11 @@ SECTOR_SIZE = 512
 # pygrub
 LIMIT_FSIZE = 128 << 20
 
+# Unless provided through the env variable PYGRUB_MAX_RAM_USAGE_MB, then
+# this is the maximum amount of memory allowed to be used by the depriv
+# pygrub.
+LIMIT_AS = 2 * LIMIT_FSIZE
+
 CLONE_NEWNS = 0x00020000 # mount namespace
 CLONE_NEWNET = 0x40000000 # network namespace
 CLONE_NEWIPC = 0x08000000 # IPC namespace
@@ -75,6 +80,11 @@ def downgrade_rlimits():
     resource.setrlimit(resource.RLIMIT_CORE,     (0, 0))
     resource.setrlimit(resource.RLIMIT_MEMLOCK,  (0, 0))
 
+    max_ram_usage = LIMIT_AS
+    if "PYGRUB_MAX_RAM_USAGE_MB" in os.environ.keys():
+        max_ram_usage = int(os.environ["PYGRUB_MAX_RAM_USAGE_MB"]) << 20
+    resource.setrlimit(resource.RLIMIT_AS,  (max_ram_usage, max_ram_usage))
+
     # py2's resource module doesn't know about resource.RLIMIT_MSGQUEUE
     #
     # TODO: Use resource.RLIMIT_MSGQUEUE after python2 is deprecated
Signature · 1 line
2.34.1
Acked-by on v1 3/6
#12 lore raw

Re: [PATCH 3/6] tools/pygrub: Restrict depriv operation with RLIMIT_AS

tools/pygrub/src/pygrub def downgrade_rlimits(): · line 84

Quoted 10 lines · Alejandro Vallejo
tools/pygrub/src/pygrub +2 -0
index 327cf51774..b96bdfd849 100755
@@ -75,6 +80,11 @@ def downgrade_rlimits():
     resource.setrlimit(resource.RLIMIT_CORE,     (0, 0))
     resource.setrlimit(resource.RLIMIT_MEMLOCK,  (0, 0))
 
+    max_ram_usage = LIMIT_AS
+    if "PYGRUB_MAX_RAM_USAGE_MB" in os.environ.keys():

With the .keys() dropped as per patch 2.5/6,

Happy to do this on commit.

#13 lore raw

Re: [PATCH 3/6] tools/pygrub: Restrict depriv operation with RLIMIT_AS

Quoted 9 lines · Andrew Cooper
Quoted 8 lines · Alejandro Vallejo
tools/pygrub/src/pygrub +0 -0
index 327cf51774..b96bdfd849 100755
@@ -75,6 +80,11 @@ def downgrade_rlimits():
      resource.setrlimit(resource.RLIMIT_CORE,     (0, 0))
      resource.setrlimit(resource.RLIMIT_MEMLOCK,  (0, 0))
 
Quoted 8 lines

tools/pygrub/src/pygrub def downgrade_rlimits(): · line 84

Quoted 2 lines
tools/pygrub/src/pygrub +2 -0
+    max_ram_usage = LIMIT_AS
+    if "PYGRUB_MAX_RAM_USAGE_MB" in os.environ.keys():

With the .keys() dropped as per patch 2.5/6,

Happy to do this on commit.

Sure

Cheers,
Alejandro

#14 lore raw

PATCH 4/6 tools/libfsimage: Add an fdopen() interface to libfsimage

In reply to Alejandro Vallejo

Currently libfsimage requires taking a path so it can open a file itself. This needs not to be the case and is, as far as I've gathered, a side effect of the ext2fs-lib's optional dependency because it couldn't cope directly with FDs until e2fsprogs-1.43.2. That was 2016, so it's safe to make use of this feature in order to improve the security stance of pygrub.

https://github.com/tytso/e2fsprogs/commit/4ccf9e4fe165cfa966c8af0f3d310230aa5c3a1e

This patch modifies the internals of libfsimage to:
* Expose a new fdopen() function
* Mirrors open(), except we pass an fd rather than a path
* Refactor open() to use fdopen() internally
* Rewire libfsimage so paths are not passed around
* Rewire ext2fs-lib shim to use unixfd_io_manager

Note that while fdopen() takes an FD, close() will still close it. Clients of libfsimage must ensure they duplicate any file descriptor they want to preserve past the lifetime of the fsi_t* objects that use them.

---
 tools/libfsimage/common/fsimage.c           | 42 +++++++++++++++------
 tools/libfsimage/common/fsimage_grub.c      |  2 +-
 tools/libfsimage/common/fsimage_plugin.c    |  4 +-
 tools/libfsimage/common/fsimage_priv.h      |  3 +-
 tools/libfsimage/common/mapfile-GNU         |  2 +
 tools/libfsimage/common/mapfile-SunOS       |  2 +
 tools/libfsimage/common/xenfsimage.h        |  3 ++
 tools/libfsimage/common/xenfsimage_plugin.h |  2 +-
 tools/libfsimage/ext2fs-lib/ext2fs-lib.c    | 14 ++++++-
 9 files changed, 56 insertions(+), 18 deletions(-)
tools/libfsimage/common/fsimage.c +31 -11
index 5cfa56a84d..1fd302e506 100644
@@ -38,15 +38,32 @@ static pthread_mutex_t fsi_lock = PTHREAD_MUTEX_INITIALIZER;
 
 fsi_t *fsi_open_fsimage(const char *path, uint64_t off, const char *options)
 {
-	fsi_t *fsi = NULL;
+	fsi_t *fsi;
 	int fd;
 	int err;
 
 	if ((fd = open(path, O_RDONLY)) == -1)
-		goto fail;
+		return NULL;
+
+	fsi = fsi_fdopen_fsimage(fd, off, options);
+
+	if (fsi)
+		return fsi;
+
+	err = errno;
+	(void) close(fd);
+	errno = err;
+
+	return NULL;
+}
+
+fsi_t *fsi_fdopen_fsimage(int fd, uint64_t off, const char *options)
+{
+	fsi_t *fsi = NULL;
+	int err;
 
 	if ((fsi = malloc(sizeof(*fsi))) == NULL)
-		goto fail;
+		return NULL;
 
 	fsi->f_fd = fd;
 	fsi->f_off = off;
@@ -54,20 +71,17 @@ fsi_t *fsi_open_fsimage(const char *path, uint64_t off, const char *options)
 	fsi->f_bootstring = NULL;
 
 	pthread_mutex_lock(&fsi_lock);
-	err = find_plugin(fsi, path, options);
+	err = find_plugin(fsi, options);
 	pthread_mutex_unlock(&fsi_lock);
-	if (err != 0)
-		goto fail;
 
-	return (fsi);
+	if (!err)
+		return fsi;
 
-fail:
 	err = errno;
-	if (fd != -1)
-		(void) close(fd);
 	free(fsi);
 	errno = err;
-	return (NULL);
+
+	return NULL;
 }
 
 void fsi_close_fsimage(fsi_t *fsi)
@@ -167,3 +181,9 @@ fsi_fs_bootstring(fsi_t *fsi)
 {
 	return (fsi->f_bootstring);
 }
+
+int
+fsi_fd(fsi_t *fsi)
+{
+	return (fsi->f_fd);
+}
tools/libfsimage/common/fsimage_grub.c +1 -1
index 258d48bfbb..04397235f7 100644
@@ -221,7 +221,7 @@ fsig_substring(const char *s1, const char *s2)
 }
 
 static int
-fsig_mount(fsi_t *fsi, const char *path, const char *options)
+fsig_mount(fsi_t *fsi, const char *options)
 {
 	fsig_plugin_ops_t *ops = fsi->f_plugin->fp_data;
 	fsi_file_t *ffi;
tools/libfsimage/common/fsimage_plugin.c +2 -2
index d0cb9e96a6..6645ce3bfe 100644
@@ -175,7 +175,7 @@ fail:
 	return (ret);
 }
 
-int find_plugin(fsi_t *fsi, const char *path, const char *options)
+int find_plugin(fsi_t *fsi, const char *options)
 {
 	fsi_plugin_t *fp;
 	int ret = 0;
@@ -185,7 +185,7 @@ int find_plugin(fsi_t *fsi, const char *path, const char *options)
 
 	for (fp = plugins; fp != NULL; fp = fp->fp_next) {
 		fsi->f_plugin = fp;
-		if (fp->fp_ops->fpo_mount(fsi, path, options) == 0)
+		if (fp->fp_ops->fpo_mount(fsi, options) == 0)
 			goto out;
 	}
 
tools/libfsimage/common/fsimage_priv.h +2 -1
index 2274403557..779e433b37 100644
@@ -29,6 +29,7 @@ extern C {
 #endif
 
 #include <sys/types.h>
+#include <stdbool.h>
 
 #include "xenfsimage.h"
 #include "xenfsimage_plugin.h"
@@ -54,7 +55,7 @@ struct fsi_file {
 	void *ff_data;
 };
 
-int find_plugin(fsi_t *, const char *, const char *);
+int find_plugin(fsi_t *, const char *);
 
 #ifdef __cplusplus
 };
tools/libfsimage/common/mapfile-GNU +2 -0
index 2d54d527d7..658f313315 100644
@@ -3,6 +3,7 @@ VERSION {
 		global:
 			fsi_init;
 			fsi_open_fsimage;
+			fsi_fdopen_fsimage;
 			fsi_close_fsimage;
 			fsi_file_exists;
 			fsi_open_file;
@@ -12,6 +13,7 @@ VERSION {
 			fsi_bootstring_alloc;
 			fsi_bootstring_free;
 			fsi_fs_bootstring;
+			fsi_fd;
 	
 			fsip_fs_set_data;
 			fsip_file_alloc;
tools/libfsimage/common/mapfile-SunOS +2 -0
index 48deedb425..a03646ff73 100644
@@ -2,6 +2,7 @@ libfsimage.so.1.0 {
 	global:
 		fsi_init;
 		fsi_open_fsimage;
+		fsi_fdopen_fsimage;
 		fsi_close_fsimage;
 		fsi_file_exists;
 		fsi_open_file;
@@ -11,6 +12,7 @@ libfsimage.so.1.0 {
 		fsi_bootstring_alloc;
 		fsi_bootstring_free;
 		fsi_fs_bootstring;
+		fsi_fd;
 
 		fsip_fs_set_data;
 		fsip_file_alloc;
tools/libfsimage/common/xenfsimage.h +3 -0
index 341883b2d7..8048cc7470 100644
@@ -44,6 +44,7 @@ typedef struct fsi_file fsi_file_t;
 int fsi_init(void);
 
 fsi_t *fsi_open_fsimage(const char *, uint64_t, const char *);
+fsi_t *fsi_fdopen_fsimage(int, uint64_t, const char *);
 void fsi_close_fsimage(fsi_t *);
 
 int fsi_file_exists(fsi_t *, const char *);
@@ -57,6 +58,8 @@ char *fsi_bootstring_alloc(fsi_t *, size_t);
 void fsi_bootstring_free(fsi_t *);
 char *fsi_fs_bootstring(fsi_t *);
 
+int fsi_fd(fsi_t *);
+
 #ifdef __cplusplus
 };
 #endif
tools/libfsimage/common/xenfsimage_plugin.h +1 -1
index 4135769018..996ea5ecbb 100644
@@ -38,7 +38,7 @@ typedef struct fsi_plugin fsi_plugin_t;
 
 typedef struct fsi_plugin_ops {
 	int fpo_version;
-	int (*fpo_mount)(fsi_t *, const char *, const char *);
+	int (*fpo_mount)(fsi_t *, const char *);
 	int (*fpo_umount)(fsi_t *);
 	fsi_file_t *(*fpo_open)(fsi_t *, const char *);
 	ssize_t (*fpo_read)(fsi_file_t *, void *, size_t);
tools/libfsimage/ext2fs-lib/ext2fs-lib.c +12 -2
index 864a15b349..9f07ea288f 100644
@@ -25,15 +25,25 @@
 #include INCLUDE_EXTFS_H
 #include <errno.h>
 #include <inttypes.h>
+#include <stdio.h>
 
 static int
-ext2lib_mount(fsi_t *fsi, const char *name, const char *options)
+ext2lib_mount(fsi_t *fsi, const char *options)
 {
 	int err;
 	char opts[30] = "";
 	ext2_filsys *fs;
 	uint64_t offset = fsip_fs_offset(fsi);
 
+	/*
+	 * We must choose unixfd_io_manager rather than unix_io_manager in
+	 * order for the library to accept fd strings instead of paths. It
+	 * still means we must pass a string representing an fd rather than
+	 * an int, but at least this way we don't need to pass paths around
+	 */
+	char name[32] = {0};
+	(void)snprintf(name, sizeof(name) - 1, "%d", fsi_fd(fsi));
+
 	if (offset)
 		snprintf(opts, 29, "offset=%" PRId64, offset);
 
@@ -41,7 +51,7 @@ ext2lib_mount(fsi_t *fsi, const char *name, const char *options)
 	if (fs == NULL)
 		return (-1);
 
-	err = ext2fs_open2(name, opts, 0, 0, 0, unix_io_manager, fs);
+	err = ext2fs_open2(name, opts, 0, 0, 0, unixfd_io_manager, fs);
 
 	if (err != 0) {
 		free(fs);
Signature · 1 line
2.34.1
#15 lore raw

Re: [PATCH 4/6] tools/libfsimage: Add an fdopen() interface to libfsimage

Quoted 13 lines · Alejandro Vallejo
tools/libfsimage/common/fsimage_priv.h +1 -0
index 2274403557..779e433b37 100644
@@ -29,6 +29,7 @@ extern C {
 #endif
 
 #include <sys/types.h>
+#include <stdbool.h>
 
 #include "xenfsimage.h"
 #include "xenfsimage_plugin.h"

tools/libfsimage/common/fsimage_priv.h struct fsi_file { · line 61

Quoted 8 lines
tools/libfsimage/common/fsimage_priv.h +1 -1
@@ -54,7 +55,7 @@ struct fsi_file {
 	void *ff_data;
 };
 
-int find_plugin(fsi_t *, const char *, const char *);
+int find_plugin(fsi_t *, const char *);
 
 #ifdef __cplusplus
 };

These are the only two hunks in this file.  Is the stdbool include stale?

It seems to compile fine with it removed.

Quoted 16 lines
tools/libfsimage/ext2fs-lib/ext2fs-lib.c +2 -1
index 864a15b349..9f07ea288f 100644
@@ -25,15 +25,25 @@
 #include INCLUDE_EXTFS_H
 #include <errno.h>
 #include <inttypes.h>
+#include <stdio.h>
 
 static int
-ext2lib_mount(fsi_t *fsi, const char *name, const char *options)
+ext2lib_mount(fsi_t *fsi, const char *options)
 {
 	int err;
 	char opts[30] = "";

tools/libfsimage/ext2fs-lib/ext2fs-lib.c line 44

Quoted 10 lines
tools/libfsimage/ext2fs-lib/ext2fs-lib.c +7 -0
 	ext2_filsys *fs;
 	uint64_t offset = fsip_fs_offset(fsi);
 
+	/*
+	 * We must choose unixfd_io_manager rather than unix_io_manager in
+	 * order for the library to accept fd strings instead of paths. It
+	 * still means we must pass a string representing an fd rather than
+	 * an int, but at least this way we don't need to pass paths around
+	 */
+	char name[32] = {0};

For an int?  12 will do fine including a terminator, and practical system limits leave it far smaller than that generally.

Given that it is guaranteed long enough, you don't need to zero it just to have snprintf() write a well-formed string in.

~Andrew

#16 lore raw

Re: [PATCH 4/6] tools/libfsimage: Add an fdopen() interface to libfsimage

Quoted 20 lines · Andrew Cooper
Quoted 19 lines · Alejandro Vallejo
tools/libfsimage/common/fsimage_priv.h +2 -1
index 2274403557..779e433b37 100644
@@ -29,6 +29,7 @@ extern C {
  #endif
 
  #include <sys/types.h>
+#include <stdbool.h>
 
  #include "xenfsimage.h"
  #include "xenfsimage_plugin.h"
@@ -54,7 +55,7 @@ struct fsi_file {
  	void *ff_data;
  };
 
-int find_plugin(fsi_t *, const char *, const char *);
+int find_plugin(fsi_t *, const char *);
 
Quoted 6 lines

tools/libfsimage/common/fsimage_priv.h struct fsi_file { · line 61

Quoted 2 lines
tools/libfsimage/common/fsimage_priv.h +0 -0
  #ifdef __cplusplus
  };

These are the only two hunks in this file.  Is the stdbool include stale?

It seems to compile fine with it removed.

I think it's leftover from code I needed initially and then didn't anymore. Safe to get rid of.

Quoted 20 lines
Quoted 20 lines
tools/libfsimage/ext2fs-lib/ext2fs-lib.c +2 -1
index 864a15b349..9f07ea288f 100644
@@ -25,15 +25,25 @@
  #include INCLUDE_EXTFS_H
  #include <errno.h>
  #include <inttypes.h>
+#include <stdio.h>
 
  static int
-ext2lib_mount(fsi_t *fsi, const char *name, const char *options)
+ext2lib_mount(fsi_t *fsi, const char *options)
  {
  	int err;
  	char opts[30] = "";
  	ext2_filsys *fs;
  	uint64_t offset = fsip_fs_offset(fsi);
 
Quoted 10 lines

tools/libfsimage/ext2fs-lib/ext2fs-lib.c line 44

Quoted 7 lines
tools/libfsimage/ext2fs-lib/ext2fs-lib.c +7 -0
+	/*
+	 * We must choose unixfd_io_manager rather than unix_io_manager in
+	 * order for the library to accept fd strings instead of paths. It
+	 * still means we must pass a string representing an fd rather than
+	 * an int, but at least this way we don't need to pass paths around
+	 */
+	char name[32] = {0};

For an int?  12 will do fine including a terminator, and practical system limits leave it far smaller than that generally.

Maybe. I admit optimising that line went pretty low on the list of things I cared terribly about. I'm happy to reduce it, but it is inconsequential.

Quoted 5 lines

Given that it is guaranteed long enough, you don't need to zero it just to have snprintf() write a well-formed string in.

~Andrew

For wellformed fd's that's true. Through bugs or malice that may not be the case. I'm happier knowing at least the last zero remains.

Cheers,
Alejandro

#17 lore raw

PATCH 5/6 tools/pygrub: Expose libfsimage's fdopen() to python

In reply to Alejandro Vallejo

Create a wrapper for the new fdopen() function of libfsimage.

---
 tools/pygrub/src/fsimage/fsimage.c | 33 ++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
tools/pygrub/src/fsimage/fsimage.c +33 -0
index 12dfcff6e3..216f265331 100644
@@ -270,6 +270,30 @@ fsimage_open(PyObject *o, PyObject *args, PyObject *kwargs)
 	return (PyObject *)fs;
 }
 
+static PyObject *
+fsimage_fdopen(PyObject *o, PyObject *args, PyObject *kwargs)
+{
+	static char *kwlist[] = { "fd", "offset", "options", NULL };
+	int fd;
+	char *options = NULL;
+	uint64_t offset = 0;
+	fsimage_fs_t *fs;
+
+	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|Ls", kwlist,
+	    &fd, &offset, &options))
+		return (NULL);
+
+	if ((fs = PyObject_NEW(fsimage_fs_t, &fsimage_fs_type)) == NULL)
+		return (NULL);
+
+	if ((fs->fs = fsi_fdopen_fsimage(fd, offset, options)) == NULL) {
+		PyErr_SetFromErrno(PyExc_IOError);
+		return (NULL);
+	}
+
+	return (PyObject *)fs;
+}
+
 static PyObject *
 fsimage_getbootstring(PyObject *o, PyObject *args)
 {
@@ -302,6 +326,13 @@ PyDoc_STRVAR(fsimage_open__doc__,
     "offset - offset of file system within file image.\n"
     "options - mount options string.\n");
 
+PyDoc_STRVAR(fsimage_fdopen__doc__,
+    "fdopen(fd, [offset=off]) - Use the file provided by the given fd as a filesystem image.\n"
+    "\n"
+    "fd - File descriptor to use.\n"
+    "offset - offset of file system within file image.\n"
+    "options - mount options string.\n");
+
 PyDoc_STRVAR(fsimage_getbootstring__doc__,
     "getbootstring(fs) - Return the boot string needed for this file system "
     "or NULL if none is needed.\n");
@@ -315,6 +346,8 @@ static struct PyMethodDef fsimage_module_methods[] = {
 	    METH_VARARGS, fsimage_init__doc__ },
 	{ "open", (PyCFunction)fsimage_open,
 	    METH_VARARGS|METH_KEYWORDS, fsimage_open__doc__ },
+	{ "fdopen", (PyCFunction)fsimage_fdopen,
+	    METH_VARARGS|METH_KEYWORDS, fsimage_fdopen__doc__ },
 	{ "getbootstring", (PyCFunction)fsimage_getbootstring,
 	    METH_VARARGS, fsimage_getbootstring__doc__ },
 	{ NULL, NULL, 0, NULL }
Signature · 1 line
2.34.1
#18 lore raw

Re: [PATCH 5/6] tools/pygrub: Expose libfsimage's fdopen() to python

Quoted 3 lines · Alejandro Vallejo

Create a wrapper for the new fdopen() function of libfsimage.

I'd appreciate it if Marek would cast his eye (as python maintainer) over it.

That said, ...

Quoted 16 lines
tools/pygrub/src/fsimage/fsimage.c +8 -0
index 12dfcff6e3..216f265331 100644
@@ -270,6 +270,30 @@ fsimage_open(PyObject *o, PyObject *args, PyObject *kwargs)
 	return (PyObject *)fs;
 }
 
+static PyObject *
+fsimage_fdopen(PyObject *o, PyObject *args, PyObject *kwargs)
+{
+	static char *kwlist[] = { "fd", "offset", "options", NULL };
+	int fd;
+	char *options = NULL;
+	uint64_t offset = 0;
+	fsimage_fs_t *fs;

tools/pygrub/src/fsimage/fsimage.c fsimage_open(PyObject *o, PyObject *args, PyObject *kwargs) · line 290

Quoted 10 lines
tools/pygrub/src/fsimage/fsimage.c +10 -0
+
+	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|Ls", kwlist,
+	    &fd, &offset, &options))
+		return (NULL);
+
+	if ((fs = PyObject_NEW(fsimage_fs_t, &fsimage_fs_type)) == NULL)
+		return (NULL);
+
+	if ((fs->fs = fsi_fdopen_fsimage(fd, offset, options)) == NULL) {
+		PyErr_SetFromErrno(PyExc_IOError);

Don't we need a Py_DECREF(fs) here to avoid leaking it?

~Andrew

Quoted 32 lines
tools/pygrub/src/fsimage/fsimage.c +15 -0
+		return (NULL);
+	}
+
+	return (PyObject *)fs;
+}
+
 static PyObject *
 fsimage_getbootstring(PyObject *o, PyObject *args)
 {
@@ -302,6 +326,13 @@ PyDoc_STRVAR(fsimage_open__doc__,
     "offset - offset of file system within file image.\n"
     "options - mount options string.\n");
 
+PyDoc_STRVAR(fsimage_fdopen__doc__,
+    "fdopen(fd, [offset=off]) - Use the file provided by the given fd as a filesystem image.\n"
+    "\n"
+    "fd - File descriptor to use.\n"
+    "offset - offset of file system within file image.\n"
+    "options - mount options string.\n");
+
 PyDoc_STRVAR(fsimage_getbootstring__doc__,
     "getbootstring(fs) - Return the boot string needed for this file system "
     "or NULL if none is needed.\n");
@@ -315,6 +346,8 @@ static struct PyMethodDef fsimage_module_methods[] = {
 	    METH_VARARGS, fsimage_init__doc__ },
 	{ "open", (PyCFunction)fsimage_open,
 	    METH_VARARGS|METH_KEYWORDS, fsimage_open__doc__ },
+	{ "fdopen", (PyCFunction)fsimage_fdopen,
+	    METH_VARARGS|METH_KEYWORDS, fsimage_fdopen__doc__ },
 	{ "getbootstring", (PyCFunction)fsimage_getbootstring,
 	    METH_VARARGS, fsimage_getbootstring__doc__ },
 	{ NULL, NULL, 0, NULL }
#19 lore raw

Re: [PATCH 5/6] tools/pygrub: Expose libfsimage's fdopen() to python

Quoted 39 lines · Andrew Cooper
Quoted 3 lines · Alejandro Vallejo

Create a wrapper for the new fdopen() function of libfsimage.

I'd appreciate it if Marek would cast his eye (as python maintainer) over it.

That said, ...

Quoted 16 lines
tools/pygrub/src/fsimage/fsimage.c +8 -0
index 12dfcff6e3..216f265331 100644
@@ -270,6 +270,30 @@ fsimage_open(PyObject *o, PyObject *args, PyObject *kwargs)
  	return (PyObject *)fs;
  }
 
+static PyObject *
+fsimage_fdopen(PyObject *o, PyObject *args, PyObject *kwargs)
+{
+	static char *kwlist[] = { "fd", "offset", "options", NULL };
+	int fd;
+	char *options = NULL;
+	uint64_t offset = 0;
+	fsimage_fs_t *fs;

tools/pygrub/src/fsimage/fsimage.c fsimage_open(PyObject *o, PyObject *args, PyObject *kwargs) · line 290

Quoted 10 lines
tools/pygrub/src/fsimage/fsimage.c +10 -0
+
+	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|Ls", kwlist,
+	    &fd, &offset, &options))
+		return (NULL);
+
+	if ((fs = PyObject_NEW(fsimage_fs_t, &fsimage_fs_type)) == NULL)
+		return (NULL);
+
+	if ((fs->fs = fsi_fdopen_fsimage(fd, offset, options)) == NULL) {
+		PyErr_SetFromErrno(PyExc_IOError);

Don't we need a Py_DECREF(fs) here to avoid leaking it?

Quoted 1 line

~Andrew

If so, there's a bug in fsimage_open() as well. The logic here identical to the logic there.

Cheers,
Alejandro

#20 lore raw

PATCH 6/6 tools/pygrub: Hook libfsimage's fdopen() to pygrub

In reply to Alejandro Vallejo

This patch increases the security posture by removing the need to grant filesystem access to the depriv pygrub. Using libfsimage's fdopen(), the parent thread in the depriv procedure can simply ensure all the appropriate file descriptors are present before revoking permissions to the filesystem.

A convenient usability side-effect is that it's no longer required for the restricted user to have access to the disk, because the depriv thread already has the file descriptor open by its parent.

---
 docs/man/xl.cfg.5.pod.in         |  6 +-
 tools/pygrub/src/ExtLinuxConf.py | 20 ++++---
 tools/pygrub/src/GrubConf.py     | 29 ++++++----
 tools/pygrub/src/LiloConf.py     | 20 ++++---
 tools/pygrub/src/pygrub          | 95 ++++++++------------------------
 5 files changed, 68 insertions(+), 102 deletions(-)
docs/man/xl.cfg.5.pod.in +2 -4
index 2e234b450e..e3fd2e37eb 100644
@@ -1704,8 +1704,7 @@ See docs/features/qemu-deprivilege.pandoc for more information
 on how to setup the unprivileged users.
 
 Note that running the bootloader in restricted mode also implies using
-non-interactive mode, and the disk image must be readable by the
-restricted user.
+non-interactive mode.
 
 =item B<bootloader_user=USERNAME>
 
@@ -2768,8 +2767,7 @@ See docs/features/qemu-deprivilege.pandoc for more information
 on how to setup the unprivileged users.
 
 Note that running the bootloader in restricted mode also implies using
-non-interactive mode, and the disk image must be readable by the
-restricted user.
+non-interactive mode.
 
 =item B<bootloader_user=USERNAME>
 
tools/pygrub/src/ExtLinuxConf.py +13 -7
index 4e990a9304..f2e9a81013 100644
@@ -123,6 +123,7 @@ class ExtLinuxImage(object):
 class ExtLinuxConfigFile(object):
     def __init__(self, fn = None):
         self.filename = fn
+        self.file = None
         self.images = []
         self.timeout = -1
         self._default = 0
@@ -138,16 +139,21 @@ class ExtLinuxConfigFile(object):
 
     def parse(self, buf = None):
         if buf is None:
-            if self.filename is None:
+            if not self.filename and not self.file:
                 raise ValueError("No config file defined to parse!")
 
-            f = open(self.filename, 'r')
-            lines = f.readlines()
-            f.close()
-        else:
-            lines = buf.split("\n")
+            if self.file:
+                buf = file.read()
+                path = self.file.name
+            else:
+                f = open(self.filename, 'r')
+                buf = f.read()
+                f.close()
+        lines = buf.split("\n")
+
+        if not path:
+            path = os.path.dirname(self.filename)
 
-        path = os.path.dirname(self.filename)
         img = []
         for l in lines:
             l = l.strip()
tools/pygrub/src/GrubConf.py +17 -12
index 580c9628ca..96b79b89a7 100644
@@ -170,6 +170,7 @@ class GrubImage(_GrubImage):
 class _GrubConfigFile(object):
     def __init__(self, fn = None):
         self.filename = fn
+        self.file = None
         self.images = []
         self.timeout = -1
         self._default = 0
@@ -271,14 +272,16 @@ class GrubConfigFile(_GrubConfigFile):
 
     def parse(self, buf = None):
         if buf is None:
-            if self.filename is None:
+            if not self.filename and not self.file:
                 raise ValueError("No config file defined to parse!")
 
-            f = open(self.filename, 'r')
-            lines = f.readlines()
-            f.close()
-        else:
-            lines = buf.split("\n")
+            if self.file:
+                buf = file.read()
+            else:
+                f = open(self.filename, 'r')
+                buf = f.read()
+                f.close()
+        lines = buf.split("\n")
 
         img = None
         title = ""
@@ -370,14 +373,16 @@ class Grub2ConfigFile(_GrubConfigFile):
 
     def parse(self, buf = None):
         if buf is None:
-            if self.filename is None:
+            if not self.filename and not self.file:
                 raise ValueError("No config file defined to parse!")
 
-            f = open(self.filename, 'r')
-            lines = f.readlines()
-            f.close()
-        else:
-            lines = buf.split("\n")
+            if self.file:
+                buf = file.read()
+            else:
+                f = open(self.filename, 'r')
+                buf = f.read()
+                f.close()
+        lines = buf.split("\n")
 
         in_function = False
         img = None
tools/pygrub/src/LiloConf.py +13 -7
index e3bfcb5244..73f8fcb214 100644
@@ -90,6 +90,7 @@ class LiloImage(object):
 class LiloConfigFile(object):
     def __init__(self, fn = None):
         self.filename = fn
+        self.file = None
         self.images = []
         self.timeout = -1
         self._default = 0
@@ -99,16 +100,21 @@ class LiloConfigFile(object):
 
     def parse(self, buf = None):
         if buf is None:
-            if self.filename is None:
+            if not self.filename and not self.file:
                 raise ValueError("No config file defined to parse!")
 
-            f = open(self.filename, 'r')
-            lines = f.readlines()
-            f.close()
-        else:
-            lines = buf.split("\n")
+            if self.file:
+                buf = file.read()
+                path = self.file.name
+            else:
+                f = open(self.filename, 'r')
+                buf = f.read()
+                f.close()
+        lines = buf.split("\n")
+
+        if not path:
+            path = os.path.dirname(self.filename)
 
-        path = os.path.dirname(self.filename)
         img = []
         for l in lines:
             l = l.strip()
tools/pygrub/src/pygrub +23 -72

217 lines not on this page · raw message

Signature · 1 line
2.34.1
#21 lore raw

Re: [PATCH 6/6] tools/pygrub: Hook libfsimage's fdopen() to pygrub

Quoted 33 lines · Alejandro Vallejo

This patch increases the security posture by removing the need to grant filesystem access to the depriv pygrub. Using libfsimage's fdopen(), the parent thread in the depriv procedure can simply ensure all the appropriate file descriptors are present before revoking permissions to the filesystem.

A convenient usability side-effect is that it's no longer required for the restricted user to have access to the disk, because the depriv thread already has the file descriptor open by its parent.

---
 docs/man/xl.cfg.5.pod.in         |  6 +-
 tools/pygrub/src/ExtLinuxConf.py | 20 ++++---
 tools/pygrub/src/GrubConf.py     | 29 ++++++----
 tools/pygrub/src/LiloConf.py     | 20 ++++---
 tools/pygrub/src/pygrub          | 95 ++++++++------------------------
 5 files changed, 68 insertions(+), 102 deletions(-)
docs/man/xl.cfg.5.pod.in +1 -2
index 2e234b450e..e3fd2e37eb 100644
@@ -1704,8 +1704,7 @@ See docs/features/qemu-deprivilege.pandoc for more information
 on how to setup the unprivileged users.
 
 Note that running the bootloader in restricted mode also implies using
-non-interactive mode, and the disk image must be readable by the
-restricted user.
+non-interactive mode.
 
 =item B<bootloader_user=USERNAME>
 

docs/man/xl.cfg.5.pod.in See docs/features/qemu-deprivilege.pandoc for more information · line 2773

Quoted 9 lines
docs/man/xl.cfg.5.pod.in +1 -2
@@ -2768,8 +2767,7 @@ See docs/features/qemu-deprivilege.pandoc for more information
 on how to setup the unprivileged users.
 
 Note that running the bootloader in restricted mode also implies using
-non-interactive mode, and the disk image must be readable by the
-restricted user.
+non-interactive mode.
 
 =item B<bootloader_user=USERNAME>
 

I'm leaning towards suggesting that this wants a note in the changelog, as we're removing a limitation imposed by a security fix.

Quoted 31 lines
tools/pygrub/src/ExtLinuxConf.py +8 -6
index 4e990a9304..f2e9a81013 100644
@@ -123,6 +123,7 @@ class ExtLinuxImage(object):
 class ExtLinuxConfigFile(object):
     def __init__(self, fn = None):
         self.filename = fn
+        self.file = None
         self.images = []
         self.timeout = -1
         self._default = 0
@@ -138,16 +139,21 @@ class ExtLinuxConfigFile(object):
 
     def parse(self, buf = None):
         if buf is None:
-            if self.filename is None:
+            if not self.filename and not self.file:
                 raise ValueError("No config file defined to parse!")
 
-            f = open(self.filename, 'r')
-            lines = f.readlines()
-            f.close()
-        else:
-            lines = buf.split("\n")
+            if self.file:
+                buf = file.read()
+                path = self.file.name
+            else:
+                f = open(self.filename, 'r')
+                buf = f.read()

tools/pygrub/src/ExtLinuxConf.py class ExtLinuxConfigFile(object): · line 159

Quoted 10 lines
tools/pygrub/src/ExtLinuxConf.py +5 -1
+                f.close()
+        lines = buf.split("\n")
+
+        if not path:
+            path = os.path.dirname(self.filename)
 
-        path = os.path.dirname(self.filename)
         img = []
         for l in lines:
             l = l.strip()

[List context, Alejandro and I discussed this IRL]

This pattern is horrible and repeated in each object.  I'm going to experiment and see if there's a (limited) bit of cleanup which can be done to reduce the invasiveness, and therefore the legibility of this patch.

~Andrew