| 
 | 1 | +#! /usr/bin/python  | 
 | 2 | +#  | 
 | 3 | +# Copyright (C) 2023 Cloud Software Group  | 
 | 4 | +#  | 
 | 5 | +# This program is free software; you can redistribute it and/or modify  | 
 | 6 | +# it under the terms of the GNU Lesser General Public License as published  | 
 | 7 | +# by the Free Software Foundation; version 2.1 only. with the special  | 
 | 8 | +# exception on linking described in file LICENSE.  | 
 | 9 | +#  | 
 | 10 | +# This program is distributed in the hope that it will be useful,  | 
 | 11 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of  | 
 | 12 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  | 
 | 13 | +# GNU Lesser General Public License for more details.  | 
 | 14 | + | 
 | 15 | +from __future__ import print_function  | 
 | 16 | +import pwd, subprocess, sys  | 
 | 17 | +import grp, os, stat  | 
 | 18 | + | 
 | 19 | +cmd = ["pygrub"]  | 
 | 20 | + | 
 | 21 | +# Get the usage string. We can't use check_output() because the exit status isn't 0  | 
 | 22 | +pygrub_usage = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[1]  | 
 | 23 | + | 
 | 24 | +with_depriv = False  | 
 | 25 | +for arg in sys.argv[1:]:  | 
 | 26 | +    # Catch the synthetic --domid argument and turn it into --runas  | 
 | 27 | +    argname_domid = "--domid="  | 
 | 28 | +    if arg.startswith(argname_domid):  | 
 | 29 | +        if "[--runas=]" not in pygrub_usage:  | 
 | 30 | +            # Skip depriv if pygrub doesn't support it  | 
 | 31 | +            continue  | 
 | 32 | +        with_depriv = True  | 
 | 33 | +        domid = int(arg[len(argname_domid):])  | 
 | 34 | +        uid = pwd.getpwnam('qemu_base').pw_uid + domid  | 
 | 35 | +        cmd += ["--runas=" + str(uid)]  | 
 | 36 | + | 
 | 37 | +        # Set group permissions on the disk so a depriv pygrub can read it  | 
 | 38 | +        disk = sys.argv[-1]  | 
 | 39 | +        gid = grp.getgrnam('disk').gr_gid  | 
 | 40 | +        disk_stat = os.stat(disk)  | 
 | 41 | +        os.chown(disk, uid, gid)  | 
 | 42 | +        os.chmod(disk, disk_stat.st_mode | stat.S_IRGRP)  | 
 | 43 | +    else:  | 
 | 44 | +        cmd += [arg]  | 
 | 45 | + | 
 | 46 | +if 'PYGRUB_FORCE_DEPRIV' in os.environ.keys() and not with_depriv:  | 
 | 47 | +    raise RuntimeError("Trying to run pygrub as root: %s" % pygrub_usage)  | 
 | 48 | + | 
 | 49 | +sys.exit(subprocess.call(cmd))  | 
0 commit comments