Back to home page

OSCL-LXR

 
 

    


0001 #!/usr/bin/env python3
0002 # SPDX-License-Identifier: GPL-2.0
0003 #
0004 # Test that truncation of bprm->buf doesn't cause unexpected execs paths, along
0005 # with various other pathological cases.
0006 import os, subprocess
0007 
0008 # Relevant commits
0009 #
0010 # b5372fe5dc84 ("exec: load_script: Do not exec truncated interpreter path")
0011 # 6eb3c3d0a52d ("exec: increase BINPRM_BUF_SIZE to 256")
0012 
0013 # BINPRM_BUF_SIZE
0014 SIZE=256
0015 
0016 NAME_MAX=int(subprocess.check_output(["getconf", "NAME_MAX", "."]))
0017 
0018 test_num=0
0019 
0020 code='''#!/usr/bin/perl
0021 print "Executed interpreter! Args:\n";
0022 print "0 : '$0'\n";
0023 $counter = 1;
0024 foreach my $a (@ARGV) {
0025     print "$counter : '$a'\n";
0026     $counter++;
0027 }
0028 '''
0029 
0030 ##
0031 # test - produce a binfmt_script hashbang line for testing
0032 #
0033 # @size:     bytes for bprm->buf line, including hashbang but not newline
0034 # @good:     whether this script is expected to execute correctly
0035 # @hashbang: the special 2 bytes for running binfmt_script
0036 # @leading:  any leading whitespace before the executable path
0037 # @root:     start of executable pathname
0038 # @target:   end of executable pathname
0039 # @arg:      bytes following the executable pathname
0040 # @fill:     character to fill between @root and @target to reach @size bytes
0041 # @newline:  character to use as newline, not counted towards @size
0042 # ...
0043 def test(name, size, good=True, leading="", root="./", target="/perl",
0044                      fill="A", arg="", newline="\n", hashbang="#!"):
0045     global test_num, tests, NAME_MAX
0046     test_num += 1
0047     if test_num > tests:
0048         raise ValueError("more binfmt_script tests than expected! (want %d, expected %d)"
0049                          % (test_num, tests))
0050 
0051     middle = ""
0052     remaining = size - len(hashbang) - len(leading) - len(root) - len(target) - len(arg)
0053     # The middle of the pathname must not exceed NAME_MAX
0054     while remaining >= NAME_MAX:
0055         middle += fill * (NAME_MAX - 1)
0056         middle += '/'
0057         remaining -= NAME_MAX
0058     middle += fill * remaining
0059 
0060     dirpath = root + middle
0061     binary = dirpath + target
0062     if len(target):
0063         os.makedirs(dirpath, mode=0o755, exist_ok=True)
0064         open(binary, "w").write(code)
0065         os.chmod(binary, 0o755)
0066 
0067     buf=hashbang + leading + root + middle + target + arg + newline
0068     if len(newline) > 0:
0069         buf += 'echo this is not really perl\n'
0070 
0071     script = "binfmt_script-%s" % (name)
0072     open(script, "w").write(buf)
0073     os.chmod(script, 0o755)
0074 
0075     proc = subprocess.Popen(["./%s" % (script)], shell=True,
0076                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
0077     stdout = proc.communicate()[0]
0078 
0079     if proc.returncode == 0 and b'Executed interpreter' in stdout:
0080         if good:
0081             print("ok %d - binfmt_script %s (successful good exec)"
0082                   % (test_num, name))
0083         else:
0084             print("not ok %d - binfmt_script %s succeeded when it should have failed"
0085                   % (test_num, name))
0086     else:
0087         if good:
0088             print("not ok %d - binfmt_script %s failed when it should have succeeded (rc:%d)"
0089                   % (test_num, name, proc.returncode))
0090         else:
0091             print("ok %d - binfmt_script %s (correctly failed bad exec)"
0092                   % (test_num, name))
0093 
0094     # Clean up crazy binaries
0095     os.unlink(script)
0096     if len(target):
0097         elements = binary.split('/')
0098         os.unlink(binary)
0099         elements.pop()
0100         while len(elements) > 1:
0101             os.rmdir("/".join(elements))
0102             elements.pop()
0103 
0104 tests=27
0105 print("TAP version 1.3")
0106 print("1..%d" % (tests))
0107 
0108 ### FAIL (8 tests)
0109 
0110 # Entire path is well past the BINFMT_BUF_SIZE.
0111 test(name="too-big",        size=SIZE+80, good=False)
0112 # Path is right at max size, making it impossible to tell if it was truncated.
0113 test(name="exact",          size=SIZE,    good=False)
0114 # Same as above, but with leading whitespace.
0115 test(name="exact-space",    size=SIZE,    good=False, leading=" ")
0116 # Huge buffer of only whitespace.
0117 test(name="whitespace-too-big", size=SIZE+71, good=False, root="",
0118                                               fill=" ", target="")
0119 # A good path, but it gets truncated due to leading whitespace.
0120 test(name="truncated",      size=SIZE+17, good=False, leading=" " * 19)
0121 # Entirely empty except for #!
0122 test(name="empty",          size=2,       good=False, root="",
0123                                           fill="", target="", newline="")
0124 # Within size, but entirely spaces
0125 test(name="spaces",         size=SIZE-1,  good=False, root="", fill=" ",
0126                                           target="", newline="")
0127 # Newline before binary.
0128 test(name="newline-prefix", size=SIZE-1,  good=False, leading="\n",
0129                                           root="", fill=" ", target="")
0130 
0131 ### ok (19 tests)
0132 
0133 # The original test case that was broken by commit:
0134 # 8099b047ecc4 ("exec: load_script: don't blindly truncate shebang string")
0135 test(name="test.pl",        size=439, leading=" ",
0136      root="./nix/store/bwav8kz8b3y471wjsybgzw84mrh4js9-perl-5.28.1/bin",
0137      arg=" -I/nix/store/x6yyav38jgr924nkna62q3pkp0dgmzlx-perl5.28.1-File-Slurp-9999.25/lib/perl5/site_perl -I/nix/store/ha8v67sl8dac92r9z07vzr4gv1y9nwqz-perl5.28.1-Net-DBus-1.1.0/lib/perl5/site_perl -I/nix/store/dcrkvnjmwh69ljsvpbdjjdnqgwx90a9d-perl5.28.1-XML-Parser-2.44/lib/perl5/site_perl -I/nix/store/rmji88k2zz7h4zg97385bygcydrf2q8h-perl5.28.1-XML-Twig-3.52/lib/perl5/site_perl")
0138 # One byte under size, leaving newline visible.
0139 test(name="one-under",           size=SIZE-1)
0140 # Two bytes under size, leaving newline visible.
0141 test(name="two-under",           size=SIZE-2)
0142 # Exact size, but trailing whitespace visible instead of newline
0143 test(name="exact-trunc-whitespace", size=SIZE, arg=" ")
0144 # Exact size, but trailing space and first arg char visible instead of newline.
0145 test(name="exact-trunc-arg",     size=SIZE, arg=" f")
0146 # One bute under, with confirmed non-truncated arg since newline now visible.
0147 test(name="one-under-full-arg",  size=SIZE-1, arg=" f")
0148 # Short read buffer by one byte.
0149 test(name="one-under-no-nl",     size=SIZE-1, newline="")
0150 # Short read buffer by half buffer size.
0151 test(name="half-under-no-nl",    size=int(SIZE/2), newline="")
0152 # One byte under with whitespace arg. leaving wenline visible.
0153 test(name="one-under-trunc-arg", size=SIZE-1, arg=" ")
0154 # One byte under with whitespace leading. leaving wenline visible.
0155 test(name="one-under-leading",   size=SIZE-1, leading=" ")
0156 # One byte under with whitespace leading and as arg. leaving newline visible.
0157 test(name="one-under-leading-trunc-arg",  size=SIZE-1, leading=" ", arg=" ")
0158 # Same as above, but with 2 bytes under
0159 test(name="two-under-no-nl",     size=SIZE-2, newline="")
0160 test(name="two-under-trunc-arg", size=SIZE-2, arg=" ")
0161 test(name="two-under-leading",   size=SIZE-2, leading=" ")
0162 test(name="two-under-leading-trunc-arg",   size=SIZE-2, leading=" ", arg=" ")
0163 # Same as above, but with buffer half filled
0164 test(name="two-under-no-nl",     size=int(SIZE/2), newline="")
0165 test(name="two-under-trunc-arg", size=int(SIZE/2), arg=" ")
0166 test(name="two-under-leading",   size=int(SIZE/2), leading=" ")
0167 test(name="two-under-lead-trunc-arg", size=int(SIZE/2), leading=" ", arg=" ")
0168 
0169 if test_num != tests:
0170     raise ValueError("fewer binfmt_script tests than expected! (ran %d, expected %d"
0171                      % (test_num, tests))