xref: /OK3568_Linux_fs/yocto/poky/meta/classes/rootfs-postcommands.bbclass (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1
2# Zap the root password if debug-tweaks and empty-root-password features are not enabled
3ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains_any("IMAGE_FEATURES", [ 'debug-tweaks', 'empty-root-password' ], "", "zap_empty_root_password; ",d)}'
4
5# Allow dropbear/openssh to accept logins from accounts with an empty password string if debug-tweaks or allow-empty-password is enabled
6ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains_any("IMAGE_FEATURES", [ 'debug-tweaks', 'allow-empty-password' ], "ssh_allow_empty_password; ", "",d)}'
7
8# Allow dropbear/openssh to accept root logins if debug-tweaks or allow-root-login is enabled
9ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains_any("IMAGE_FEATURES", [ 'debug-tweaks', 'allow-root-login' ], "ssh_allow_root_login; ", "",d)}'
10
11# Enable postinst logging if debug-tweaks or post-install-logging is enabled
12ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains_any("IMAGE_FEATURES", [ 'debug-tweaks', 'post-install-logging' ], "postinst_enable_logging; ", "",d)}'
13
14# Create /etc/timestamp during image construction to give a reasonably sane default time setting
15ROOTFS_POSTPROCESS_COMMAND += "rootfs_update_timestamp; "
16
17# Tweak files in /etc if read-only-rootfs is enabled
18ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains("IMAGE_FEATURES", "read-only-rootfs", "read_only_rootfs_hook; ", "",d)}'
19
20# We also need to do the same for the kernel boot parameters,
21# otherwise kernel or initramfs end up mounting the rootfs read/write
22# (the default) if supported by the underlying storage.
23#
24# We do this with :append because the default value might get set later with ?=
25# and we don't want to disable such a default that by setting a value here.
26APPEND:append = '${@bb.utils.contains("IMAGE_FEATURES", "read-only-rootfs", " ro", "", d)}'
27
28# Generates test data file with data store variables expanded in json format
29ROOTFS_POSTPROCESS_COMMAND += "write_image_test_data; "
30
31# Write manifest
32IMAGE_MANIFEST = "${IMGDEPLOYDIR}/${IMAGE_NAME}${IMAGE_NAME_SUFFIX}.manifest"
33ROOTFS_POSTUNINSTALL_COMMAND =+ "write_image_manifest ; "
34# Set default postinst log file
35POSTINST_LOGFILE ?= "${localstatedir}/log/postinstall.log"
36# Set default target for systemd images
37SYSTEMD_DEFAULT_TARGET ?= '${@bb.utils.contains_any("IMAGE_FEATURES", [ "x11-base", "weston" ], "graphical.target", "multi-user.target", d)}'
38ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains("DISTRO_FEATURES", "systemd", "set_systemd_default_target; systemd_create_users;", "", d)}'
39
40ROOTFS_POSTPROCESS_COMMAND += 'empty_var_volatile;'
41
42ROOTFS_POSTPROCESS_COMMAND += '${@bb.utils.contains("DISTRO_FEATURES", "overlayfs", "overlayfs_qa_check;", "", d)}'
43
44inherit image-artifact-names
45
46# Sort the user and group entries in /etc by ID in order to make the content
47# deterministic. Package installs are not deterministic, causing the ordering
48# of entries to change between builds. In case that this isn't desired,
49# the command can be overridden.
50#
51# Note that useradd-staticids.bbclass has to be used to ensure that
52# the numeric IDs of dynamically created entries remain stable.
53#
54# We want this to run as late as possible, in particular after
55# systemd_sysusers_create and set_user_group. Using :append is not
56# enough for that, set_user_group is added that way and would end
57# up running after us.
58SORT_PASSWD_POSTPROCESS_COMMAND ??= " sort_passwd; "
59python () {
60    d.appendVar('ROOTFS_POSTPROCESS_COMMAND', '${SORT_PASSWD_POSTPROCESS_COMMAND}')
61    d.appendVar('ROOTFS_POSTPROCESS_COMMAND', 'rootfs_reproducible;')
62}
63
64systemd_create_users () {
65	for conffile in ${IMAGE_ROOTFS}/usr/lib/sysusers.d/*.conf; do
66		[ -e $conffile ] || continue
67		grep -v "^#" $conffile | sed -e '/^$/d' | while read type name id comment; do
68		if [ "$type" = "u" ]; then
69			useradd_params="--shell /sbin/nologin"
70			[ "$id" != "-" ] && useradd_params="$useradd_params --uid $id"
71			[ "$comment" != "-" ] && useradd_params="$useradd_params --comment $comment"
72			useradd_params="$useradd_params --system $name"
73			eval useradd --root ${IMAGE_ROOTFS} $useradd_params || true
74		elif [ "$type" = "g" ]; then
75			groupadd_params=""
76			[ "$id" != "-" ] && groupadd_params="$groupadd_params --gid $id"
77			groupadd_params="$groupadd_params --system $name"
78			eval groupadd --root ${IMAGE_ROOTFS} $groupadd_params || true
79		elif [ "$type" = "m" ]; then
80			group=$id
81			eval groupadd --root ${IMAGE_ROOTFS} --system $group || true
82			eval useradd --root ${IMAGE_ROOTFS} --shell /sbin/nologin --system $name --no-user-group || true
83			eval usermod --root ${IMAGE_ROOTFS} -a -G $group $name
84		fi
85		done
86	done
87}
88
89#
90# A hook function to support read-only-rootfs IMAGE_FEATURES
91#
92read_only_rootfs_hook () {
93	# Tweak the mount option and fs_passno for rootfs in fstab
94	if [ -f ${IMAGE_ROOTFS}/etc/fstab ]; then
95		sed -i -e '/^[#[:space:]]*\/dev\/root/{s/defaults/ro/;s/\([[:space:]]*[[:digit:]]\)\([[:space:]]*\)[[:digit:]]$/\1\20/}' ${IMAGE_ROOTFS}/etc/fstab
96	fi
97
98	# Tweak the "mount -o remount,rw /" command in busybox-inittab inittab
99	if [ -f ${IMAGE_ROOTFS}/etc/inittab ]; then
100		sed -i 's|/bin/mount -o remount,rw /|/bin/mount -o remount,ro /|' ${IMAGE_ROOTFS}/etc/inittab
101	fi
102
103	# If we're using openssh and the /etc/ssh directory has no pre-generated keys,
104	# we should configure openssh to use the configuration file /etc/ssh/sshd_config_readonly
105	# and the keys under /var/run/ssh.
106	# If overlayfs-etc is used this is not done as /etc is treated as writable
107	# If stateless-rootfs is enabled this is always done as we don't want to save keys then
108	if ${@ 'true' if not bb.utils.contains('IMAGE_FEATURES', 'overlayfs-etc', True, False, d) or bb.utils.contains('IMAGE_FEATURES', 'stateless-rootfs', True, False, d) else 'false'}; then
109		if [ -d ${IMAGE_ROOTFS}/etc/ssh ]; then
110			if [ -e ${IMAGE_ROOTFS}/etc/ssh/ssh_host_rsa_key ]; then
111				echo "SYSCONFDIR=\${SYSCONFDIR:-/etc/ssh}" >> ${IMAGE_ROOTFS}/etc/default/ssh
112				echo "SSHD_OPTS=" >> ${IMAGE_ROOTFS}/etc/default/ssh
113			else
114				echo "SYSCONFDIR=\${SYSCONFDIR:-/var/run/ssh}" >> ${IMAGE_ROOTFS}/etc/default/ssh
115				echo "SSHD_OPTS='-f /etc/ssh/sshd_config_readonly'" >> ${IMAGE_ROOTFS}/etc/default/ssh
116			fi
117		fi
118
119		# Also tweak the key location for dropbear in the same way.
120		if [ -d ${IMAGE_ROOTFS}/etc/dropbear ]; then
121			if [ ! -e ${IMAGE_ROOTFS}/etc/dropbear/dropbear_rsa_host_key ]; then
122				echo "DROPBEAR_RSAKEY_DIR=/var/lib/dropbear" >> ${IMAGE_ROOTFS}/etc/default/dropbear
123			fi
124		fi
125	fi
126
127	if ${@bb.utils.contains("DISTRO_FEATURES", "sysvinit", "true", "false", d)}; then
128		# Change the value of ROOTFS_READ_ONLY in /etc/default/rcS to yes
129		if [ -e ${IMAGE_ROOTFS}/etc/default/rcS ]; then
130			sed -i 's/ROOTFS_READ_ONLY=no/ROOTFS_READ_ONLY=yes/' ${IMAGE_ROOTFS}/etc/default/rcS
131		fi
132		# Run populate-volatile.sh at rootfs time to set up basic files
133		# and directories to support read-only rootfs.
134		if [ -x ${IMAGE_ROOTFS}/etc/init.d/populate-volatile.sh ]; then
135			${IMAGE_ROOTFS}/etc/init.d/populate-volatile.sh
136		fi
137	fi
138
139	if ${@bb.utils.contains("DISTRO_FEATURES", "systemd", "true", "false", d)}; then
140	# Create machine-id
141	# 20:12 < mezcalero> koen: you have three options: a) run systemd-machine-id-setup at install time, b) have / read-only and an empty file there (for stateless) and c) boot with / writable
142		touch ${IMAGE_ROOTFS}${sysconfdir}/machine-id
143	fi
144}
145
146#
147# This function disallows empty root passwords
148#
149zap_empty_root_password () {
150	if [ -e ${IMAGE_ROOTFS}/etc/shadow ]; then
151		sed -i 's%^root::%root:*:%' ${IMAGE_ROOTFS}/etc/shadow
152        fi
153	if [ -e ${IMAGE_ROOTFS}/etc/passwd ]; then
154		sed -i 's%^root::%root:*:%' ${IMAGE_ROOTFS}/etc/passwd
155	fi
156}
157
158#
159# allow dropbear/openssh to accept logins from accounts with an empty password string
160#
161ssh_allow_empty_password () {
162	for config in sshd_config sshd_config_readonly; do
163		if [ -e ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config ]; then
164			sed -i 's/^[#[:space:]]*PermitEmptyPasswords.*/PermitEmptyPasswords yes/' ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config
165		fi
166	done
167
168	if [ -e ${IMAGE_ROOTFS}${sbindir}/dropbear ] ; then
169		if grep -q DROPBEAR_EXTRA_ARGS ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear 2>/dev/null ; then
170			if ! grep -q "DROPBEAR_EXTRA_ARGS=.*-B" ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear ; then
171				sed -i 's/^DROPBEAR_EXTRA_ARGS="*\([^"]*\)"*/DROPBEAR_EXTRA_ARGS="\1 -B"/' ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear
172			fi
173		else
174			printf '\nDROPBEAR_EXTRA_ARGS="-B"\n' >> ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear
175		fi
176	fi
177
178	if [ -d ${IMAGE_ROOTFS}${sysconfdir}/pam.d ] ; then
179		for f in `find ${IMAGE_ROOTFS}${sysconfdir}/pam.d/* -type f -exec test -e {} \; -print`
180		do
181			sed -i 's/nullok_secure/nullok/' $f
182		done
183	fi
184}
185
186#
187# allow dropbear/openssh to accept root logins
188#
189ssh_allow_root_login () {
190	for config in sshd_config sshd_config_readonly; do
191		if [ -e ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config ]; then
192			sed -i 's/^[#[:space:]]*PermitRootLogin.*/PermitRootLogin yes/' ${IMAGE_ROOTFS}${sysconfdir}/ssh/$config
193		fi
194	done
195
196	if [ -e ${IMAGE_ROOTFS}${sbindir}/dropbear ] ; then
197		if grep -q DROPBEAR_EXTRA_ARGS ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear 2>/dev/null ; then
198			sed -i '/^DROPBEAR_EXTRA_ARGS=/ s/-w//' ${IMAGE_ROOTFS}${sysconfdir}/default/dropbear
199		fi
200	fi
201}
202
203python sort_passwd () {
204    import rootfspostcommands
205    rootfspostcommands.sort_passwd(d.expand('${IMAGE_ROOTFS}${sysconfdir}'))
206}
207
208#
209# Enable postinst logging
210#
211postinst_enable_logging () {
212	mkdir -p ${IMAGE_ROOTFS}${sysconfdir}/default
213	echo "POSTINST_LOGGING=1" >> ${IMAGE_ROOTFS}${sysconfdir}/default/postinst
214	echo "LOGFILE=${POSTINST_LOGFILE}" >> ${IMAGE_ROOTFS}${sysconfdir}/default/postinst
215}
216
217#
218# Modify systemd default target
219#
220set_systemd_default_target () {
221	if [ -d ${IMAGE_ROOTFS}${sysconfdir}/systemd/system -a -e ${IMAGE_ROOTFS}${systemd_system_unitdir}/${SYSTEMD_DEFAULT_TARGET} ]; then
222		ln -sf ${systemd_system_unitdir}/${SYSTEMD_DEFAULT_TARGET} ${IMAGE_ROOTFS}${sysconfdir}/systemd/system/default.target
223	fi
224}
225
226# If /var/volatile is not empty, we have seen problems where programs such as the
227# journal make assumptions based on the contents of /var/volatile. The journal
228# would then write to /var/volatile before it was mounted, thus hiding the
229# items previously written.
230#
231# This change is to attempt to fix those types of issues in a way that doesn't
232# affect users that may not be using /var/volatile.
233empty_var_volatile () {
234	if [ -e ${IMAGE_ROOTFS}/etc/fstab ]; then
235		match=`awk '$1 !~ "#" && $2 ~ /\/var\/volatile/{print $2}' ${IMAGE_ROOTFS}/etc/fstab 2> /dev/null`
236		if [ -n "$match" ]; then
237			find ${IMAGE_ROOTFS}/var/volatile -mindepth 1 -delete
238		fi
239	fi
240}
241
242# Turn any symbolic /sbin/init link into a file
243remove_init_link () {
244	if [ -h ${IMAGE_ROOTFS}/sbin/init ]; then
245		LINKFILE=${IMAGE_ROOTFS}`readlink ${IMAGE_ROOTFS}/sbin/init`
246		rm ${IMAGE_ROOTFS}/sbin/init
247		cp $LINKFILE ${IMAGE_ROOTFS}/sbin/init
248	fi
249}
250
251make_zimage_symlink_relative () {
252	if [ -L ${IMAGE_ROOTFS}/boot/zImage ]; then
253		(cd ${IMAGE_ROOTFS}/boot/ && for i in `ls zImage-* | sort`; do ln -sf $i zImage; done)
254	fi
255}
256
257python write_image_manifest () {
258    from oe.rootfs import image_list_installed_packages
259    from oe.utils import format_pkg_list
260
261    deploy_dir = d.getVar('IMGDEPLOYDIR')
262    link_name = d.getVar('IMAGE_LINK_NAME')
263    manifest_name = d.getVar('IMAGE_MANIFEST')
264
265    if not manifest_name:
266        return
267
268    pkgs = image_list_installed_packages(d)
269    with open(manifest_name, 'w+') as image_manifest:
270        image_manifest.write(format_pkg_list(pkgs, "ver"))
271
272    if os.path.exists(manifest_name) and link_name:
273        manifest_link = deploy_dir + "/" + link_name + ".manifest"
274        if manifest_link != manifest_name:
275            if os.path.lexists(manifest_link):
276                os.remove(manifest_link)
277            os.symlink(os.path.basename(manifest_name), manifest_link)
278}
279
280# Can be used to create /etc/timestamp during image construction to give a reasonably
281# sane default time setting
282rootfs_update_timestamp () {
283	if [ "${REPRODUCIBLE_TIMESTAMP_ROOTFS}" != "" ]; then
284		# Convert UTC into %4Y%2m%2d%2H%2M%2S
285		sformatted=`date -u -d @${REPRODUCIBLE_TIMESTAMP_ROOTFS} +%4Y%2m%2d%2H%2M%2S`
286	else
287		sformatted=`date -u +%4Y%2m%2d%2H%2M%2S`
288	fi
289	echo $sformatted > ${IMAGE_ROOTFS}/etc/timestamp
290	bbnote "rootfs_update_timestamp: set /etc/timestamp to $sformatted"
291}
292
293# Prevent X from being started
294rootfs_no_x_startup () {
295	if [ -f ${IMAGE_ROOTFS}/etc/init.d/xserver-nodm ]; then
296		chmod a-x ${IMAGE_ROOTFS}/etc/init.d/xserver-nodm
297	fi
298}
299
300rootfs_trim_schemas () {
301	for schema in ${IMAGE_ROOTFS}/etc/gconf/schemas/*.schemas
302	do
303		# Need this in case no files exist
304		if [ -e $schema ]; then
305			oe-trim-schemas $schema > $schema.new
306			mv $schema.new $schema
307		fi
308	done
309}
310
311rootfs_check_host_user_contaminated () {
312	contaminated="${S}/host-user-contaminated.txt"
313	HOST_USER_UID="$(PSEUDO_UNLOAD=1 id -u)"
314	HOST_USER_GID="$(PSEUDO_UNLOAD=1 id -g)"
315
316	find "${IMAGE_ROOTFS}" -path "${IMAGE_ROOTFS}/home" -prune -o \
317	    -user "$HOST_USER_UID" -print -o -group "$HOST_USER_GID" -print >"$contaminated"
318
319	sed -e "s,${IMAGE_ROOTFS},," $contaminated | while read line; do
320		bbwarn "Path in the rootfs is owned by the same user or group as the user running bitbake:" $line `ls -lan ${IMAGE_ROOTFS}/$line`
321	done
322
323	if [ -s "$contaminated" ]; then
324		bbwarn "/etc/passwd:" `cat ${IMAGE_ROOTFS}/etc/passwd`
325		bbwarn "/etc/group:" `cat ${IMAGE_ROOTFS}/etc/group`
326	fi
327}
328
329# Make any absolute links in a sysroot relative
330rootfs_sysroot_relativelinks () {
331	sysroot-relativelinks.py ${SDK_OUTPUT}/${SDKTARGETSYSROOT}
332}
333
334# Generated test data json file
335python write_image_test_data() {
336    from oe.data import export2json
337
338    deploy_dir = d.getVar('IMGDEPLOYDIR')
339    link_name = d.getVar('IMAGE_LINK_NAME')
340    testdata_name = os.path.join(deploy_dir, "%s.testdata.json" % d.getVar('IMAGE_NAME'))
341
342    searchString = "%s/"%(d.getVar("TOPDIR")).replace("//","/")
343    export2json(d, testdata_name, searchString=searchString, replaceString="")
344
345    if os.path.exists(testdata_name) and link_name:
346        testdata_link = os.path.join(deploy_dir, "%s.testdata.json" % link_name)
347        if testdata_link != testdata_name:
348            if os.path.lexists(testdata_link):
349                os.remove(testdata_link)
350            os.symlink(os.path.basename(testdata_name), testdata_link)
351}
352write_image_test_data[vardepsexclude] += "TOPDIR"
353
354# Check for unsatisfied recommendations (RRECOMMENDS)
355python rootfs_log_check_recommends() {
356    log_path = d.expand("${T}/log.do_rootfs")
357    with open(log_path, 'r') as log:
358        for line in log:
359            if 'log_check' in line:
360                continue
361
362            if 'unsatisfied recommendation for' in line:
363                bb.warn('[log_check] %s: %s' % (d.getVar('PN'), line))
364}
365
366# Perform any additional adjustments needed to make rootf binary reproducible
367rootfs_reproducible () {
368	if [ "${REPRODUCIBLE_TIMESTAMP_ROOTFS}" != "" ]; then
369		# Convert UTC into %4Y%2m%2d%2H%2M%2S
370		sformatted=`date -u -d @${REPRODUCIBLE_TIMESTAMP_ROOTFS} +%4Y%2m%2d%2H%2M%2S`
371		echo $sformatted > ${IMAGE_ROOTFS}/etc/version
372		bbnote "rootfs_reproducible: set /etc/version to $sformatted"
373
374		if [ -d ${IMAGE_ROOTFS}${sysconfdir}/gconf ]; then
375			find ${IMAGE_ROOTFS}${sysconfdir}/gconf -name '%gconf.xml' -print0 | xargs -0r \
376			sed -i -e 's@\bmtime="[0-9][0-9]*"@mtime="'${REPRODUCIBLE_TIMESTAMP_ROOTFS}'"@g'
377		fi
378	fi
379}
380
381# Perform a dumb check for unit existence, not its validity
382python overlayfs_qa_check() {
383    from oe.overlayfs import mountUnitName
384
385    overlayMountPoints = d.getVarFlags("OVERLAYFS_MOUNT_POINT") or {}
386    imagepath = d.getVar("IMAGE_ROOTFS")
387    sysconfdir = d.getVar("sysconfdir")
388    searchpaths = [oe.path.join(imagepath, sysconfdir, "systemd", "system"),
389                   oe.path.join(imagepath, d.getVar("systemd_system_unitdir"))]
390    fstabpath = oe.path.join(imagepath, sysconfdir, "fstab")
391
392    if not any(os.path.exists(path) for path in [*searchpaths, fstabpath]):
393        return
394
395    fstabDevices = []
396    if os.path.isfile(fstabpath):
397        with open(fstabpath, 'r') as f:
398            for line in f:
399                if line[0] == '#':
400                    continue
401                path = line.split(maxsplit=2)
402                if len(path) > 2:
403                    fstabDevices.append(path[1])
404
405    allUnitExist = True;
406    for mountPoint in overlayMountPoints:
407        qaSkip = (d.getVarFlag("OVERLAYFS_QA_SKIP", mountPoint) or "").split()
408        if "mount-configured" in qaSkip:
409            continue
410
411        mountPath = d.getVarFlag('OVERLAYFS_MOUNT_POINT', mountPoint)
412        if mountPath in fstabDevices:
413            continue
414
415        mountUnit = mountUnitName(mountPath)
416        if any(os.path.isfile(oe.path.join(dirpath, mountUnit))
417               for dirpath in searchpaths):
418            continue
419
420        bb.warn(f'Mount path {mountPath} not found in fstab and unit '
421                f'{mountUnit} not found in systemd unit directories.')
422        bb.warn(f'Skip this check by setting OVERLAYFS_QA_SKIP[{mountPoint}] = '
423                '"mount-configured"')
424        allUnitExist = False;
425
426    if not allUnitExist:
427        bb.fatal('Not all mount paths and units are installed in the image')
428}
429