blob: 2b580f9053e48b9bc97ad428878ce0772b6f40b9 [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',
142 'chromeos-base/cros-config-test',
143}
144
145
146def has_subdirs(path):
147 """See if |path| has any subdirs."""
148 # These checks are helpful for manually running the script when debugging.
149 if os.path.ismount(path):
150 logging.warning('Ignoring mounted dir for subdir check: %s', path)
151 return False
152
153 if os.path.join(os.getenv('SYSROOT', '/'), 'tmp') == path:
154 logging.warning('Ignoring live dir: %s', path)
155 return False
156
157 for _, dirs, _ in os.walk(path):
158 if dirs:
159 logging.error('Subdirs found in a dir that should be empty:\n %s\n'
160 ' |-- %s', path, '\n |-- '.join(sorted(dirs)))
161 return True
162 break
163
164 return False
165
166
167def check_usr(usr, host=False):
168 """Check the /usr filesystem at |usr|."""
169 ret = True
170
171 # Not all packages install into /usr.
172 if not os.path.exists(usr):
173 return ret
174
175 atom = get_current_package()
176 paths = set(os.listdir(usr))
177 unknown = paths - VALID_USR
178 for target in KNOWN_TARGETS:
179 unknown = set(x for x in unknown if not fnmatch.fnmatch(x, target))
180 if host:
181 unknown -= VALID_HOST_USR
182
183 if atom in BAD_HOST_USR_LOCAL_PACKAGES:
184 logging.warning('Ignoring known bad /usr/local install for now')
185 unknown -= {'local'}
186 else:
187 unknown -= VALID_BOARD_USR
188
189 if atom in {'chromeos-base/ap-daemons'}:
190 logging.warning('Ignoring known bad /usr install for now')
191 unknown -= {'www'}
192
193 if unknown:
194 logging.error('Paths are not allowed in the /usr dir: %s', sorted(unknown))
195 ret = False
196
197 for path in NOSUBDIRS_USR:
198 if has_subdirs(os.path.join(usr, path)):
199 ret = False
200
201 return ret
202
203
204def check_root(root, host=False):
205 """Check the filesystem |root|."""
206 ret = True
207
208 atom = get_current_package()
209 paths = set(os.listdir(root))
210 unknown = paths - VALID_ROOT
211 if host:
212 unknown -= VALID_HOST_ROOT
213 else:
214 unknown -= VALID_BOARD_ROOT
215
216 if atom in BAD_ROOT_PACKAGES:
217 logging.warning('Ignoring known bad / install for now')
218 elif unknown:
219 logging.error('Paths are not allowed in the root dir:\n %s\n |-- %s',
220 root, '\n |-- '.join(sorted(unknown)))
221 ret = False
222
223 # Some of these may have subdirs at runtime, but not from package installs.
224 for path in NOSUBDIRS_ROOT:
225 if has_subdirs(os.path.join(root, path)):
226 if path == 'tmp' and atom in BAD_TMP_PACKAGES:
227 logging.warning('Ignoring known bad /tmp install for now')
228 else:
229 ret = False
230
231 # Special case /var due to so many misuses currently.
232 if has_subdirs(os.path.join(root, 'var')):
233 if atom in BAD_VAR_PACKAGES:
234 logging.warning('Ignoring known bad /var install for now')
235 elif os.environ.get('PORTAGE_REPO_NAME') == 'portage-stable':
236 logging.warning('Ignoring bad /var install with portage-stable package '
237 'for now')
238 else:
239 ret = False
240 else:
241 if atom in BAD_VAR_PACKAGES:
242 logging.warning('Package has improved; please update BAD_VAR_PACKAGES')
243
244 # Special case /run due to so many misuses currently.
245 if has_subdirs(os.path.join(root, 'run')):
246 if atom in BAD_RUN_PACKAGES:
247 logging.warning('Ignoring known bad /run install for now')
248 elif os.environ.get('PORTAGE_REPO_NAME') == 'portage-stable':
249 logging.warning('Ignoring bad /run install with portage-stable package '
250 'for now')
251 else:
252 ret = False
253 else:
254 if atom in BAD_RUN_PACKAGES:
255 logging.warning('Package has improved; please update BAD_RUN_PACKAGES')
256
257 if not check_usr(os.path.join(root, 'usr'), host):
258 ret = False
259
260 return ret
261
262
263def get_current_package():
264 """Figure out what package is being built currently."""
265 if 'CATEGORY' in os.environ and 'PN' in os.environ:
266 return f'{os.environ.get("CATEGORY")}/{os.environ.get("PN")}'
267 else:
268 return None
269
270
271def get_parser():
272 """Get a CLI parser."""
273 parser = argparse.ArgumentParser(description=__doc__)
274 parser.add_argument('--host', default=None, action='store_true',
275 help='the filesystem is the host SDK, not board sysroot')
276 parser.add_argument('--board', dest='host', action='store_false',
277 help='the filesystem is a board sysroot')
278 parser.add_argument('root', nargs='?',
279 help='the rootfs to scan')
280 return parser
281
282
283def main(argv):
284 """The main func!"""
285 parser = get_parser()
286 opts = parser.parse_args(argv)
287
288 # Default to common portage env vars.
289 if opts.root is None:
290 for var in ('ED', 'D', 'ROOT'):
291 if var in os.environ:
292 logging.debug('Scanning filesystem root via $%s', var)
293 opts.root = os.environ[var]
294 break
295 if not opts.root:
296 parser.error('Need a valid rootfs to scan, but unable to detect one')
297
298 if opts.host is None:
299 if os.getenv('BOARD') == 'amd64-host':
300 opts.host = True
301 else:
302 opts.host = not bool(os.getenv('SYSROOT'))
303
304 if not check_root(opts.root, opts.host):
305 logging.critical(
306 "This package does not conform to CrOS's filesystem conventions. "
307 'Please review the paths flagged above and adjust its layout.')
308 return 1
309 else:
310 return 0
311
312
313if __name__ == '__main__':
314 sys.exit(main(sys.argv[1:]))