summaryrefslogtreecommitdiff
path: root/python/samba/tests/source_chars.py
blob: 093d7318cb019b93dad80bf7d6b5d95ff1a0ddca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# Unix SMB/CIFS implementation.
#
# Copyright (C) Catalyst.Net Ltd. 2021
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import subprocess
import os
import sys
from collections import Counter
from samba.colour import c_RED, c_GREEN, c_DARK_YELLOW, switch_colour_off
import re
import unicodedata as u
from samba.tests import TestCase

if not sys.stdout.isatty():
    switch_colour_off()


def _find_root():
    try:
        p = subprocess.run(['git', 'rev-parse', '--show-toplevel'],
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE,
                           timeout=10)
    except subprocess.SubprocessError as e:
        print(c_RED(f"Error running git (is this a git tree?): {e}"))
        print("This test is only useful in a git working tree")
        sys.exit(1)

    root = p.stdout.decode().strip()

    should_be_roots = (
        os.path.abspath(os.path.join(os.path.dirname(__file__),
                                     "../../..")),
        os.path.abspath(os.path.join(os.path.dirname(__file__),
                                     "../../../..")),
    )
    if root not in should_be_roots:
        print(c_RED("It looks like we have found the wrong git tree!"))
        sys.exit(1)
    return root


ROOT = _find_root()


IGNORED_FILES = {
    'examples/validchars/validchr.com',
    'examples/tridge/smb.conf',
    'source3/selftest/ktest-krb5_ccache-2',
    'source3/selftest/ktest-krb5_ccache-3',
    'testdata/source-chars-bad.c',
}

IGNORED_EXTENSIONS = {
    'cer',
    'corrupt',
    'crl',
    'dat',
    'dump',
    'gpg',
    'gz',
    'ico',
    'keytab',
    'ldb',
    'p12',
    'pem',
    'png',
    'SAMBABACKUP',
    'sxd',
    'tdb',
    'tif',
    'reg',
}


# This list is by no means exhaustive -- these are just the format
# characters we actually use.
SAFE_FORMAT_CHARS = {
    '\u200b',
    '\ufeff'
}

# These files legitimately mix left-to-right and right-to-left text.
# In the real world mixing directions would be normal in bilingual
# documents, but it is rare in Samba source code.
BIDI_FILES = {
    'source4/heimdal/lib/wind/NormalizationTest.txt',
    'testdata/source-chars-bidi.py',
}


def get_git_files():
    try:
        p = subprocess.run(['git',
                            '-C', ROOT,
                            'ls-files',
                            '-z'],
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE,
                           timeout=10)
    except subprocess.SubprocessError as e:
        print(c_RED(f"Error running git (is this a git tree?): {e}"))
        print("This test is only useful in a git working tree")
        return []

    filenames = p.stdout.split(b'\x00')
    return [x.decode() for x in filenames[:-1]]


def iter_source_files():
    filenames = get_git_files()

    for name in filenames:
        if name in IGNORED_FILES:
            print(c_DARK_YELLOW(f"ignoring {name}"))
            continue

        if '.' in name:
            ext = name.rsplit('.', 1)[1]
            if ext in IGNORED_EXTENSIONS:
                print(c_DARK_YELLOW(f"ignoring {name}"))
                continue

        yield name


def is_latin1_file(name):
    for pattern in (
            r'^source4/setup/ad-schema/\w+.ldf$',
            r'^source4/setup/display-specifiers/D[\w-]+.txt$',
            r'^source4/heimdal/HEIMDAL-LICENCE.txt$',
            r'^source4/heimdal/lib/asn1/asn1-template.h$',
            r'^source4/heimdal/lib/asn1/gen_template.c$',
            r'^source4/heimdal/lib/hdb/hdb-keytab.c$',
    ):
        if re.match(pattern, name):
            return True
    return False


def is_bad_latin1_file(fullname):
    # In practice, the few latin-1 files we have have single non-ASCII
    # byte islands in a sea of ASCII. The utf-8 sequences we are
    # concerned about involve sequences of 3 high bytes. We can say a
    # file is safe latin-1 if it has only individual high bytes.
    with open(fullname, 'rb') as f:
        b = f.read()
    in_seq = False
    for c in b:
        if c > 0x7f:
            if in_seq:
                return True
            in_seq = True
        else:
            in_seq = False
    return False


def is_bad_char(c):
    if u.category(c) != 'Cf':
        return False
    if c in SAFE_FORMAT_CHARS:
        return False
    return True


class CharacterTests(TestCase):
    def test_no_unexpected_format_chars(self):
        """This test tries to ensure that no source file has unicode control
        characters that can change the apparent order of other
        characters. These characters could make code appear to have
        different semantic meaning it really does.

        This issue is sometimes called "Trojan Source", "CVE-2021-42574",
        or "CVE-2021-42694".
        """
        for name in iter_source_files():
            fullname = os.path.join(ROOT, name)
            try:
                with open(fullname) as f:
                    s = f.read()
            except UnicodeDecodeError as e:
                # probably a latin-1 encoding, which we tolerate in a few
                # files for historical reasons, though we check that there
                # are not long sequences of high bytes.
                if is_latin1_file(name):
                    if is_bad_latin1_file(fullname):
                        self.fail(f"latin-1 file {name} has long sequences "
                                  "of high bytes")
                else:
                    self.fail(f"could not decode {name}: {e}")

            dirs = set()
            for c in set(s):
                if is_bad_char(c):
                    self.fail(f"{name} has potentially bad format characters!")
                dirs.add(u.bidirectional(c))

            if 'L' in dirs and 'R' in dirs:
                if name not in BIDI_FILES:
                    self.fail(f"{name} has LTR and RTL text ({dirs})")

    def test_unexpected_format_chars_do_fail(self):
        """Test the test"""
        for name, n_bad in [
                ('testdata/source-chars-bad.c', 3)
        ]:
            fullname = os.path.join(ROOT, name)
            with open(fullname) as f:
                s = f.read()
            chars = set(s)
            bad_chars = [c for c in chars if is_bad_char(c)]
            self.assertEqual(len(bad_chars), n_bad)

    def test_unexpected_bidi_fails(self):
        """Test the test"""
        for name in [
                'testdata/source-chars-bidi.py'
        ]:
            fullname = os.path.join(ROOT, name)
            with open(fullname) as f:
                s = f.read()

            dirs = set()
            for c in set(s):
                dirs.add(u.bidirectional(c))
            self.assertIn('L', dirs)
            self.assertIn('R', dirs)


def check_file_text():
    """If called directly as a script, count the found characters."""
    counts = Counter()
    for name in iter_source_files():
        fullname = os.path.join(ROOT, name)
        try:
            with open(fullname) as f:
                s = f.read()
        except UnicodeDecodeError as e:
            if is_latin1_file(name):
                if is_bad_latin1_file(fullname):
                    print(c_RED(f"latin-1 file {name} has long sequences "
                                "of high bytes"))
                else:
                    print(c_GREEN(f"latin-1 file {name} is fine"))
            else:
                print(c_RED(f"can't read {name}: {e}"))

        counts.update(s)
        chars = set(s)
        for c in chars:
            if u.category(c) == 'Cf':
                print(c_GREEN(f"{name} has {u.name(c)}"))

    print(len(counts))
    controls = []
    formats = []
    others = []
    for x in counts:
        c = u.category(x)
        if c == 'Cc':
            controls.append(x)
        elif c == 'Cf':
            formats.append(x)
        elif c[0] == 'C':
            others.append(x)

    print("normal control characters {controls}")
    print("format characters {formats}")
    print("other control characters {others}")


if __name__ == '__main__':
    check_file_text()