blob: 9c23ef5d0f9d162e45a1983bdab2a1dd6b9873e6 [file] [log] [blame]
Mike Frysingerb9743c62020-02-20 02:53:55 -05001#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# Copyright 2020 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Make sure packages don't create random paths outside of existing norms."""
8
9from __future__ import print_function
10
11import argparse
12import fnmatch
13import logging # pylint: disable=cros-logging-import
14import os
15import sys
16
17
18# NB: Do not add any new entries here without wider discussion.
19
20
21# Paths that are allowed in the / dir.
22VALID_ROOT = {
23 'bin', 'boot', 'dev', 'etc', 'home', 'lib', 'lib32', 'lib64', 'media',
24 'mnt', 'opt', 'proc', 'root', 'run', 'sbin', 'sys', 'tmp', 'usr', 'var',
25}
26
27# Paths that are allowed in the / dir for boards.
28VALID_BOARD_ROOT = {
29 'build', 'firmware',
30 # TODO(): We should clean this up.
31 'postinst',
32}
33
34# Paths that are allowed in the / dir for the SDK chroot.
35VALID_HOST_ROOT = set()
36
37# Paths under / that should not have any subdirs.
38NOSUBDIRS_ROOT = {
39 'bin', 'dev', 'proc', 'sbin', 'sys', 'tmp',
40}
41
42# Paths that are allowed in the /usr dir.
43VALID_USR = {
44 'bin', 'include', 'lib', 'lib32', 'lib64', 'libexec', 'sbin', 'share',
45 'src',
46}
47
48# Paths that are allowed in the /usr dir for boards.
49VALID_BOARD_USR = {
50 # Boards install into /usr/local for test images.
51 'local',
52}
53
54# Paths that are allowed in the /usr dir for the SDK chroot.
55VALID_HOST_USR = set()
56
57# Paths under /usr that should not have any subdirs.
58NOSUBDIRS_USR = {
59 'bin', 'sbin',
60}
61
62# Valid toolchain targets. We don't want to add any more non-standard ones.
63# targets that use *-cros-* as the vendor are OK to add more.
64KNOWN_TARGETS = {
65 'arm-none-eabi',
66 'i686-pc-linux-gnu',
67 'x86_64-pc-linux-gnu',
68 'arm*-cros-eabi',
69 '*-cros-linux-gnu*',
70}
71
72# These packages need fixing.
73# NB: Do *not* add more packages here.
74BAD_ROOT_PACKAGES = {
75 # TODO(crbug.com/1003107): Delete this.
76 'dev-go/go-tools',
77}
78
79# These SDK packages need cleanup.
80# NB: Do *not* add more packages here.
81BAD_HOST_USR_LOCAL_PACKAGES = {
82 'app-crypt/nss',
83}
84
85# Ignore some packages installing into /var for now.
86# NB: Do *not* add more packages here.
87BAD_VAR_PACKAGES = {
88 'app-accessibility/brltty',
89 'app-admin/eselect',
90 'app-admin/puppet',
91 'app-admin/rsyslog',
92 'app-admin/sudo',
93 'app-admin/sysstat',
94 'app-admin/webapp-config',
95 'app-crypt/mit-krb5',
96 'app-crypt/trousers',
97 'app-emulation/containerd',
98 'app-emulation/lxc',
99 'chromeos-base/chromeos-initramfs',
100 # https://crbug.com/1054646
101 'chromeos-base/devserver',
102 # https://crbug.com/1007402
103 'chromeos-base/factory',
104 'chromeos-base/factory-board',
105 'dev-python/django',
106 'media-gfx/sane-backends',
107 'media-sound/alsa-utils',
108 'net-analyzer/netperf',
109 'net-dns/dnsmasq',
110 'net-firewall/iptables',
111 'net-fs/samba',
112 'net-misc/dhcpcd',
113 'net-misc/openssh',
114 'net-print/cups',
115 'sys-apps/dbus',
116 'sys-apps/fwupd',
117 'sys-apps/iproute2',
118 'sys-apps/journald',
119 'sys-apps/portage',
120 'sys-apps/sandbox',
121 'sys-apps/systemd',
122 'sys-apps/usbguard',
123 'sys-kernel/loonix-initramfs',
124 'sys-libs/glibc',
125 'sys-process/audit',
126 'www-servers/nginx',
127 'x11-base/xwayland',
128}
129
130# Ignore some packages installing into /run for now.
131# NB: Do *not* add more packages here.
132BAD_RUN_PACKAGES = {
133 'app-accessibility/brltty',
134 'net-fs/samba',
135}
136
137# Ignore some packages installing into /tmp for now.
138# NB: Do *not* add more packages here.
139BAD_TMP_PACKAGES = {
140 # https://crbug.com/1057059
141 'chromeos-base/chromeos-bsp-caroline-private',
Mike Frysinger833a8222020-03-02 14:04:36 -0500142 'chromeos-base/chromeos-bsp-elm-private',
143 'chromeos-base/chromeos-config-bsp-coral',
144 'chromeos-base/chromeos-config-bsp-coral-private',
145 'chromeos-base/chromeos-config-bsp-nami',
146 'chromeos-base/chromeos-config-bsp-scarlet-private',
Mike Frysingerb9743c62020-02-20 02:53:55 -0500147 'chromeos-base/cros-config-test',
148}
149
150
151def has_subdirs(path):
152 """See if |path| has any subdirs."""
153 # These checks are helpful for manually running the script when debugging.
154 if os.path.ismount(path):
155 logging.warning('Ignoring mounted dir for subdir check: %s', path)
156 return False
157
158 if os.path.join(os.getenv('SYSROOT', '/'), 'tmp') == path:
159 logging.warning('Ignoring live dir: %s', path)
160 return False
161
162 for _, dirs, _ in os.walk(path):
163 if dirs:
164 logging.error('Subdirs found in a dir that should be empty:\n %s\n'
165 ' |-- %s', path, '\n |-- '.join(sorted(dirs)))
166 return True
167 break
168
169 return False
170
171
172def check_usr(usr, host=False):
173 """Check the /usr filesystem at |usr|."""
174 ret = True
175
176 # Not all packages install into /usr.
177 if not os.path.exists(usr):
178 return ret
179
180 atom = get_current_package()
181 paths = set(os.listdir(usr))
182 unknown = paths - VALID_USR
183 for target in KNOWN_TARGETS:
184 unknown = set(x for x in unknown if not fnmatch.fnmatch(x, target))
185 if host:
186 unknown -= VALID_HOST_USR
187
188 if atom in BAD_HOST_USR_LOCAL_PACKAGES:
189 logging.warning('Ignoring known bad /usr/local install for now')
190 unknown -= {'local'}
191 else:
192 unknown -= VALID_BOARD_USR
193
194 if atom in {'chromeos-base/ap-daemons'}:
195 logging.warning('Ignoring known bad /usr install for now')
196 unknown -= {'www'}
197
198 if unknown:
199 logging.error('Paths are not allowed in the /usr dir: %s', sorted(unknown))
200 ret = False
201
202 for path in NOSUBDIRS_USR:
203 if has_subdirs(os.path.join(usr, path)):
204 ret = False
205
206 return ret
207
208
209def check_root(root, host=False):
210 """Check the filesystem |root|."""
211 ret = True
212
213 atom = get_current_package()
214 paths = set(os.listdir(root))
215 unknown = paths - VALID_ROOT
216 if host:
217 unknown -= VALID_HOST_ROOT
218 else:
219 unknown -= VALID_BOARD_ROOT
220
221 if atom in BAD_ROOT_PACKAGES:
222 logging.warning('Ignoring known bad / install for now')
223 elif unknown:
224 logging.error('Paths are not allowed in the root dir:\n %s\n |-- %s',
225 root, '\n |-- '.join(sorted(unknown)))
226 ret = False
227
228 # Some of these may have subdirs at runtime, but not from package installs.
229 for path in NOSUBDIRS_ROOT:
230 if has_subdirs(os.path.join(root, path)):
231 if path == 'tmp' and atom in BAD_TMP_PACKAGES:
232 logging.warning('Ignoring known bad /tmp install for now')
233 else:
234 ret = False
235
236 # Special case /var due to so many misuses currently.
237 if has_subdirs(os.path.join(root, 'var')):
238 if atom in BAD_VAR_PACKAGES:
239 logging.warning('Ignoring known bad /var install for now')
240 elif os.environ.get('PORTAGE_REPO_NAME') == 'portage-stable':
241 logging.warning('Ignoring bad /var install with portage-stable package '
242 'for now')
243 else:
244 ret = False
245 else:
246 if atom in BAD_VAR_PACKAGES:
247 logging.warning('Package has improved; please update BAD_VAR_PACKAGES')
248
249 # Special case /run due to so many misuses currently.
250 if has_subdirs(os.path.join(root, 'run')):
251 if atom in BAD_RUN_PACKAGES:
252 logging.warning('Ignoring known bad /run install for now')
253 elif os.environ.get('PORTAGE_REPO_NAME') == 'portage-stable':
254 logging.warning('Ignoring bad /run install with portage-stable package '
255 'for now')
256 else:
257 ret = False
258 else:
259 if atom in BAD_RUN_PACKAGES:
260 logging.warning('Package has improved; please update BAD_RUN_PACKAGES')
261
262 if not check_usr(os.path.join(root, 'usr'), host):
263 ret = False
264
265 return ret
266
267
268def get_current_package():
269 """Figure out what package is being built currently."""
270 if 'CATEGORY' in os.environ and 'PN' in os.environ:
271 return f'{os.environ.get("CATEGORY")}/{os.environ.get("PN")}'
272 else:
273 return None
274
275
276def get_parser():
277 """Get a CLI parser."""
278 parser = argparse.ArgumentParser(description=__doc__)
279 parser.add_argument('--host', default=None, action='store_true',
280 help='the filesystem is the host SDK, not board sysroot')
281 parser.add_argument('--board', dest='host', action='store_false',
282 help='the filesystem is a board sysroot')
283 parser.add_argument('root', nargs='?',
284 help='the rootfs to scan')
285 return parser
286
287
288def main(argv):
289 """The main func!"""
290 parser = get_parser()
291 opts = parser.parse_args(argv)
292
293 # Default to common portage env vars.
294 if opts.root is None:
295 for var in ('ED', 'D', 'ROOT'):
296 if var in os.environ:
297 logging.debug('Scanning filesystem root via $%s', var)
298 opts.root = os.environ[var]
299 break
300 if not opts.root:
301 parser.error('Need a valid rootfs to scan, but unable to detect one')
302
303 if opts.host is None:
304 if os.getenv('BOARD') == 'amd64-host':
305 opts.host = True
306 else:
307 opts.host = not bool(os.getenv('SYSROOT'))
308
309 if not check_root(opts.root, opts.host):
310 logging.critical(
311 "This package does not conform to CrOS's filesystem conventions. "
312 'Please review the paths flagged above and adjust its layout.')
313 return 1
314 else:
315 return 0
316
317
318if __name__ == '__main__':
319 sys.exit(main(sys.argv[1:]))