1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0
3#
4# Test that truncation of bprm->buf doesn't cause unexpected execs paths, along
5# with various other pathological cases.
6import os, subprocess
7
8# Relevant commits
9#
10# b5372fe5dc84 ("exec: load_script: Do not exec truncated interpreter path")
11# 6eb3c3d0a52d ("exec: increase BINPRM_BUF_SIZE to 256")
12
13# BINPRM_BUF_SIZE
14SIZE=256
15
16NAME_MAX=int(subprocess.check_output(["getconf", "NAME_MAX", "."]))
17
18test_num=0
19pass_num=0
20fail_num=0
21
22code='''#!/usr/bin/perl
23print "Executed interpreter! Args:\n";
24print "0 : '$0'\n";
25$counter = 1;
26foreach my $a (@ARGV) {
27    print "$counter : '$a'\n";
28    $counter++;
29}
30'''
31
32##
33# test - produce a binfmt_script hashbang line for testing
34#
35# @size:     bytes for bprm->buf line, including hashbang but not newline
36# @good:     whether this script is expected to execute correctly
37# @hashbang: the special 2 bytes for running binfmt_script
38# @leading:  any leading whitespace before the executable path
39# @root:     start of executable pathname
40# @target:   end of executable pathname
41# @arg:      bytes following the executable pathname
42# @fill:     character to fill between @root and @target to reach @size bytes
43# @newline:  character to use as newline, not counted towards @size
44# ...
45def test(name, size, good=True, leading="", root="./", target="/perl",
46                     fill="A", arg="", newline="\n", hashbang="#!"):
47    global test_num, pass_num, fail_num, tests, NAME_MAX
48    test_num += 1
49    if test_num > tests:
50        raise ValueError("more binfmt_script tests than expected! (want %d, expected %d)"
51                         % (test_num, tests))
52
53    middle = ""
54    remaining = size - len(hashbang) - len(leading) - len(root) - len(target) - len(arg)
55    # The middle of the pathname must not exceed NAME_MAX
56    while remaining >= NAME_MAX:
57        middle += fill * (NAME_MAX - 1)
58        middle += '/'
59        remaining -= NAME_MAX
60    middle += fill * remaining
61
62    dirpath = root + middle
63    binary = dirpath + target
64    if len(target):
65        os.makedirs(dirpath, mode=0o755, exist_ok=True)
66        open(binary, "w").write(code)
67        os.chmod(binary, 0o755)
68
69    buf=hashbang + leading + root + middle + target + arg + newline
70    if len(newline) > 0:
71        buf += 'echo this is not really perl\n'
72
73    script = "binfmt_script-%s" % (name)
74    open(script, "w").write(buf)
75    os.chmod(script, 0o755)
76
77    proc = subprocess.Popen(["./%s" % (script)], shell=True,
78                            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
79    stdout = proc.communicate()[0]
80
81    if proc.returncode == 0 and b'Executed interpreter' in stdout:
82        if good:
83            print("ok %d - binfmt_script %s (successful good exec)"
84                  % (test_num, name))
85            pass_num += 1
86        else:
87            print("not ok %d - binfmt_script %s succeeded when it should have failed"
88                  % (test_num, name))
89            fail_num = 1
90    else:
91        if good:
92            print("not ok %d - binfmt_script %s failed when it should have succeeded (rc:%d)"
93                  % (test_num, name, proc.returncode))
94            fail_num = 1
95        else:
96            print("ok %d - binfmt_script %s (correctly failed bad exec)"
97                  % (test_num, name))
98            pass_num += 1
99
100    # Clean up crazy binaries
101    os.unlink(script)
102    if len(target):
103        elements = binary.split('/')
104        os.unlink(binary)
105        elements.pop()
106        while len(elements) > 1:
107            os.rmdir("/".join(elements))
108            elements.pop()
109
110tests=27
111print("TAP version 1.3")
112print("1..%d" % (tests))
113
114### FAIL (8 tests)
115
116# Entire path is well past the BINFMT_BUF_SIZE.
117test(name="too-big",        size=SIZE+80, good=False)
118# Path is right at max size, making it impossible to tell if it was truncated.
119test(name="exact",          size=SIZE,    good=False)
120# Same as above, but with leading whitespace.
121test(name="exact-space",    size=SIZE,    good=False, leading=" ")
122# Huge buffer of only whitespace.
123test(name="whitespace-too-big", size=SIZE+71, good=False, root="",
124                                              fill=" ", target="")
125# A good path, but it gets truncated due to leading whitespace.
126test(name="truncated",      size=SIZE+17, good=False, leading=" " * 19)
127# Entirely empty except for #!
128test(name="empty",          size=2,       good=False, root="",
129                                          fill="", target="", newline="")
130# Within size, but entirely spaces
131test(name="spaces",         size=SIZE-1,  good=False, root="", fill=" ",
132                                          target="", newline="")
133# Newline before binary.
134test(name="newline-prefix", size=SIZE-1,  good=False, leading="\n",
135                                          root="", fill=" ", target="")
136
137### ok (19 tests)
138
139# The original test case that was broken by commit:
140# 8099b047ecc4 ("exec: load_script: don't blindly truncate shebang string")
141test(name="test.pl",        size=439, leading=" ",
142     root="./nix/store/bwav8kz8b3y471wjsybgzw84mrh4js9-perl-5.28.1/bin",
143     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")
144# One byte under size, leaving newline visible.
145test(name="one-under",           size=SIZE-1)
146# Two bytes under size, leaving newline visible.
147test(name="two-under",           size=SIZE-2)
148# Exact size, but trailing whitespace visible instead of newline
149test(name="exact-trunc-whitespace", size=SIZE, arg=" ")
150# Exact size, but trailing space and first arg char visible instead of newline.
151test(name="exact-trunc-arg",     size=SIZE, arg=" f")
152# One bute under, with confirmed non-truncated arg since newline now visible.
153test(name="one-under-full-arg",  size=SIZE-1, arg=" f")
154# Short read buffer by one byte.
155test(name="one-under-no-nl",     size=SIZE-1, newline="")
156# Short read buffer by half buffer size.
157test(name="half-under-no-nl",    size=int(SIZE/2), newline="")
158# One byte under with whitespace arg. leaving wenline visible.
159test(name="one-under-trunc-arg", size=SIZE-1, arg=" ")
160# One byte under with whitespace leading. leaving wenline visible.
161test(name="one-under-leading",   size=SIZE-1, leading=" ")
162# One byte under with whitespace leading and as arg. leaving newline visible.
163test(name="one-under-leading-trunc-arg",  size=SIZE-1, leading=" ", arg=" ")
164# Same as above, but with 2 bytes under
165test(name="two-under-no-nl",     size=SIZE-2, newline="")
166test(name="two-under-trunc-arg", size=SIZE-2, arg=" ")
167test(name="two-under-leading",   size=SIZE-2, leading=" ")
168test(name="two-under-leading-trunc-arg",   size=SIZE-2, leading=" ", arg=" ")
169# Same as above, but with buffer half filled
170test(name="two-under-no-nl",     size=int(SIZE/2), newline="")
171test(name="two-under-trunc-arg", size=int(SIZE/2), arg=" ")
172test(name="two-under-leading",   size=int(SIZE/2), leading=" ")
173test(name="two-under-lead-trunc-arg", size=int(SIZE/2), leading=" ", arg=" ")
174
175print("# Totals: pass:%d fail:%d xfail:0 xpass:0 skip:0 error:0" % (pass_num, fail_num))
176
177if test_num != tests:
178    raise ValueError("fewer binfmt_script tests than expected! (ran %d, expected %d"
179                     % (test_num, tests))
180